prompt
large_stringlengths
72
9.34k
completion
large_stringlengths
0
7.61k
<|file_name|>sblim_sfcb.py<|end_file_name|><|fim▁begin|>#!/bin/python import os, subprocess import logging from autotest.client import test from autotest.client.shared import error, software_manager sm = software_manager.SoftwareManager() class sblim_sfcb(test.test): """ Autotest module for testing basic functionality of sblim_sfcb @author Wang Tao <[email protected]> """ version = 1 nfail = 0 path = '' def initialize(self, test_path=''): """ Sets the overall failure counter for the test. """ self.nfail = 0 if not sm.check_installed('gcc'): logging.debug("gcc missing - trying to install") sm.install('gcc') ret_val = subprocess.Popen(['make', 'all'], cwd="%s/sblim_sfcb" %(test_path)) ret_val.communicate() if ret_val.returncode != 0: self.nfail += 1 logging.info('\n Test initialize successfully') def run_once(self, test_path=''): """ Trigger test run """ try: os.environ["LTPBIN"] = "%s/shared" %(test_path) ret_val = subprocess.Popen(['./sblim-sfcb-test.sh'], cwd="%s/sblim_sfcb" %(test_path)) ret_val.communicate() if ret_val.returncode != 0: self.nfail += 1 except error.CmdError, e: self.nfail += 1 logging.error("Test Failed: %s", e) def postprocess(self): if self.nfail != 0: <|fim_middle|> else: logging.info('\n Test completed successfully ') <|fim▁end|>
logging.info('\n nfails is non-zero') raise error.TestError('\nTest failed')
<|file_name|>sblim_sfcb.py<|end_file_name|><|fim▁begin|>#!/bin/python import os, subprocess import logging from autotest.client import test from autotest.client.shared import error, software_manager sm = software_manager.SoftwareManager() class sblim_sfcb(test.test): """ Autotest module for testing basic functionality of sblim_sfcb @author Wang Tao <[email protected]> """ version = 1 nfail = 0 path = '' def initialize(self, test_path=''): """ Sets the overall failure counter for the test. """ self.nfail = 0 if not sm.check_installed('gcc'): logging.debug("gcc missing - trying to install") sm.install('gcc') ret_val = subprocess.Popen(['make', 'all'], cwd="%s/sblim_sfcb" %(test_path)) ret_val.communicate() if ret_val.returncode != 0: self.nfail += 1 logging.info('\n Test initialize successfully') def run_once(self, test_path=''): """ Trigger test run """ try: os.environ["LTPBIN"] = "%s/shared" %(test_path) ret_val = subprocess.Popen(['./sblim-sfcb-test.sh'], cwd="%s/sblim_sfcb" %(test_path)) ret_val.communicate() if ret_val.returncode != 0: self.nfail += 1 except error.CmdError, e: self.nfail += 1 logging.error("Test Failed: %s", e) def postprocess(self): if self.nfail != 0: logging.info('\n nfails is non-zero') raise error.TestError('\nTest failed') else: <|fim_middle|> <|fim▁end|>
logging.info('\n Test completed successfully ')
<|file_name|>sblim_sfcb.py<|end_file_name|><|fim▁begin|>#!/bin/python import os, subprocess import logging from autotest.client import test from autotest.client.shared import error, software_manager sm = software_manager.SoftwareManager() class sblim_sfcb(test.test): """ Autotest module for testing basic functionality of sblim_sfcb @author Wang Tao <[email protected]> """ version = 1 nfail = 0 path = '' def <|fim_middle|>(self, test_path=''): """ Sets the overall failure counter for the test. """ self.nfail = 0 if not sm.check_installed('gcc'): logging.debug("gcc missing - trying to install") sm.install('gcc') ret_val = subprocess.Popen(['make', 'all'], cwd="%s/sblim_sfcb" %(test_path)) ret_val.communicate() if ret_val.returncode != 0: self.nfail += 1 logging.info('\n Test initialize successfully') def run_once(self, test_path=''): """ Trigger test run """ try: os.environ["LTPBIN"] = "%s/shared" %(test_path) ret_val = subprocess.Popen(['./sblim-sfcb-test.sh'], cwd="%s/sblim_sfcb" %(test_path)) ret_val.communicate() if ret_val.returncode != 0: self.nfail += 1 except error.CmdError, e: self.nfail += 1 logging.error("Test Failed: %s", e) def postprocess(self): if self.nfail != 0: logging.info('\n nfails is non-zero') raise error.TestError('\nTest failed') else: logging.info('\n Test completed successfully ') <|fim▁end|>
initialize
<|file_name|>sblim_sfcb.py<|end_file_name|><|fim▁begin|>#!/bin/python import os, subprocess import logging from autotest.client import test from autotest.client.shared import error, software_manager sm = software_manager.SoftwareManager() class sblim_sfcb(test.test): """ Autotest module for testing basic functionality of sblim_sfcb @author Wang Tao <[email protected]> """ version = 1 nfail = 0 path = '' def initialize(self, test_path=''): """ Sets the overall failure counter for the test. """ self.nfail = 0 if not sm.check_installed('gcc'): logging.debug("gcc missing - trying to install") sm.install('gcc') ret_val = subprocess.Popen(['make', 'all'], cwd="%s/sblim_sfcb" %(test_path)) ret_val.communicate() if ret_val.returncode != 0: self.nfail += 1 logging.info('\n Test initialize successfully') def <|fim_middle|>(self, test_path=''): """ Trigger test run """ try: os.environ["LTPBIN"] = "%s/shared" %(test_path) ret_val = subprocess.Popen(['./sblim-sfcb-test.sh'], cwd="%s/sblim_sfcb" %(test_path)) ret_val.communicate() if ret_val.returncode != 0: self.nfail += 1 except error.CmdError, e: self.nfail += 1 logging.error("Test Failed: %s", e) def postprocess(self): if self.nfail != 0: logging.info('\n nfails is non-zero') raise error.TestError('\nTest failed') else: logging.info('\n Test completed successfully ') <|fim▁end|>
run_once
<|file_name|>sblim_sfcb.py<|end_file_name|><|fim▁begin|>#!/bin/python import os, subprocess import logging from autotest.client import test from autotest.client.shared import error, software_manager sm = software_manager.SoftwareManager() class sblim_sfcb(test.test): """ Autotest module for testing basic functionality of sblim_sfcb @author Wang Tao <[email protected]> """ version = 1 nfail = 0 path = '' def initialize(self, test_path=''): """ Sets the overall failure counter for the test. """ self.nfail = 0 if not sm.check_installed('gcc'): logging.debug("gcc missing - trying to install") sm.install('gcc') ret_val = subprocess.Popen(['make', 'all'], cwd="%s/sblim_sfcb" %(test_path)) ret_val.communicate() if ret_val.returncode != 0: self.nfail += 1 logging.info('\n Test initialize successfully') def run_once(self, test_path=''): """ Trigger test run """ try: os.environ["LTPBIN"] = "%s/shared" %(test_path) ret_val = subprocess.Popen(['./sblim-sfcb-test.sh'], cwd="%s/sblim_sfcb" %(test_path)) ret_val.communicate() if ret_val.returncode != 0: self.nfail += 1 except error.CmdError, e: self.nfail += 1 logging.error("Test Failed: %s", e) def <|fim_middle|>(self): if self.nfail != 0: logging.info('\n nfails is non-zero') raise error.TestError('\nTest failed') else: logging.info('\n Test completed successfully ') <|fim▁end|>
postprocess
<|file_name|>Example_Dudko_Fit.py<|end_file_name|><|fim▁begin|># force floating point division. Can still use integer with //<|fim▁hole|>import numpy as np import matplotlib.pyplot as plt import sys sys.path.append("../../../../../") from EnergyLandscapes.Lifetime_Dudko2008.Python.TestExamples.Util import \ Example_Data def PlotFit(data,BaseName): fig = Example_Data.PlotHistograms(data) fig.savefig(BaseName + "_Histogram.png") fig = Example_Data.PlotLifetimesAndFit(data) fig.savefig(BaseName + "_Lifetimes.png") def run(): """ """ # figure 1 from dudko 2008 data = Example_Data.Dudko2008Fig1_Probabilities() PlotFit(data,"../Out/Dudko2008_Fig1") # figure 2 frm dudko 2008 data = Example_Data.Dudko2008Fig2_Probabilities() PlotFit(data,"../Out/Dudko2008_Fig2") if __name__ == "__main__": run()<|fim▁end|>
from __future__ import division # This file is used for importing the common utilities classes.
<|file_name|>Example_Dudko_Fit.py<|end_file_name|><|fim▁begin|># force floating point division. Can still use integer with // from __future__ import division # This file is used for importing the common utilities classes. import numpy as np import matplotlib.pyplot as plt import sys sys.path.append("../../../../../") from EnergyLandscapes.Lifetime_Dudko2008.Python.TestExamples.Util import \ Example_Data def PlotFit(data,BaseName): <|fim_middle|> def run(): """ """ # figure 1 from dudko 2008 data = Example_Data.Dudko2008Fig1_Probabilities() PlotFit(data,"../Out/Dudko2008_Fig1") # figure 2 frm dudko 2008 data = Example_Data.Dudko2008Fig2_Probabilities() PlotFit(data,"../Out/Dudko2008_Fig2") if __name__ == "__main__": run() <|fim▁end|>
fig = Example_Data.PlotHistograms(data) fig.savefig(BaseName + "_Histogram.png") fig = Example_Data.PlotLifetimesAndFit(data) fig.savefig(BaseName + "_Lifetimes.png")
<|file_name|>Example_Dudko_Fit.py<|end_file_name|><|fim▁begin|># force floating point division. Can still use integer with // from __future__ import division # This file is used for importing the common utilities classes. import numpy as np import matplotlib.pyplot as plt import sys sys.path.append("../../../../../") from EnergyLandscapes.Lifetime_Dudko2008.Python.TestExamples.Util import \ Example_Data def PlotFit(data,BaseName): fig = Example_Data.PlotHistograms(data) fig.savefig(BaseName + "_Histogram.png") fig = Example_Data.PlotLifetimesAndFit(data) fig.savefig(BaseName + "_Lifetimes.png") def run(): <|fim_middle|> if __name__ == "__main__": run() <|fim▁end|>
""" """ # figure 1 from dudko 2008 data = Example_Data.Dudko2008Fig1_Probabilities() PlotFit(data,"../Out/Dudko2008_Fig1") # figure 2 frm dudko 2008 data = Example_Data.Dudko2008Fig2_Probabilities() PlotFit(data,"../Out/Dudko2008_Fig2")
<|file_name|>Example_Dudko_Fit.py<|end_file_name|><|fim▁begin|># force floating point division. Can still use integer with // from __future__ import division # This file is used for importing the common utilities classes. import numpy as np import matplotlib.pyplot as plt import sys sys.path.append("../../../../../") from EnergyLandscapes.Lifetime_Dudko2008.Python.TestExamples.Util import \ Example_Data def PlotFit(data,BaseName): fig = Example_Data.PlotHistograms(data) fig.savefig(BaseName + "_Histogram.png") fig = Example_Data.PlotLifetimesAndFit(data) fig.savefig(BaseName + "_Lifetimes.png") def run(): """ """ # figure 1 from dudko 2008 data = Example_Data.Dudko2008Fig1_Probabilities() PlotFit(data,"../Out/Dudko2008_Fig1") # figure 2 frm dudko 2008 data = Example_Data.Dudko2008Fig2_Probabilities() PlotFit(data,"../Out/Dudko2008_Fig2") if __name__ == "__main__": <|fim_middle|> <|fim▁end|>
run()
<|file_name|>Example_Dudko_Fit.py<|end_file_name|><|fim▁begin|># force floating point division. Can still use integer with // from __future__ import division # This file is used for importing the common utilities classes. import numpy as np import matplotlib.pyplot as plt import sys sys.path.append("../../../../../") from EnergyLandscapes.Lifetime_Dudko2008.Python.TestExamples.Util import \ Example_Data def <|fim_middle|>(data,BaseName): fig = Example_Data.PlotHistograms(data) fig.savefig(BaseName + "_Histogram.png") fig = Example_Data.PlotLifetimesAndFit(data) fig.savefig(BaseName + "_Lifetimes.png") def run(): """ """ # figure 1 from dudko 2008 data = Example_Data.Dudko2008Fig1_Probabilities() PlotFit(data,"../Out/Dudko2008_Fig1") # figure 2 frm dudko 2008 data = Example_Data.Dudko2008Fig2_Probabilities() PlotFit(data,"../Out/Dudko2008_Fig2") if __name__ == "__main__": run() <|fim▁end|>
PlotFit
<|file_name|>Example_Dudko_Fit.py<|end_file_name|><|fim▁begin|># force floating point division. Can still use integer with // from __future__ import division # This file is used for importing the common utilities classes. import numpy as np import matplotlib.pyplot as plt import sys sys.path.append("../../../../../") from EnergyLandscapes.Lifetime_Dudko2008.Python.TestExamples.Util import \ Example_Data def PlotFit(data,BaseName): fig = Example_Data.PlotHistograms(data) fig.savefig(BaseName + "_Histogram.png") fig = Example_Data.PlotLifetimesAndFit(data) fig.savefig(BaseName + "_Lifetimes.png") def <|fim_middle|>(): """ """ # figure 1 from dudko 2008 data = Example_Data.Dudko2008Fig1_Probabilities() PlotFit(data,"../Out/Dudko2008_Fig1") # figure 2 frm dudko 2008 data = Example_Data.Dudko2008Fig2_Probabilities() PlotFit(data,"../Out/Dudko2008_Fig2") if __name__ == "__main__": run() <|fim▁end|>
run
<|file_name|>ceph.py<|end_file_name|><|fim▁begin|># 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 os import uuid import pkg_resources from pifpaf import drivers class CephDriver(drivers.Driver): DEFAULT_PORT = 6790 def __init__(self, port=DEFAULT_PORT, **kwargs): """Create a new Ceph cluster.""" super(CephDriver, self).__init__(**kwargs) self.port = port @classmethod def get_options(cls): return [ {"param_decls": ["--port"], "type": int, "default": cls.DEFAULT_PORT, "help": "port to use for Ceph Monitor"}, ] def _setUp(self): super(CephDriver, self)._setUp() self._ensure_xattr_support() fsid = str(uuid.uuid4()) conffile = os.path.join(self.tempdir, "ceph.conf") mondir = os.path.join(self.tempdir, "mon", "ceph-a") osddir = os.path.join(self.tempdir, "osd", "ceph-0") os.makedirs(mondir) os.makedirs(osddir) _, version = self._exec(["ceph", "--version"], stdout=True) version = version.decode("ascii").split()[2] version = pkg_resources.parse_version(version) if version < pkg_resources.parse_version("12.0.0"): extra = """ mon_osd_nearfull_ratio = 1 mon_osd_full_ratio = 1 osd_failsafe_nearfull_ratio = 1 osd_failsafe_full_ratio = 1 """ else: extra = """ mon_allow_pool_delete = true """ # FIXME(sileht): check availible space on /dev/shm # if os.path.exists("/dev/shm") and os.access('/dev/shm', os.W_OK): # journal_path = "/dev/shm/$cluster-$id-journal"<|fim▁hole|> f.write("""[global] fsid = %(fsid)s # no auth for now auth cluster required = none auth service required = none auth client required = none ## no replica osd pool default size = 1 osd pool default min size = 1 osd crush chooseleaf type = 0 ## some default path change run dir = %(tempdir)s pid file = %(tempdir)s/$type.$id.pid admin socket = %(tempdir)s/$cluster-$name.asok mon data = %(tempdir)s/mon/$cluster-$id osd data = %(tempdir)s/osd/$cluster-$id osd journal = %(journal_path)s log file = %(tempdir)s/$cluster-$name.log mon cluster log file = %(tempdir)s/$cluster.log # Only omap to have same behavior for all filesystems filestore xattr use omap = True # workaround for ext4 and last Jewel version osd max object name len = 256 osd max object namespace len = 64 osd op threads = 10 filestore max sync interval = 10001 filestore min sync interval = 10000 %(extra)s journal_aio = false journal_dio = false journal zero on create = false journal block align = false # run as file owner setuser match path = %(tempdir)s/$type/$cluster-$id [mon.a] host = localhost mon addr = 127.0.0.1:%(port)d """ % dict(fsid=fsid, tempdir=self.tempdir, port=self.port, journal_path=journal_path, extra=extra)) # noqa ceph_opts = ["ceph", "-c", conffile] mon_opts = ["ceph-mon", "-c", conffile, "--id", "a", "-d"] osd_opts = ["ceph-osd", "-c", conffile, "--id", "0", "-d", "-m", "127.0.0.1:%d" % self.port] # Create and start monitor self._exec(mon_opts + ["--mkfs"]) self._touch(os.path.join(mondir, "done")) mon, _ = self._exec( mon_opts, wait_for_line=r"mon.a@0\(leader\).mds e1 print_map") # Create and start OSD self._exec(ceph_opts + ["osd", "create"]) self._exec(ceph_opts + ["osd", "crush", "add", "osd.0", "1", "root=default"]) self._exec(osd_opts + ["--mkfs", "--mkjournal"]) if version < pkg_resources.parse_version("0.94.0"): wait_for_line = "journal close" else: wait_for_line = "done with init" osd, _ = self._exec(osd_opts, wait_for_line=wait_for_line) if version >= pkg_resources.parse_version("12.0.0"): self._exec(ceph_opts + ["osd", "set-full-ratio", "0.95"]) self._exec(ceph_opts + ["osd", "set-backfillfull-ratio", "0.95"]) self._exec(ceph_opts + ["osd", "set-nearfull-ratio", "0.95"]) # Wait it's ready out = b"" while b"HEALTH_OK" not in out: ceph, out = self._exec(ceph_opts + ["health"], stdout=True) if b"HEALTH_ERR" in out: raise RuntimeError("Fail to deploy ceph") self.putenv("CEPH_CONF", conffile, True) self.putenv("CEPH_CONF", conffile) self.putenv("URL", "ceph://localhost:%d" % self.port)<|fim▁end|>
# else: journal_path = "%s/osd/$cluster-$id/journal" % self.tempdir with open(conffile, "w") as f:
<|file_name|>ceph.py<|end_file_name|><|fim▁begin|># 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 os import uuid import pkg_resources from pifpaf import drivers class CephDriver(drivers.Driver): <|fim_middle|> <|fim▁end|>
DEFAULT_PORT = 6790 def __init__(self, port=DEFAULT_PORT, **kwargs): """Create a new Ceph cluster.""" super(CephDriver, self).__init__(**kwargs) self.port = port @classmethod def get_options(cls): return [ {"param_decls": ["--port"], "type": int, "default": cls.DEFAULT_PORT, "help": "port to use for Ceph Monitor"}, ] def _setUp(self): super(CephDriver, self)._setUp() self._ensure_xattr_support() fsid = str(uuid.uuid4()) conffile = os.path.join(self.tempdir, "ceph.conf") mondir = os.path.join(self.tempdir, "mon", "ceph-a") osddir = os.path.join(self.tempdir, "osd", "ceph-0") os.makedirs(mondir) os.makedirs(osddir) _, version = self._exec(["ceph", "--version"], stdout=True) version = version.decode("ascii").split()[2] version = pkg_resources.parse_version(version) if version < pkg_resources.parse_version("12.0.0"): extra = """ mon_osd_nearfull_ratio = 1 mon_osd_full_ratio = 1 osd_failsafe_nearfull_ratio = 1 osd_failsafe_full_ratio = 1 """ else: extra = """ mon_allow_pool_delete = true """ # FIXME(sileht): check availible space on /dev/shm # if os.path.exists("/dev/shm") and os.access('/dev/shm', os.W_OK): # journal_path = "/dev/shm/$cluster-$id-journal" # else: journal_path = "%s/osd/$cluster-$id/journal" % self.tempdir with open(conffile, "w") as f: f.write("""[global] fsid = %(fsid)s # no auth for now auth cluster required = none auth service required = none auth client required = none ## no replica osd pool default size = 1 osd pool default min size = 1 osd crush chooseleaf type = 0 ## some default path change run dir = %(tempdir)s pid file = %(tempdir)s/$type.$id.pid admin socket = %(tempdir)s/$cluster-$name.asok mon data = %(tempdir)s/mon/$cluster-$id osd data = %(tempdir)s/osd/$cluster-$id osd journal = %(journal_path)s log file = %(tempdir)s/$cluster-$name.log mon cluster log file = %(tempdir)s/$cluster.log # Only omap to have same behavior for all filesystems filestore xattr use omap = True # workaround for ext4 and last Jewel version osd max object name len = 256 osd max object namespace len = 64 osd op threads = 10 filestore max sync interval = 10001 filestore min sync interval = 10000 %(extra)s journal_aio = false journal_dio = false journal zero on create = false journal block align = false # run as file owner setuser match path = %(tempdir)s/$type/$cluster-$id [mon.a] host = localhost mon addr = 127.0.0.1:%(port)d """ % dict(fsid=fsid, tempdir=self.tempdir, port=self.port, journal_path=journal_path, extra=extra)) # noqa ceph_opts = ["ceph", "-c", conffile] mon_opts = ["ceph-mon", "-c", conffile, "--id", "a", "-d"] osd_opts = ["ceph-osd", "-c", conffile, "--id", "0", "-d", "-m", "127.0.0.1:%d" % self.port] # Create and start monitor self._exec(mon_opts + ["--mkfs"]) self._touch(os.path.join(mondir, "done")) mon, _ = self._exec( mon_opts, wait_for_line=r"mon.a@0\(leader\).mds e1 print_map") # Create and start OSD self._exec(ceph_opts + ["osd", "create"]) self._exec(ceph_opts + ["osd", "crush", "add", "osd.0", "1", "root=default"]) self._exec(osd_opts + ["--mkfs", "--mkjournal"]) if version < pkg_resources.parse_version("0.94.0"): wait_for_line = "journal close" else: wait_for_line = "done with init" osd, _ = self._exec(osd_opts, wait_for_line=wait_for_line) if version >= pkg_resources.parse_version("12.0.0"): self._exec(ceph_opts + ["osd", "set-full-ratio", "0.95"]) self._exec(ceph_opts + ["osd", "set-backfillfull-ratio", "0.95"]) self._exec(ceph_opts + ["osd", "set-nearfull-ratio", "0.95"]) # Wait it's ready out = b"" while b"HEALTH_OK" not in out: ceph, out = self._exec(ceph_opts + ["health"], stdout=True) if b"HEALTH_ERR" in out: raise RuntimeError("Fail to deploy ceph") self.putenv("CEPH_CONF", conffile, True) self.putenv("CEPH_CONF", conffile) self.putenv("URL", "ceph://localhost:%d" % self.port)
<|file_name|>ceph.py<|end_file_name|><|fim▁begin|># 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 os import uuid import pkg_resources from pifpaf import drivers class CephDriver(drivers.Driver): DEFAULT_PORT = 6790 def __init__(self, port=DEFAULT_PORT, **kwargs): <|fim_middle|> @classmethod def get_options(cls): return [ {"param_decls": ["--port"], "type": int, "default": cls.DEFAULT_PORT, "help": "port to use for Ceph Monitor"}, ] def _setUp(self): super(CephDriver, self)._setUp() self._ensure_xattr_support() fsid = str(uuid.uuid4()) conffile = os.path.join(self.tempdir, "ceph.conf") mondir = os.path.join(self.tempdir, "mon", "ceph-a") osddir = os.path.join(self.tempdir, "osd", "ceph-0") os.makedirs(mondir) os.makedirs(osddir) _, version = self._exec(["ceph", "--version"], stdout=True) version = version.decode("ascii").split()[2] version = pkg_resources.parse_version(version) if version < pkg_resources.parse_version("12.0.0"): extra = """ mon_osd_nearfull_ratio = 1 mon_osd_full_ratio = 1 osd_failsafe_nearfull_ratio = 1 osd_failsafe_full_ratio = 1 """ else: extra = """ mon_allow_pool_delete = true """ # FIXME(sileht): check availible space on /dev/shm # if os.path.exists("/dev/shm") and os.access('/dev/shm', os.W_OK): # journal_path = "/dev/shm/$cluster-$id-journal" # else: journal_path = "%s/osd/$cluster-$id/journal" % self.tempdir with open(conffile, "w") as f: f.write("""[global] fsid = %(fsid)s # no auth for now auth cluster required = none auth service required = none auth client required = none ## no replica osd pool default size = 1 osd pool default min size = 1 osd crush chooseleaf type = 0 ## some default path change run dir = %(tempdir)s pid file = %(tempdir)s/$type.$id.pid admin socket = %(tempdir)s/$cluster-$name.asok mon data = %(tempdir)s/mon/$cluster-$id osd data = %(tempdir)s/osd/$cluster-$id osd journal = %(journal_path)s log file = %(tempdir)s/$cluster-$name.log mon cluster log file = %(tempdir)s/$cluster.log # Only omap to have same behavior for all filesystems filestore xattr use omap = True # workaround for ext4 and last Jewel version osd max object name len = 256 osd max object namespace len = 64 osd op threads = 10 filestore max sync interval = 10001 filestore min sync interval = 10000 %(extra)s journal_aio = false journal_dio = false journal zero on create = false journal block align = false # run as file owner setuser match path = %(tempdir)s/$type/$cluster-$id [mon.a] host = localhost mon addr = 127.0.0.1:%(port)d """ % dict(fsid=fsid, tempdir=self.tempdir, port=self.port, journal_path=journal_path, extra=extra)) # noqa ceph_opts = ["ceph", "-c", conffile] mon_opts = ["ceph-mon", "-c", conffile, "--id", "a", "-d"] osd_opts = ["ceph-osd", "-c", conffile, "--id", "0", "-d", "-m", "127.0.0.1:%d" % self.port] # Create and start monitor self._exec(mon_opts + ["--mkfs"]) self._touch(os.path.join(mondir, "done")) mon, _ = self._exec( mon_opts, wait_for_line=r"mon.a@0\(leader\).mds e1 print_map") # Create and start OSD self._exec(ceph_opts + ["osd", "create"]) self._exec(ceph_opts + ["osd", "crush", "add", "osd.0", "1", "root=default"]) self._exec(osd_opts + ["--mkfs", "--mkjournal"]) if version < pkg_resources.parse_version("0.94.0"): wait_for_line = "journal close" else: wait_for_line = "done with init" osd, _ = self._exec(osd_opts, wait_for_line=wait_for_line) if version >= pkg_resources.parse_version("12.0.0"): self._exec(ceph_opts + ["osd", "set-full-ratio", "0.95"]) self._exec(ceph_opts + ["osd", "set-backfillfull-ratio", "0.95"]) self._exec(ceph_opts + ["osd", "set-nearfull-ratio", "0.95"]) # Wait it's ready out = b"" while b"HEALTH_OK" not in out: ceph, out = self._exec(ceph_opts + ["health"], stdout=True) if b"HEALTH_ERR" in out: raise RuntimeError("Fail to deploy ceph") self.putenv("CEPH_CONF", conffile, True) self.putenv("CEPH_CONF", conffile) self.putenv("URL", "ceph://localhost:%d" % self.port) <|fim▁end|>
"""Create a new Ceph cluster.""" super(CephDriver, self).__init__(**kwargs) self.port = port
<|file_name|>ceph.py<|end_file_name|><|fim▁begin|># 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 os import uuid import pkg_resources from pifpaf import drivers class CephDriver(drivers.Driver): DEFAULT_PORT = 6790 def __init__(self, port=DEFAULT_PORT, **kwargs): """Create a new Ceph cluster.""" super(CephDriver, self).__init__(**kwargs) self.port = port @classmethod def get_options(cls): <|fim_middle|> def _setUp(self): super(CephDriver, self)._setUp() self._ensure_xattr_support() fsid = str(uuid.uuid4()) conffile = os.path.join(self.tempdir, "ceph.conf") mondir = os.path.join(self.tempdir, "mon", "ceph-a") osddir = os.path.join(self.tempdir, "osd", "ceph-0") os.makedirs(mondir) os.makedirs(osddir) _, version = self._exec(["ceph", "--version"], stdout=True) version = version.decode("ascii").split()[2] version = pkg_resources.parse_version(version) if version < pkg_resources.parse_version("12.0.0"): extra = """ mon_osd_nearfull_ratio = 1 mon_osd_full_ratio = 1 osd_failsafe_nearfull_ratio = 1 osd_failsafe_full_ratio = 1 """ else: extra = """ mon_allow_pool_delete = true """ # FIXME(sileht): check availible space on /dev/shm # if os.path.exists("/dev/shm") and os.access('/dev/shm', os.W_OK): # journal_path = "/dev/shm/$cluster-$id-journal" # else: journal_path = "%s/osd/$cluster-$id/journal" % self.tempdir with open(conffile, "w") as f: f.write("""[global] fsid = %(fsid)s # no auth for now auth cluster required = none auth service required = none auth client required = none ## no replica osd pool default size = 1 osd pool default min size = 1 osd crush chooseleaf type = 0 ## some default path change run dir = %(tempdir)s pid file = %(tempdir)s/$type.$id.pid admin socket = %(tempdir)s/$cluster-$name.asok mon data = %(tempdir)s/mon/$cluster-$id osd data = %(tempdir)s/osd/$cluster-$id osd journal = %(journal_path)s log file = %(tempdir)s/$cluster-$name.log mon cluster log file = %(tempdir)s/$cluster.log # Only omap to have same behavior for all filesystems filestore xattr use omap = True # workaround for ext4 and last Jewel version osd max object name len = 256 osd max object namespace len = 64 osd op threads = 10 filestore max sync interval = 10001 filestore min sync interval = 10000 %(extra)s journal_aio = false journal_dio = false journal zero on create = false journal block align = false # run as file owner setuser match path = %(tempdir)s/$type/$cluster-$id [mon.a] host = localhost mon addr = 127.0.0.1:%(port)d """ % dict(fsid=fsid, tempdir=self.tempdir, port=self.port, journal_path=journal_path, extra=extra)) # noqa ceph_opts = ["ceph", "-c", conffile] mon_opts = ["ceph-mon", "-c", conffile, "--id", "a", "-d"] osd_opts = ["ceph-osd", "-c", conffile, "--id", "0", "-d", "-m", "127.0.0.1:%d" % self.port] # Create and start monitor self._exec(mon_opts + ["--mkfs"]) self._touch(os.path.join(mondir, "done")) mon, _ = self._exec( mon_opts, wait_for_line=r"mon.a@0\(leader\).mds e1 print_map") # Create and start OSD self._exec(ceph_opts + ["osd", "create"]) self._exec(ceph_opts + ["osd", "crush", "add", "osd.0", "1", "root=default"]) self._exec(osd_opts + ["--mkfs", "--mkjournal"]) if version < pkg_resources.parse_version("0.94.0"): wait_for_line = "journal close" else: wait_for_line = "done with init" osd, _ = self._exec(osd_opts, wait_for_line=wait_for_line) if version >= pkg_resources.parse_version("12.0.0"): self._exec(ceph_opts + ["osd", "set-full-ratio", "0.95"]) self._exec(ceph_opts + ["osd", "set-backfillfull-ratio", "0.95"]) self._exec(ceph_opts + ["osd", "set-nearfull-ratio", "0.95"]) # Wait it's ready out = b"" while b"HEALTH_OK" not in out: ceph, out = self._exec(ceph_opts + ["health"], stdout=True) if b"HEALTH_ERR" in out: raise RuntimeError("Fail to deploy ceph") self.putenv("CEPH_CONF", conffile, True) self.putenv("CEPH_CONF", conffile) self.putenv("URL", "ceph://localhost:%d" % self.port) <|fim▁end|>
return [ {"param_decls": ["--port"], "type": int, "default": cls.DEFAULT_PORT, "help": "port to use for Ceph Monitor"}, ]
<|file_name|>ceph.py<|end_file_name|><|fim▁begin|># 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 os import uuid import pkg_resources from pifpaf import drivers class CephDriver(drivers.Driver): DEFAULT_PORT = 6790 def __init__(self, port=DEFAULT_PORT, **kwargs): """Create a new Ceph cluster.""" super(CephDriver, self).__init__(**kwargs) self.port = port @classmethod def get_options(cls): return [ {"param_decls": ["--port"], "type": int, "default": cls.DEFAULT_PORT, "help": "port to use for Ceph Monitor"}, ] def _setUp(self): <|fim_middle|> <|fim▁end|>
super(CephDriver, self)._setUp() self._ensure_xattr_support() fsid = str(uuid.uuid4()) conffile = os.path.join(self.tempdir, "ceph.conf") mondir = os.path.join(self.tempdir, "mon", "ceph-a") osddir = os.path.join(self.tempdir, "osd", "ceph-0") os.makedirs(mondir) os.makedirs(osddir) _, version = self._exec(["ceph", "--version"], stdout=True) version = version.decode("ascii").split()[2] version = pkg_resources.parse_version(version) if version < pkg_resources.parse_version("12.0.0"): extra = """ mon_osd_nearfull_ratio = 1 mon_osd_full_ratio = 1 osd_failsafe_nearfull_ratio = 1 osd_failsafe_full_ratio = 1 """ else: extra = """ mon_allow_pool_delete = true """ # FIXME(sileht): check availible space on /dev/shm # if os.path.exists("/dev/shm") and os.access('/dev/shm', os.W_OK): # journal_path = "/dev/shm/$cluster-$id-journal" # else: journal_path = "%s/osd/$cluster-$id/journal" % self.tempdir with open(conffile, "w") as f: f.write("""[global] fsid = %(fsid)s # no auth for now auth cluster required = none auth service required = none auth client required = none ## no replica osd pool default size = 1 osd pool default min size = 1 osd crush chooseleaf type = 0 ## some default path change run dir = %(tempdir)s pid file = %(tempdir)s/$type.$id.pid admin socket = %(tempdir)s/$cluster-$name.asok mon data = %(tempdir)s/mon/$cluster-$id osd data = %(tempdir)s/osd/$cluster-$id osd journal = %(journal_path)s log file = %(tempdir)s/$cluster-$name.log mon cluster log file = %(tempdir)s/$cluster.log # Only omap to have same behavior for all filesystems filestore xattr use omap = True # workaround for ext4 and last Jewel version osd max object name len = 256 osd max object namespace len = 64 osd op threads = 10 filestore max sync interval = 10001 filestore min sync interval = 10000 %(extra)s journal_aio = false journal_dio = false journal zero on create = false journal block align = false # run as file owner setuser match path = %(tempdir)s/$type/$cluster-$id [mon.a] host = localhost mon addr = 127.0.0.1:%(port)d """ % dict(fsid=fsid, tempdir=self.tempdir, port=self.port, journal_path=journal_path, extra=extra)) # noqa ceph_opts = ["ceph", "-c", conffile] mon_opts = ["ceph-mon", "-c", conffile, "--id", "a", "-d"] osd_opts = ["ceph-osd", "-c", conffile, "--id", "0", "-d", "-m", "127.0.0.1:%d" % self.port] # Create and start monitor self._exec(mon_opts + ["--mkfs"]) self._touch(os.path.join(mondir, "done")) mon, _ = self._exec( mon_opts, wait_for_line=r"mon.a@0\(leader\).mds e1 print_map") # Create and start OSD self._exec(ceph_opts + ["osd", "create"]) self._exec(ceph_opts + ["osd", "crush", "add", "osd.0", "1", "root=default"]) self._exec(osd_opts + ["--mkfs", "--mkjournal"]) if version < pkg_resources.parse_version("0.94.0"): wait_for_line = "journal close" else: wait_for_line = "done with init" osd, _ = self._exec(osd_opts, wait_for_line=wait_for_line) if version >= pkg_resources.parse_version("12.0.0"): self._exec(ceph_opts + ["osd", "set-full-ratio", "0.95"]) self._exec(ceph_opts + ["osd", "set-backfillfull-ratio", "0.95"]) self._exec(ceph_opts + ["osd", "set-nearfull-ratio", "0.95"]) # Wait it's ready out = b"" while b"HEALTH_OK" not in out: ceph, out = self._exec(ceph_opts + ["health"], stdout=True) if b"HEALTH_ERR" in out: raise RuntimeError("Fail to deploy ceph") self.putenv("CEPH_CONF", conffile, True) self.putenv("CEPH_CONF", conffile) self.putenv("URL", "ceph://localhost:%d" % self.port)
<|file_name|>ceph.py<|end_file_name|><|fim▁begin|># 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 os import uuid import pkg_resources from pifpaf import drivers class CephDriver(drivers.Driver): DEFAULT_PORT = 6790 def __init__(self, port=DEFAULT_PORT, **kwargs): """Create a new Ceph cluster.""" super(CephDriver, self).__init__(**kwargs) self.port = port @classmethod def get_options(cls): return [ {"param_decls": ["--port"], "type": int, "default": cls.DEFAULT_PORT, "help": "port to use for Ceph Monitor"}, ] def _setUp(self): super(CephDriver, self)._setUp() self._ensure_xattr_support() fsid = str(uuid.uuid4()) conffile = os.path.join(self.tempdir, "ceph.conf") mondir = os.path.join(self.tempdir, "mon", "ceph-a") osddir = os.path.join(self.tempdir, "osd", "ceph-0") os.makedirs(mondir) os.makedirs(osddir) _, version = self._exec(["ceph", "--version"], stdout=True) version = version.decode("ascii").split()[2] version = pkg_resources.parse_version(version) if version < pkg_resources.parse_version("12.0.0"): <|fim_middle|> else: extra = """ mon_allow_pool_delete = true """ # FIXME(sileht): check availible space on /dev/shm # if os.path.exists("/dev/shm") and os.access('/dev/shm', os.W_OK): # journal_path = "/dev/shm/$cluster-$id-journal" # else: journal_path = "%s/osd/$cluster-$id/journal" % self.tempdir with open(conffile, "w") as f: f.write("""[global] fsid = %(fsid)s # no auth for now auth cluster required = none auth service required = none auth client required = none ## no replica osd pool default size = 1 osd pool default min size = 1 osd crush chooseleaf type = 0 ## some default path change run dir = %(tempdir)s pid file = %(tempdir)s/$type.$id.pid admin socket = %(tempdir)s/$cluster-$name.asok mon data = %(tempdir)s/mon/$cluster-$id osd data = %(tempdir)s/osd/$cluster-$id osd journal = %(journal_path)s log file = %(tempdir)s/$cluster-$name.log mon cluster log file = %(tempdir)s/$cluster.log # Only omap to have same behavior for all filesystems filestore xattr use omap = True # workaround for ext4 and last Jewel version osd max object name len = 256 osd max object namespace len = 64 osd op threads = 10 filestore max sync interval = 10001 filestore min sync interval = 10000 %(extra)s journal_aio = false journal_dio = false journal zero on create = false journal block align = false # run as file owner setuser match path = %(tempdir)s/$type/$cluster-$id [mon.a] host = localhost mon addr = 127.0.0.1:%(port)d """ % dict(fsid=fsid, tempdir=self.tempdir, port=self.port, journal_path=journal_path, extra=extra)) # noqa ceph_opts = ["ceph", "-c", conffile] mon_opts = ["ceph-mon", "-c", conffile, "--id", "a", "-d"] osd_opts = ["ceph-osd", "-c", conffile, "--id", "0", "-d", "-m", "127.0.0.1:%d" % self.port] # Create and start monitor self._exec(mon_opts + ["--mkfs"]) self._touch(os.path.join(mondir, "done")) mon, _ = self._exec( mon_opts, wait_for_line=r"mon.a@0\(leader\).mds e1 print_map") # Create and start OSD self._exec(ceph_opts + ["osd", "create"]) self._exec(ceph_opts + ["osd", "crush", "add", "osd.0", "1", "root=default"]) self._exec(osd_opts + ["--mkfs", "--mkjournal"]) if version < pkg_resources.parse_version("0.94.0"): wait_for_line = "journal close" else: wait_for_line = "done with init" osd, _ = self._exec(osd_opts, wait_for_line=wait_for_line) if version >= pkg_resources.parse_version("12.0.0"): self._exec(ceph_opts + ["osd", "set-full-ratio", "0.95"]) self._exec(ceph_opts + ["osd", "set-backfillfull-ratio", "0.95"]) self._exec(ceph_opts + ["osd", "set-nearfull-ratio", "0.95"]) # Wait it's ready out = b"" while b"HEALTH_OK" not in out: ceph, out = self._exec(ceph_opts + ["health"], stdout=True) if b"HEALTH_ERR" in out: raise RuntimeError("Fail to deploy ceph") self.putenv("CEPH_CONF", conffile, True) self.putenv("CEPH_CONF", conffile) self.putenv("URL", "ceph://localhost:%d" % self.port) <|fim▁end|>
extra = """ mon_osd_nearfull_ratio = 1 mon_osd_full_ratio = 1 osd_failsafe_nearfull_ratio = 1 osd_failsafe_full_ratio = 1 """
<|file_name|>ceph.py<|end_file_name|><|fim▁begin|># 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 os import uuid import pkg_resources from pifpaf import drivers class CephDriver(drivers.Driver): DEFAULT_PORT = 6790 def __init__(self, port=DEFAULT_PORT, **kwargs): """Create a new Ceph cluster.""" super(CephDriver, self).__init__(**kwargs) self.port = port @classmethod def get_options(cls): return [ {"param_decls": ["--port"], "type": int, "default": cls.DEFAULT_PORT, "help": "port to use for Ceph Monitor"}, ] def _setUp(self): super(CephDriver, self)._setUp() self._ensure_xattr_support() fsid = str(uuid.uuid4()) conffile = os.path.join(self.tempdir, "ceph.conf") mondir = os.path.join(self.tempdir, "mon", "ceph-a") osddir = os.path.join(self.tempdir, "osd", "ceph-0") os.makedirs(mondir) os.makedirs(osddir) _, version = self._exec(["ceph", "--version"], stdout=True) version = version.decode("ascii").split()[2] version = pkg_resources.parse_version(version) if version < pkg_resources.parse_version("12.0.0"): extra = """ mon_osd_nearfull_ratio = 1 mon_osd_full_ratio = 1 osd_failsafe_nearfull_ratio = 1 osd_failsafe_full_ratio = 1 """ else: <|fim_middle|> # FIXME(sileht): check availible space on /dev/shm # if os.path.exists("/dev/shm") and os.access('/dev/shm', os.W_OK): # journal_path = "/dev/shm/$cluster-$id-journal" # else: journal_path = "%s/osd/$cluster-$id/journal" % self.tempdir with open(conffile, "w") as f: f.write("""[global] fsid = %(fsid)s # no auth for now auth cluster required = none auth service required = none auth client required = none ## no replica osd pool default size = 1 osd pool default min size = 1 osd crush chooseleaf type = 0 ## some default path change run dir = %(tempdir)s pid file = %(tempdir)s/$type.$id.pid admin socket = %(tempdir)s/$cluster-$name.asok mon data = %(tempdir)s/mon/$cluster-$id osd data = %(tempdir)s/osd/$cluster-$id osd journal = %(journal_path)s log file = %(tempdir)s/$cluster-$name.log mon cluster log file = %(tempdir)s/$cluster.log # Only omap to have same behavior for all filesystems filestore xattr use omap = True # workaround for ext4 and last Jewel version osd max object name len = 256 osd max object namespace len = 64 osd op threads = 10 filestore max sync interval = 10001 filestore min sync interval = 10000 %(extra)s journal_aio = false journal_dio = false journal zero on create = false journal block align = false # run as file owner setuser match path = %(tempdir)s/$type/$cluster-$id [mon.a] host = localhost mon addr = 127.0.0.1:%(port)d """ % dict(fsid=fsid, tempdir=self.tempdir, port=self.port, journal_path=journal_path, extra=extra)) # noqa ceph_opts = ["ceph", "-c", conffile] mon_opts = ["ceph-mon", "-c", conffile, "--id", "a", "-d"] osd_opts = ["ceph-osd", "-c", conffile, "--id", "0", "-d", "-m", "127.0.0.1:%d" % self.port] # Create and start monitor self._exec(mon_opts + ["--mkfs"]) self._touch(os.path.join(mondir, "done")) mon, _ = self._exec( mon_opts, wait_for_line=r"mon.a@0\(leader\).mds e1 print_map") # Create and start OSD self._exec(ceph_opts + ["osd", "create"]) self._exec(ceph_opts + ["osd", "crush", "add", "osd.0", "1", "root=default"]) self._exec(osd_opts + ["--mkfs", "--mkjournal"]) if version < pkg_resources.parse_version("0.94.0"): wait_for_line = "journal close" else: wait_for_line = "done with init" osd, _ = self._exec(osd_opts, wait_for_line=wait_for_line) if version >= pkg_resources.parse_version("12.0.0"): self._exec(ceph_opts + ["osd", "set-full-ratio", "0.95"]) self._exec(ceph_opts + ["osd", "set-backfillfull-ratio", "0.95"]) self._exec(ceph_opts + ["osd", "set-nearfull-ratio", "0.95"]) # Wait it's ready out = b"" while b"HEALTH_OK" not in out: ceph, out = self._exec(ceph_opts + ["health"], stdout=True) if b"HEALTH_ERR" in out: raise RuntimeError("Fail to deploy ceph") self.putenv("CEPH_CONF", conffile, True) self.putenv("CEPH_CONF", conffile) self.putenv("URL", "ceph://localhost:%d" % self.port) <|fim▁end|>
extra = """ mon_allow_pool_delete = true """
<|file_name|>ceph.py<|end_file_name|><|fim▁begin|># 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 os import uuid import pkg_resources from pifpaf import drivers class CephDriver(drivers.Driver): DEFAULT_PORT = 6790 def __init__(self, port=DEFAULT_PORT, **kwargs): """Create a new Ceph cluster.""" super(CephDriver, self).__init__(**kwargs) self.port = port @classmethod def get_options(cls): return [ {"param_decls": ["--port"], "type": int, "default": cls.DEFAULT_PORT, "help": "port to use for Ceph Monitor"}, ] def _setUp(self): super(CephDriver, self)._setUp() self._ensure_xattr_support() fsid = str(uuid.uuid4()) conffile = os.path.join(self.tempdir, "ceph.conf") mondir = os.path.join(self.tempdir, "mon", "ceph-a") osddir = os.path.join(self.tempdir, "osd", "ceph-0") os.makedirs(mondir) os.makedirs(osddir) _, version = self._exec(["ceph", "--version"], stdout=True) version = version.decode("ascii").split()[2] version = pkg_resources.parse_version(version) if version < pkg_resources.parse_version("12.0.0"): extra = """ mon_osd_nearfull_ratio = 1 mon_osd_full_ratio = 1 osd_failsafe_nearfull_ratio = 1 osd_failsafe_full_ratio = 1 """ else: extra = """ mon_allow_pool_delete = true """ # FIXME(sileht): check availible space on /dev/shm # if os.path.exists("/dev/shm") and os.access('/dev/shm', os.W_OK): # journal_path = "/dev/shm/$cluster-$id-journal" # else: journal_path = "%s/osd/$cluster-$id/journal" % self.tempdir with open(conffile, "w") as f: f.write("""[global] fsid = %(fsid)s # no auth for now auth cluster required = none auth service required = none auth client required = none ## no replica osd pool default size = 1 osd pool default min size = 1 osd crush chooseleaf type = 0 ## some default path change run dir = %(tempdir)s pid file = %(tempdir)s/$type.$id.pid admin socket = %(tempdir)s/$cluster-$name.asok mon data = %(tempdir)s/mon/$cluster-$id osd data = %(tempdir)s/osd/$cluster-$id osd journal = %(journal_path)s log file = %(tempdir)s/$cluster-$name.log mon cluster log file = %(tempdir)s/$cluster.log # Only omap to have same behavior for all filesystems filestore xattr use omap = True # workaround for ext4 and last Jewel version osd max object name len = 256 osd max object namespace len = 64 osd op threads = 10 filestore max sync interval = 10001 filestore min sync interval = 10000 %(extra)s journal_aio = false journal_dio = false journal zero on create = false journal block align = false # run as file owner setuser match path = %(tempdir)s/$type/$cluster-$id [mon.a] host = localhost mon addr = 127.0.0.1:%(port)d """ % dict(fsid=fsid, tempdir=self.tempdir, port=self.port, journal_path=journal_path, extra=extra)) # noqa ceph_opts = ["ceph", "-c", conffile] mon_opts = ["ceph-mon", "-c", conffile, "--id", "a", "-d"] osd_opts = ["ceph-osd", "-c", conffile, "--id", "0", "-d", "-m", "127.0.0.1:%d" % self.port] # Create and start monitor self._exec(mon_opts + ["--mkfs"]) self._touch(os.path.join(mondir, "done")) mon, _ = self._exec( mon_opts, wait_for_line=r"mon.a@0\(leader\).mds e1 print_map") # Create and start OSD self._exec(ceph_opts + ["osd", "create"]) self._exec(ceph_opts + ["osd", "crush", "add", "osd.0", "1", "root=default"]) self._exec(osd_opts + ["--mkfs", "--mkjournal"]) if version < pkg_resources.parse_version("0.94.0"): <|fim_middle|> else: wait_for_line = "done with init" osd, _ = self._exec(osd_opts, wait_for_line=wait_for_line) if version >= pkg_resources.parse_version("12.0.0"): self._exec(ceph_opts + ["osd", "set-full-ratio", "0.95"]) self._exec(ceph_opts + ["osd", "set-backfillfull-ratio", "0.95"]) self._exec(ceph_opts + ["osd", "set-nearfull-ratio", "0.95"]) # Wait it's ready out = b"" while b"HEALTH_OK" not in out: ceph, out = self._exec(ceph_opts + ["health"], stdout=True) if b"HEALTH_ERR" in out: raise RuntimeError("Fail to deploy ceph") self.putenv("CEPH_CONF", conffile, True) self.putenv("CEPH_CONF", conffile) self.putenv("URL", "ceph://localhost:%d" % self.port) <|fim▁end|>
wait_for_line = "journal close"
<|file_name|>ceph.py<|end_file_name|><|fim▁begin|># 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 os import uuid import pkg_resources from pifpaf import drivers class CephDriver(drivers.Driver): DEFAULT_PORT = 6790 def __init__(self, port=DEFAULT_PORT, **kwargs): """Create a new Ceph cluster.""" super(CephDriver, self).__init__(**kwargs) self.port = port @classmethod def get_options(cls): return [ {"param_decls": ["--port"], "type": int, "default": cls.DEFAULT_PORT, "help": "port to use for Ceph Monitor"}, ] def _setUp(self): super(CephDriver, self)._setUp() self._ensure_xattr_support() fsid = str(uuid.uuid4()) conffile = os.path.join(self.tempdir, "ceph.conf") mondir = os.path.join(self.tempdir, "mon", "ceph-a") osddir = os.path.join(self.tempdir, "osd", "ceph-0") os.makedirs(mondir) os.makedirs(osddir) _, version = self._exec(["ceph", "--version"], stdout=True) version = version.decode("ascii").split()[2] version = pkg_resources.parse_version(version) if version < pkg_resources.parse_version("12.0.0"): extra = """ mon_osd_nearfull_ratio = 1 mon_osd_full_ratio = 1 osd_failsafe_nearfull_ratio = 1 osd_failsafe_full_ratio = 1 """ else: extra = """ mon_allow_pool_delete = true """ # FIXME(sileht): check availible space on /dev/shm # if os.path.exists("/dev/shm") and os.access('/dev/shm', os.W_OK): # journal_path = "/dev/shm/$cluster-$id-journal" # else: journal_path = "%s/osd/$cluster-$id/journal" % self.tempdir with open(conffile, "w") as f: f.write("""[global] fsid = %(fsid)s # no auth for now auth cluster required = none auth service required = none auth client required = none ## no replica osd pool default size = 1 osd pool default min size = 1 osd crush chooseleaf type = 0 ## some default path change run dir = %(tempdir)s pid file = %(tempdir)s/$type.$id.pid admin socket = %(tempdir)s/$cluster-$name.asok mon data = %(tempdir)s/mon/$cluster-$id osd data = %(tempdir)s/osd/$cluster-$id osd journal = %(journal_path)s log file = %(tempdir)s/$cluster-$name.log mon cluster log file = %(tempdir)s/$cluster.log # Only omap to have same behavior for all filesystems filestore xattr use omap = True # workaround for ext4 and last Jewel version osd max object name len = 256 osd max object namespace len = 64 osd op threads = 10 filestore max sync interval = 10001 filestore min sync interval = 10000 %(extra)s journal_aio = false journal_dio = false journal zero on create = false journal block align = false # run as file owner setuser match path = %(tempdir)s/$type/$cluster-$id [mon.a] host = localhost mon addr = 127.0.0.1:%(port)d """ % dict(fsid=fsid, tempdir=self.tempdir, port=self.port, journal_path=journal_path, extra=extra)) # noqa ceph_opts = ["ceph", "-c", conffile] mon_opts = ["ceph-mon", "-c", conffile, "--id", "a", "-d"] osd_opts = ["ceph-osd", "-c", conffile, "--id", "0", "-d", "-m", "127.0.0.1:%d" % self.port] # Create and start monitor self._exec(mon_opts + ["--mkfs"]) self._touch(os.path.join(mondir, "done")) mon, _ = self._exec( mon_opts, wait_for_line=r"mon.a@0\(leader\).mds e1 print_map") # Create and start OSD self._exec(ceph_opts + ["osd", "create"]) self._exec(ceph_opts + ["osd", "crush", "add", "osd.0", "1", "root=default"]) self._exec(osd_opts + ["--mkfs", "--mkjournal"]) if version < pkg_resources.parse_version("0.94.0"): wait_for_line = "journal close" else: <|fim_middle|> osd, _ = self._exec(osd_opts, wait_for_line=wait_for_line) if version >= pkg_resources.parse_version("12.0.0"): self._exec(ceph_opts + ["osd", "set-full-ratio", "0.95"]) self._exec(ceph_opts + ["osd", "set-backfillfull-ratio", "0.95"]) self._exec(ceph_opts + ["osd", "set-nearfull-ratio", "0.95"]) # Wait it's ready out = b"" while b"HEALTH_OK" not in out: ceph, out = self._exec(ceph_opts + ["health"], stdout=True) if b"HEALTH_ERR" in out: raise RuntimeError("Fail to deploy ceph") self.putenv("CEPH_CONF", conffile, True) self.putenv("CEPH_CONF", conffile) self.putenv("URL", "ceph://localhost:%d" % self.port) <|fim▁end|>
wait_for_line = "done with init"
<|file_name|>ceph.py<|end_file_name|><|fim▁begin|># 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 os import uuid import pkg_resources from pifpaf import drivers class CephDriver(drivers.Driver): DEFAULT_PORT = 6790 def __init__(self, port=DEFAULT_PORT, **kwargs): """Create a new Ceph cluster.""" super(CephDriver, self).__init__(**kwargs) self.port = port @classmethod def get_options(cls): return [ {"param_decls": ["--port"], "type": int, "default": cls.DEFAULT_PORT, "help": "port to use for Ceph Monitor"}, ] def _setUp(self): super(CephDriver, self)._setUp() self._ensure_xattr_support() fsid = str(uuid.uuid4()) conffile = os.path.join(self.tempdir, "ceph.conf") mondir = os.path.join(self.tempdir, "mon", "ceph-a") osddir = os.path.join(self.tempdir, "osd", "ceph-0") os.makedirs(mondir) os.makedirs(osddir) _, version = self._exec(["ceph", "--version"], stdout=True) version = version.decode("ascii").split()[2] version = pkg_resources.parse_version(version) if version < pkg_resources.parse_version("12.0.0"): extra = """ mon_osd_nearfull_ratio = 1 mon_osd_full_ratio = 1 osd_failsafe_nearfull_ratio = 1 osd_failsafe_full_ratio = 1 """ else: extra = """ mon_allow_pool_delete = true """ # FIXME(sileht): check availible space on /dev/shm # if os.path.exists("/dev/shm") and os.access('/dev/shm', os.W_OK): # journal_path = "/dev/shm/$cluster-$id-journal" # else: journal_path = "%s/osd/$cluster-$id/journal" % self.tempdir with open(conffile, "w") as f: f.write("""[global] fsid = %(fsid)s # no auth for now auth cluster required = none auth service required = none auth client required = none ## no replica osd pool default size = 1 osd pool default min size = 1 osd crush chooseleaf type = 0 ## some default path change run dir = %(tempdir)s pid file = %(tempdir)s/$type.$id.pid admin socket = %(tempdir)s/$cluster-$name.asok mon data = %(tempdir)s/mon/$cluster-$id osd data = %(tempdir)s/osd/$cluster-$id osd journal = %(journal_path)s log file = %(tempdir)s/$cluster-$name.log mon cluster log file = %(tempdir)s/$cluster.log # Only omap to have same behavior for all filesystems filestore xattr use omap = True # workaround for ext4 and last Jewel version osd max object name len = 256 osd max object namespace len = 64 osd op threads = 10 filestore max sync interval = 10001 filestore min sync interval = 10000 %(extra)s journal_aio = false journal_dio = false journal zero on create = false journal block align = false # run as file owner setuser match path = %(tempdir)s/$type/$cluster-$id [mon.a] host = localhost mon addr = 127.0.0.1:%(port)d """ % dict(fsid=fsid, tempdir=self.tempdir, port=self.port, journal_path=journal_path, extra=extra)) # noqa ceph_opts = ["ceph", "-c", conffile] mon_opts = ["ceph-mon", "-c", conffile, "--id", "a", "-d"] osd_opts = ["ceph-osd", "-c", conffile, "--id", "0", "-d", "-m", "127.0.0.1:%d" % self.port] # Create and start monitor self._exec(mon_opts + ["--mkfs"]) self._touch(os.path.join(mondir, "done")) mon, _ = self._exec( mon_opts, wait_for_line=r"mon.a@0\(leader\).mds e1 print_map") # Create and start OSD self._exec(ceph_opts + ["osd", "create"]) self._exec(ceph_opts + ["osd", "crush", "add", "osd.0", "1", "root=default"]) self._exec(osd_opts + ["--mkfs", "--mkjournal"]) if version < pkg_resources.parse_version("0.94.0"): wait_for_line = "journal close" else: wait_for_line = "done with init" osd, _ = self._exec(osd_opts, wait_for_line=wait_for_line) if version >= pkg_resources.parse_version("12.0.0"): <|fim_middle|> # Wait it's ready out = b"" while b"HEALTH_OK" not in out: ceph, out = self._exec(ceph_opts + ["health"], stdout=True) if b"HEALTH_ERR" in out: raise RuntimeError("Fail to deploy ceph") self.putenv("CEPH_CONF", conffile, True) self.putenv("CEPH_CONF", conffile) self.putenv("URL", "ceph://localhost:%d" % self.port) <|fim▁end|>
self._exec(ceph_opts + ["osd", "set-full-ratio", "0.95"]) self._exec(ceph_opts + ["osd", "set-backfillfull-ratio", "0.95"]) self._exec(ceph_opts + ["osd", "set-nearfull-ratio", "0.95"])
<|file_name|>ceph.py<|end_file_name|><|fim▁begin|># 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 os import uuid import pkg_resources from pifpaf import drivers class CephDriver(drivers.Driver): DEFAULT_PORT = 6790 def __init__(self, port=DEFAULT_PORT, **kwargs): """Create a new Ceph cluster.""" super(CephDriver, self).__init__(**kwargs) self.port = port @classmethod def get_options(cls): return [ {"param_decls": ["--port"], "type": int, "default": cls.DEFAULT_PORT, "help": "port to use for Ceph Monitor"}, ] def _setUp(self): super(CephDriver, self)._setUp() self._ensure_xattr_support() fsid = str(uuid.uuid4()) conffile = os.path.join(self.tempdir, "ceph.conf") mondir = os.path.join(self.tempdir, "mon", "ceph-a") osddir = os.path.join(self.tempdir, "osd", "ceph-0") os.makedirs(mondir) os.makedirs(osddir) _, version = self._exec(["ceph", "--version"], stdout=True) version = version.decode("ascii").split()[2] version = pkg_resources.parse_version(version) if version < pkg_resources.parse_version("12.0.0"): extra = """ mon_osd_nearfull_ratio = 1 mon_osd_full_ratio = 1 osd_failsafe_nearfull_ratio = 1 osd_failsafe_full_ratio = 1 """ else: extra = """ mon_allow_pool_delete = true """ # FIXME(sileht): check availible space on /dev/shm # if os.path.exists("/dev/shm") and os.access('/dev/shm', os.W_OK): # journal_path = "/dev/shm/$cluster-$id-journal" # else: journal_path = "%s/osd/$cluster-$id/journal" % self.tempdir with open(conffile, "w") as f: f.write("""[global] fsid = %(fsid)s # no auth for now auth cluster required = none auth service required = none auth client required = none ## no replica osd pool default size = 1 osd pool default min size = 1 osd crush chooseleaf type = 0 ## some default path change run dir = %(tempdir)s pid file = %(tempdir)s/$type.$id.pid admin socket = %(tempdir)s/$cluster-$name.asok mon data = %(tempdir)s/mon/$cluster-$id osd data = %(tempdir)s/osd/$cluster-$id osd journal = %(journal_path)s log file = %(tempdir)s/$cluster-$name.log mon cluster log file = %(tempdir)s/$cluster.log # Only omap to have same behavior for all filesystems filestore xattr use omap = True # workaround for ext4 and last Jewel version osd max object name len = 256 osd max object namespace len = 64 osd op threads = 10 filestore max sync interval = 10001 filestore min sync interval = 10000 %(extra)s journal_aio = false journal_dio = false journal zero on create = false journal block align = false # run as file owner setuser match path = %(tempdir)s/$type/$cluster-$id [mon.a] host = localhost mon addr = 127.0.0.1:%(port)d """ % dict(fsid=fsid, tempdir=self.tempdir, port=self.port, journal_path=journal_path, extra=extra)) # noqa ceph_opts = ["ceph", "-c", conffile] mon_opts = ["ceph-mon", "-c", conffile, "--id", "a", "-d"] osd_opts = ["ceph-osd", "-c", conffile, "--id", "0", "-d", "-m", "127.0.0.1:%d" % self.port] # Create and start monitor self._exec(mon_opts + ["--mkfs"]) self._touch(os.path.join(mondir, "done")) mon, _ = self._exec( mon_opts, wait_for_line=r"mon.a@0\(leader\).mds e1 print_map") # Create and start OSD self._exec(ceph_opts + ["osd", "create"]) self._exec(ceph_opts + ["osd", "crush", "add", "osd.0", "1", "root=default"]) self._exec(osd_opts + ["--mkfs", "--mkjournal"]) if version < pkg_resources.parse_version("0.94.0"): wait_for_line = "journal close" else: wait_for_line = "done with init" osd, _ = self._exec(osd_opts, wait_for_line=wait_for_line) if version >= pkg_resources.parse_version("12.0.0"): self._exec(ceph_opts + ["osd", "set-full-ratio", "0.95"]) self._exec(ceph_opts + ["osd", "set-backfillfull-ratio", "0.95"]) self._exec(ceph_opts + ["osd", "set-nearfull-ratio", "0.95"]) # Wait it's ready out = b"" while b"HEALTH_OK" not in out: ceph, out = self._exec(ceph_opts + ["health"], stdout=True) if b"HEALTH_ERR" in out: <|fim_middle|> self.putenv("CEPH_CONF", conffile, True) self.putenv("CEPH_CONF", conffile) self.putenv("URL", "ceph://localhost:%d" % self.port) <|fim▁end|>
raise RuntimeError("Fail to deploy ceph")
<|file_name|>ceph.py<|end_file_name|><|fim▁begin|># 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 os import uuid import pkg_resources from pifpaf import drivers class CephDriver(drivers.Driver): DEFAULT_PORT = 6790 def <|fim_middle|>(self, port=DEFAULT_PORT, **kwargs): """Create a new Ceph cluster.""" super(CephDriver, self).__init__(**kwargs) self.port = port @classmethod def get_options(cls): return [ {"param_decls": ["--port"], "type": int, "default": cls.DEFAULT_PORT, "help": "port to use for Ceph Monitor"}, ] def _setUp(self): super(CephDriver, self)._setUp() self._ensure_xattr_support() fsid = str(uuid.uuid4()) conffile = os.path.join(self.tempdir, "ceph.conf") mondir = os.path.join(self.tempdir, "mon", "ceph-a") osddir = os.path.join(self.tempdir, "osd", "ceph-0") os.makedirs(mondir) os.makedirs(osddir) _, version = self._exec(["ceph", "--version"], stdout=True) version = version.decode("ascii").split()[2] version = pkg_resources.parse_version(version) if version < pkg_resources.parse_version("12.0.0"): extra = """ mon_osd_nearfull_ratio = 1 mon_osd_full_ratio = 1 osd_failsafe_nearfull_ratio = 1 osd_failsafe_full_ratio = 1 """ else: extra = """ mon_allow_pool_delete = true """ # FIXME(sileht): check availible space on /dev/shm # if os.path.exists("/dev/shm") and os.access('/dev/shm', os.W_OK): # journal_path = "/dev/shm/$cluster-$id-journal" # else: journal_path = "%s/osd/$cluster-$id/journal" % self.tempdir with open(conffile, "w") as f: f.write("""[global] fsid = %(fsid)s # no auth for now auth cluster required = none auth service required = none auth client required = none ## no replica osd pool default size = 1 osd pool default min size = 1 osd crush chooseleaf type = 0 ## some default path change run dir = %(tempdir)s pid file = %(tempdir)s/$type.$id.pid admin socket = %(tempdir)s/$cluster-$name.asok mon data = %(tempdir)s/mon/$cluster-$id osd data = %(tempdir)s/osd/$cluster-$id osd journal = %(journal_path)s log file = %(tempdir)s/$cluster-$name.log mon cluster log file = %(tempdir)s/$cluster.log # Only omap to have same behavior for all filesystems filestore xattr use omap = True # workaround for ext4 and last Jewel version osd max object name len = 256 osd max object namespace len = 64 osd op threads = 10 filestore max sync interval = 10001 filestore min sync interval = 10000 %(extra)s journal_aio = false journal_dio = false journal zero on create = false journal block align = false # run as file owner setuser match path = %(tempdir)s/$type/$cluster-$id [mon.a] host = localhost mon addr = 127.0.0.1:%(port)d """ % dict(fsid=fsid, tempdir=self.tempdir, port=self.port, journal_path=journal_path, extra=extra)) # noqa ceph_opts = ["ceph", "-c", conffile] mon_opts = ["ceph-mon", "-c", conffile, "--id", "a", "-d"] osd_opts = ["ceph-osd", "-c", conffile, "--id", "0", "-d", "-m", "127.0.0.1:%d" % self.port] # Create and start monitor self._exec(mon_opts + ["--mkfs"]) self._touch(os.path.join(mondir, "done")) mon, _ = self._exec( mon_opts, wait_for_line=r"mon.a@0\(leader\).mds e1 print_map") # Create and start OSD self._exec(ceph_opts + ["osd", "create"]) self._exec(ceph_opts + ["osd", "crush", "add", "osd.0", "1", "root=default"]) self._exec(osd_opts + ["--mkfs", "--mkjournal"]) if version < pkg_resources.parse_version("0.94.0"): wait_for_line = "journal close" else: wait_for_line = "done with init" osd, _ = self._exec(osd_opts, wait_for_line=wait_for_line) if version >= pkg_resources.parse_version("12.0.0"): self._exec(ceph_opts + ["osd", "set-full-ratio", "0.95"]) self._exec(ceph_opts + ["osd", "set-backfillfull-ratio", "0.95"]) self._exec(ceph_opts + ["osd", "set-nearfull-ratio", "0.95"]) # Wait it's ready out = b"" while b"HEALTH_OK" not in out: ceph, out = self._exec(ceph_opts + ["health"], stdout=True) if b"HEALTH_ERR" in out: raise RuntimeError("Fail to deploy ceph") self.putenv("CEPH_CONF", conffile, True) self.putenv("CEPH_CONF", conffile) self.putenv("URL", "ceph://localhost:%d" % self.port) <|fim▁end|>
__init__
<|file_name|>ceph.py<|end_file_name|><|fim▁begin|># 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 os import uuid import pkg_resources from pifpaf import drivers class CephDriver(drivers.Driver): DEFAULT_PORT = 6790 def __init__(self, port=DEFAULT_PORT, **kwargs): """Create a new Ceph cluster.""" super(CephDriver, self).__init__(**kwargs) self.port = port @classmethod def <|fim_middle|>(cls): return [ {"param_decls": ["--port"], "type": int, "default": cls.DEFAULT_PORT, "help": "port to use for Ceph Monitor"}, ] def _setUp(self): super(CephDriver, self)._setUp() self._ensure_xattr_support() fsid = str(uuid.uuid4()) conffile = os.path.join(self.tempdir, "ceph.conf") mondir = os.path.join(self.tempdir, "mon", "ceph-a") osddir = os.path.join(self.tempdir, "osd", "ceph-0") os.makedirs(mondir) os.makedirs(osddir) _, version = self._exec(["ceph", "--version"], stdout=True) version = version.decode("ascii").split()[2] version = pkg_resources.parse_version(version) if version < pkg_resources.parse_version("12.0.0"): extra = """ mon_osd_nearfull_ratio = 1 mon_osd_full_ratio = 1 osd_failsafe_nearfull_ratio = 1 osd_failsafe_full_ratio = 1 """ else: extra = """ mon_allow_pool_delete = true """ # FIXME(sileht): check availible space on /dev/shm # if os.path.exists("/dev/shm") and os.access('/dev/shm', os.W_OK): # journal_path = "/dev/shm/$cluster-$id-journal" # else: journal_path = "%s/osd/$cluster-$id/journal" % self.tempdir with open(conffile, "w") as f: f.write("""[global] fsid = %(fsid)s # no auth for now auth cluster required = none auth service required = none auth client required = none ## no replica osd pool default size = 1 osd pool default min size = 1 osd crush chooseleaf type = 0 ## some default path change run dir = %(tempdir)s pid file = %(tempdir)s/$type.$id.pid admin socket = %(tempdir)s/$cluster-$name.asok mon data = %(tempdir)s/mon/$cluster-$id osd data = %(tempdir)s/osd/$cluster-$id osd journal = %(journal_path)s log file = %(tempdir)s/$cluster-$name.log mon cluster log file = %(tempdir)s/$cluster.log # Only omap to have same behavior for all filesystems filestore xattr use omap = True # workaround for ext4 and last Jewel version osd max object name len = 256 osd max object namespace len = 64 osd op threads = 10 filestore max sync interval = 10001 filestore min sync interval = 10000 %(extra)s journal_aio = false journal_dio = false journal zero on create = false journal block align = false # run as file owner setuser match path = %(tempdir)s/$type/$cluster-$id [mon.a] host = localhost mon addr = 127.0.0.1:%(port)d """ % dict(fsid=fsid, tempdir=self.tempdir, port=self.port, journal_path=journal_path, extra=extra)) # noqa ceph_opts = ["ceph", "-c", conffile] mon_opts = ["ceph-mon", "-c", conffile, "--id", "a", "-d"] osd_opts = ["ceph-osd", "-c", conffile, "--id", "0", "-d", "-m", "127.0.0.1:%d" % self.port] # Create and start monitor self._exec(mon_opts + ["--mkfs"]) self._touch(os.path.join(mondir, "done")) mon, _ = self._exec( mon_opts, wait_for_line=r"mon.a@0\(leader\).mds e1 print_map") # Create and start OSD self._exec(ceph_opts + ["osd", "create"]) self._exec(ceph_opts + ["osd", "crush", "add", "osd.0", "1", "root=default"]) self._exec(osd_opts + ["--mkfs", "--mkjournal"]) if version < pkg_resources.parse_version("0.94.0"): wait_for_line = "journal close" else: wait_for_line = "done with init" osd, _ = self._exec(osd_opts, wait_for_line=wait_for_line) if version >= pkg_resources.parse_version("12.0.0"): self._exec(ceph_opts + ["osd", "set-full-ratio", "0.95"]) self._exec(ceph_opts + ["osd", "set-backfillfull-ratio", "0.95"]) self._exec(ceph_opts + ["osd", "set-nearfull-ratio", "0.95"]) # Wait it's ready out = b"" while b"HEALTH_OK" not in out: ceph, out = self._exec(ceph_opts + ["health"], stdout=True) if b"HEALTH_ERR" in out: raise RuntimeError("Fail to deploy ceph") self.putenv("CEPH_CONF", conffile, True) self.putenv("CEPH_CONF", conffile) self.putenv("URL", "ceph://localhost:%d" % self.port) <|fim▁end|>
get_options
<|file_name|>ceph.py<|end_file_name|><|fim▁begin|># 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 os import uuid import pkg_resources from pifpaf import drivers class CephDriver(drivers.Driver): DEFAULT_PORT = 6790 def __init__(self, port=DEFAULT_PORT, **kwargs): """Create a new Ceph cluster.""" super(CephDriver, self).__init__(**kwargs) self.port = port @classmethod def get_options(cls): return [ {"param_decls": ["--port"], "type": int, "default": cls.DEFAULT_PORT, "help": "port to use for Ceph Monitor"}, ] def <|fim_middle|>(self): super(CephDriver, self)._setUp() self._ensure_xattr_support() fsid = str(uuid.uuid4()) conffile = os.path.join(self.tempdir, "ceph.conf") mondir = os.path.join(self.tempdir, "mon", "ceph-a") osddir = os.path.join(self.tempdir, "osd", "ceph-0") os.makedirs(mondir) os.makedirs(osddir) _, version = self._exec(["ceph", "--version"], stdout=True) version = version.decode("ascii").split()[2] version = pkg_resources.parse_version(version) if version < pkg_resources.parse_version("12.0.0"): extra = """ mon_osd_nearfull_ratio = 1 mon_osd_full_ratio = 1 osd_failsafe_nearfull_ratio = 1 osd_failsafe_full_ratio = 1 """ else: extra = """ mon_allow_pool_delete = true """ # FIXME(sileht): check availible space on /dev/shm # if os.path.exists("/dev/shm") and os.access('/dev/shm', os.W_OK): # journal_path = "/dev/shm/$cluster-$id-journal" # else: journal_path = "%s/osd/$cluster-$id/journal" % self.tempdir with open(conffile, "w") as f: f.write("""[global] fsid = %(fsid)s # no auth for now auth cluster required = none auth service required = none auth client required = none ## no replica osd pool default size = 1 osd pool default min size = 1 osd crush chooseleaf type = 0 ## some default path change run dir = %(tempdir)s pid file = %(tempdir)s/$type.$id.pid admin socket = %(tempdir)s/$cluster-$name.asok mon data = %(tempdir)s/mon/$cluster-$id osd data = %(tempdir)s/osd/$cluster-$id osd journal = %(journal_path)s log file = %(tempdir)s/$cluster-$name.log mon cluster log file = %(tempdir)s/$cluster.log # Only omap to have same behavior for all filesystems filestore xattr use omap = True # workaround for ext4 and last Jewel version osd max object name len = 256 osd max object namespace len = 64 osd op threads = 10 filestore max sync interval = 10001 filestore min sync interval = 10000 %(extra)s journal_aio = false journal_dio = false journal zero on create = false journal block align = false # run as file owner setuser match path = %(tempdir)s/$type/$cluster-$id [mon.a] host = localhost mon addr = 127.0.0.1:%(port)d """ % dict(fsid=fsid, tempdir=self.tempdir, port=self.port, journal_path=journal_path, extra=extra)) # noqa ceph_opts = ["ceph", "-c", conffile] mon_opts = ["ceph-mon", "-c", conffile, "--id", "a", "-d"] osd_opts = ["ceph-osd", "-c", conffile, "--id", "0", "-d", "-m", "127.0.0.1:%d" % self.port] # Create and start monitor self._exec(mon_opts + ["--mkfs"]) self._touch(os.path.join(mondir, "done")) mon, _ = self._exec( mon_opts, wait_for_line=r"mon.a@0\(leader\).mds e1 print_map") # Create and start OSD self._exec(ceph_opts + ["osd", "create"]) self._exec(ceph_opts + ["osd", "crush", "add", "osd.0", "1", "root=default"]) self._exec(osd_opts + ["--mkfs", "--mkjournal"]) if version < pkg_resources.parse_version("0.94.0"): wait_for_line = "journal close" else: wait_for_line = "done with init" osd, _ = self._exec(osd_opts, wait_for_line=wait_for_line) if version >= pkg_resources.parse_version("12.0.0"): self._exec(ceph_opts + ["osd", "set-full-ratio", "0.95"]) self._exec(ceph_opts + ["osd", "set-backfillfull-ratio", "0.95"]) self._exec(ceph_opts + ["osd", "set-nearfull-ratio", "0.95"]) # Wait it's ready out = b"" while b"HEALTH_OK" not in out: ceph, out = self._exec(ceph_opts + ["health"], stdout=True) if b"HEALTH_ERR" in out: raise RuntimeError("Fail to deploy ceph") self.putenv("CEPH_CONF", conffile, True) self.putenv("CEPH_CONF", conffile) self.putenv("URL", "ceph://localhost:%d" % self.port) <|fim▁end|>
_setUp
<|file_name|>dumpPHOTO.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python3 import sys from gi.repository import GExiv2 phototags = { 'Exif.Photo.ExposureTime': "Belichtung:\t", 'Exif.Photo.FNumber': "Blende:\t\tF", # 'Exif.Photo.ExposureProgram', 'Exif.Photo.ISOSpeedRatings': "ISO:\t\t", # 'Exif.Photo.SensitivityType', # 'Exif.Photo.ExifVersion', # 'Exif.Photo.DateTimeOriginal', # 'Exif.Photo.DateTimeDigitized', # 'Exif.Photo.ComponentsConfiguration', # 'Exif.Photo.CompressedBitsPerPixel', # 'Exif.Photo.ExposureBiasValue', # 'Exif.Photo.MaxApertureValue', # 'Exif.Photo.MeteringMode', # 'Exif.Photo.LightSource',<|fim▁hole|> for i in range(1, len(sys.argv)): metadata = GExiv2.Metadata(sys.argv[i]) print("file: {}".format(sys.argv[i])) for key in phototags: try: print("{}: {}".format(phototags[key], metadata[key])) except KeyError: continue<|fim▁end|>
# 'Exif.Photo.Flash', 'Exif.Photo.FocalLength': "Brennweite:\t" # 'Exif.Photo.MakerNote' }
<|file_name|>act_twitter.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # -*- coding: utf-8 -*- #<|fim▁hole|>""" SYNOPSIS TODO prog_base [-h,--help] [-v,--verbose] [--version] DESCRIPTION TODO This describes how to use this script. This docstring will be printed by the script if there is an error or if the user requests help (-h or --help). EXAMPLES TODO: Show some examples of how to use this script. EXIT STATUS TODO: List exit codes AUTHOR Rob Hawkins <[email protected]> LICENSE 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. VERSION 1.0.0 """ __author__ = "Rob Hawkins <[email protected]>" __version__ = "1.0.0" __date__ = "2013.12.01" # Version Date Notes # ------- ---------- ------------------------------------------------------- # 1.0.0 2013.12.01 Starting script template # import sys, os, traceback, argparse import time import re #from pexpect import run, spawn def test (): global options, args # TODO: Do something more interesting here... print 'Hello from the test() function!' def main (): global options, args # TODO: Do something more interesting here... print 'Hello world!' if __name__ == '__main__': try: start_time = time.time() #parser = argparse.ArgumentParser(description="This is the program description", usage=globals()['__doc__']) parser = argparse.ArgumentParser(description='This is the program description') parser.add_argument('--version', action='version', version='%(prog)s v'+__version__) parser.add_argument ('-v', '--verbose', action='store_true', help='produce verbose output') parser.add_argument ('-t', '--test', action='store_true', help='run test suite') args = parser.parse_args() #if len(args) < 1: # parser.error ('missing argument') if args.verbose: print time.asctime() if args.test: test() else: main() if args.verbose: print time.asctime() if args.verbose: print 'TOTAL TIME IN MINUTES:', if args.verbose: print (time.time() - start_time) / 60.0 sys.exit(0) except KeyboardInterrupt, e: # Ctrl-C raise e except SystemExit, e: # sys.exit() raise e except Exception, e: print 'ERROR, UNEXPECTED EXCEPTION' print str(e) traceback.print_exc() os._exit(1)<|fim▁end|>
# TODO prog_base.py - A starting template for Python scripts # # Copyright 2013 Robert B. Hawkins #
<|file_name|>act_twitter.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # -*- coding: utf-8 -*- # # TODO prog_base.py - A starting template for Python scripts # # Copyright 2013 Robert B. Hawkins # """ SYNOPSIS TODO prog_base [-h,--help] [-v,--verbose] [--version] DESCRIPTION TODO This describes how to use this script. This docstring will be printed by the script if there is an error or if the user requests help (-h or --help). EXAMPLES TODO: Show some examples of how to use this script. EXIT STATUS TODO: List exit codes AUTHOR Rob Hawkins <[email protected]> LICENSE 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. VERSION 1.0.0 """ __author__ = "Rob Hawkins <[email protected]>" __version__ = "1.0.0" __date__ = "2013.12.01" # Version Date Notes # ------- ---------- ------------------------------------------------------- # 1.0.0 2013.12.01 Starting script template # import sys, os, traceback, argparse import time import re #from pexpect import run, spawn def test (): <|fim_middle|> def main (): global options, args # TODO: Do something more interesting here... print 'Hello world!' if __name__ == '__main__': try: start_time = time.time() #parser = argparse.ArgumentParser(description="This is the program description", usage=globals()['__doc__']) parser = argparse.ArgumentParser(description='This is the program description') parser.add_argument('--version', action='version', version='%(prog)s v'+__version__) parser.add_argument ('-v', '--verbose', action='store_true', help='produce verbose output') parser.add_argument ('-t', '--test', action='store_true', help='run test suite') args = parser.parse_args() #if len(args) < 1: # parser.error ('missing argument') if args.verbose: print time.asctime() if args.test: test() else: main() if args.verbose: print time.asctime() if args.verbose: print 'TOTAL TIME IN MINUTES:', if args.verbose: print (time.time() - start_time) / 60.0 sys.exit(0) except KeyboardInterrupt, e: # Ctrl-C raise e except SystemExit, e: # sys.exit() raise e except Exception, e: print 'ERROR, UNEXPECTED EXCEPTION' print str(e) traceback.print_exc() os._exit(1) <|fim▁end|>
global options, args # TODO: Do something more interesting here... print 'Hello from the test() function!'
<|file_name|>act_twitter.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # -*- coding: utf-8 -*- # # TODO prog_base.py - A starting template for Python scripts # # Copyright 2013 Robert B. Hawkins # """ SYNOPSIS TODO prog_base [-h,--help] [-v,--verbose] [--version] DESCRIPTION TODO This describes how to use this script. This docstring will be printed by the script if there is an error or if the user requests help (-h or --help). EXAMPLES TODO: Show some examples of how to use this script. EXIT STATUS TODO: List exit codes AUTHOR Rob Hawkins <[email protected]> LICENSE 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. VERSION 1.0.0 """ __author__ = "Rob Hawkins <[email protected]>" __version__ = "1.0.0" __date__ = "2013.12.01" # Version Date Notes # ------- ---------- ------------------------------------------------------- # 1.0.0 2013.12.01 Starting script template # import sys, os, traceback, argparse import time import re #from pexpect import run, spawn def test (): global options, args # TODO: Do something more interesting here... print 'Hello from the test() function!' def main (): <|fim_middle|> if __name__ == '__main__': try: start_time = time.time() #parser = argparse.ArgumentParser(description="This is the program description", usage=globals()['__doc__']) parser = argparse.ArgumentParser(description='This is the program description') parser.add_argument('--version', action='version', version='%(prog)s v'+__version__) parser.add_argument ('-v', '--verbose', action='store_true', help='produce verbose output') parser.add_argument ('-t', '--test', action='store_true', help='run test suite') args = parser.parse_args() #if len(args) < 1: # parser.error ('missing argument') if args.verbose: print time.asctime() if args.test: test() else: main() if args.verbose: print time.asctime() if args.verbose: print 'TOTAL TIME IN MINUTES:', if args.verbose: print (time.time() - start_time) / 60.0 sys.exit(0) except KeyboardInterrupt, e: # Ctrl-C raise e except SystemExit, e: # sys.exit() raise e except Exception, e: print 'ERROR, UNEXPECTED EXCEPTION' print str(e) traceback.print_exc() os._exit(1) <|fim▁end|>
global options, args # TODO: Do something more interesting here... print 'Hello world!'
<|file_name|>act_twitter.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # -*- coding: utf-8 -*- # # TODO prog_base.py - A starting template for Python scripts # # Copyright 2013 Robert B. Hawkins # """ SYNOPSIS TODO prog_base [-h,--help] [-v,--verbose] [--version] DESCRIPTION TODO This describes how to use this script. This docstring will be printed by the script if there is an error or if the user requests help (-h or --help). EXAMPLES TODO: Show some examples of how to use this script. EXIT STATUS TODO: List exit codes AUTHOR Rob Hawkins <[email protected]> LICENSE 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. VERSION 1.0.0 """ __author__ = "Rob Hawkins <[email protected]>" __version__ = "1.0.0" __date__ = "2013.12.01" # Version Date Notes # ------- ---------- ------------------------------------------------------- # 1.0.0 2013.12.01 Starting script template # import sys, os, traceback, argparse import time import re #from pexpect import run, spawn def test (): global options, args # TODO: Do something more interesting here... print 'Hello from the test() function!' def main (): global options, args # TODO: Do something more interesting here... print 'Hello world!' if __name__ == '__main__': <|fim_middle|> <|fim▁end|>
try: start_time = time.time() #parser = argparse.ArgumentParser(description="This is the program description", usage=globals()['__doc__']) parser = argparse.ArgumentParser(description='This is the program description') parser.add_argument('--version', action='version', version='%(prog)s v'+__version__) parser.add_argument ('-v', '--verbose', action='store_true', help='produce verbose output') parser.add_argument ('-t', '--test', action='store_true', help='run test suite') args = parser.parse_args() #if len(args) < 1: # parser.error ('missing argument') if args.verbose: print time.asctime() if args.test: test() else: main() if args.verbose: print time.asctime() if args.verbose: print 'TOTAL TIME IN MINUTES:', if args.verbose: print (time.time() - start_time) / 60.0 sys.exit(0) except KeyboardInterrupt, e: # Ctrl-C raise e except SystemExit, e: # sys.exit() raise e except Exception, e: print 'ERROR, UNEXPECTED EXCEPTION' print str(e) traceback.print_exc() os._exit(1)
<|file_name|>act_twitter.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # -*- coding: utf-8 -*- # # TODO prog_base.py - A starting template for Python scripts # # Copyright 2013 Robert B. Hawkins # """ SYNOPSIS TODO prog_base [-h,--help] [-v,--verbose] [--version] DESCRIPTION TODO This describes how to use this script. This docstring will be printed by the script if there is an error or if the user requests help (-h or --help). EXAMPLES TODO: Show some examples of how to use this script. EXIT STATUS TODO: List exit codes AUTHOR Rob Hawkins <[email protected]> LICENSE 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. VERSION 1.0.0 """ __author__ = "Rob Hawkins <[email protected]>" __version__ = "1.0.0" __date__ = "2013.12.01" # Version Date Notes # ------- ---------- ------------------------------------------------------- # 1.0.0 2013.12.01 Starting script template # import sys, os, traceback, argparse import time import re #from pexpect import run, spawn def test (): global options, args # TODO: Do something more interesting here... print 'Hello from the test() function!' def main (): global options, args # TODO: Do something more interesting here... print 'Hello world!' if __name__ == '__main__': try: start_time = time.time() #parser = argparse.ArgumentParser(description="This is the program description", usage=globals()['__doc__']) parser = argparse.ArgumentParser(description='This is the program description') parser.add_argument('--version', action='version', version='%(prog)s v'+__version__) parser.add_argument ('-v', '--verbose', action='store_true', help='produce verbose output') parser.add_argument ('-t', '--test', action='store_true', help='run test suite') args = parser.parse_args() #if len(args) < 1: # parser.error ('missing argument') if args.verbose: <|fim_middle|> if args.test: test() else: main() if args.verbose: print time.asctime() if args.verbose: print 'TOTAL TIME IN MINUTES:', if args.verbose: print (time.time() - start_time) / 60.0 sys.exit(0) except KeyboardInterrupt, e: # Ctrl-C raise e except SystemExit, e: # sys.exit() raise e except Exception, e: print 'ERROR, UNEXPECTED EXCEPTION' print str(e) traceback.print_exc() os._exit(1) <|fim▁end|>
print time.asctime()
<|file_name|>act_twitter.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # -*- coding: utf-8 -*- # # TODO prog_base.py - A starting template for Python scripts # # Copyright 2013 Robert B. Hawkins # """ SYNOPSIS TODO prog_base [-h,--help] [-v,--verbose] [--version] DESCRIPTION TODO This describes how to use this script. This docstring will be printed by the script if there is an error or if the user requests help (-h or --help). EXAMPLES TODO: Show some examples of how to use this script. EXIT STATUS TODO: List exit codes AUTHOR Rob Hawkins <[email protected]> LICENSE 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. VERSION 1.0.0 """ __author__ = "Rob Hawkins <[email protected]>" __version__ = "1.0.0" __date__ = "2013.12.01" # Version Date Notes # ------- ---------- ------------------------------------------------------- # 1.0.0 2013.12.01 Starting script template # import sys, os, traceback, argparse import time import re #from pexpect import run, spawn def test (): global options, args # TODO: Do something more interesting here... print 'Hello from the test() function!' def main (): global options, args # TODO: Do something more interesting here... print 'Hello world!' if __name__ == '__main__': try: start_time = time.time() #parser = argparse.ArgumentParser(description="This is the program description", usage=globals()['__doc__']) parser = argparse.ArgumentParser(description='This is the program description') parser.add_argument('--version', action='version', version='%(prog)s v'+__version__) parser.add_argument ('-v', '--verbose', action='store_true', help='produce verbose output') parser.add_argument ('-t', '--test', action='store_true', help='run test suite') args = parser.parse_args() #if len(args) < 1: # parser.error ('missing argument') if args.verbose: print time.asctime() if args.test: <|fim_middle|> else: main() if args.verbose: print time.asctime() if args.verbose: print 'TOTAL TIME IN MINUTES:', if args.verbose: print (time.time() - start_time) / 60.0 sys.exit(0) except KeyboardInterrupt, e: # Ctrl-C raise e except SystemExit, e: # sys.exit() raise e except Exception, e: print 'ERROR, UNEXPECTED EXCEPTION' print str(e) traceback.print_exc() os._exit(1) <|fim▁end|>
test()
<|file_name|>act_twitter.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # -*- coding: utf-8 -*- # # TODO prog_base.py - A starting template for Python scripts # # Copyright 2013 Robert B. Hawkins # """ SYNOPSIS TODO prog_base [-h,--help] [-v,--verbose] [--version] DESCRIPTION TODO This describes how to use this script. This docstring will be printed by the script if there is an error or if the user requests help (-h or --help). EXAMPLES TODO: Show some examples of how to use this script. EXIT STATUS TODO: List exit codes AUTHOR Rob Hawkins <[email protected]> LICENSE 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. VERSION 1.0.0 """ __author__ = "Rob Hawkins <[email protected]>" __version__ = "1.0.0" __date__ = "2013.12.01" # Version Date Notes # ------- ---------- ------------------------------------------------------- # 1.0.0 2013.12.01 Starting script template # import sys, os, traceback, argparse import time import re #from pexpect import run, spawn def test (): global options, args # TODO: Do something more interesting here... print 'Hello from the test() function!' def main (): global options, args # TODO: Do something more interesting here... print 'Hello world!' if __name__ == '__main__': try: start_time = time.time() #parser = argparse.ArgumentParser(description="This is the program description", usage=globals()['__doc__']) parser = argparse.ArgumentParser(description='This is the program description') parser.add_argument('--version', action='version', version='%(prog)s v'+__version__) parser.add_argument ('-v', '--verbose', action='store_true', help='produce verbose output') parser.add_argument ('-t', '--test', action='store_true', help='run test suite') args = parser.parse_args() #if len(args) < 1: # parser.error ('missing argument') if args.verbose: print time.asctime() if args.test: test() else: <|fim_middle|> if args.verbose: print time.asctime() if args.verbose: print 'TOTAL TIME IN MINUTES:', if args.verbose: print (time.time() - start_time) / 60.0 sys.exit(0) except KeyboardInterrupt, e: # Ctrl-C raise e except SystemExit, e: # sys.exit() raise e except Exception, e: print 'ERROR, UNEXPECTED EXCEPTION' print str(e) traceback.print_exc() os._exit(1) <|fim▁end|>
main()
<|file_name|>act_twitter.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # -*- coding: utf-8 -*- # # TODO prog_base.py - A starting template for Python scripts # # Copyright 2013 Robert B. Hawkins # """ SYNOPSIS TODO prog_base [-h,--help] [-v,--verbose] [--version] DESCRIPTION TODO This describes how to use this script. This docstring will be printed by the script if there is an error or if the user requests help (-h or --help). EXAMPLES TODO: Show some examples of how to use this script. EXIT STATUS TODO: List exit codes AUTHOR Rob Hawkins <[email protected]> LICENSE 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. VERSION 1.0.0 """ __author__ = "Rob Hawkins <[email protected]>" __version__ = "1.0.0" __date__ = "2013.12.01" # Version Date Notes # ------- ---------- ------------------------------------------------------- # 1.0.0 2013.12.01 Starting script template # import sys, os, traceback, argparse import time import re #from pexpect import run, spawn def test (): global options, args # TODO: Do something more interesting here... print 'Hello from the test() function!' def main (): global options, args # TODO: Do something more interesting here... print 'Hello world!' if __name__ == '__main__': try: start_time = time.time() #parser = argparse.ArgumentParser(description="This is the program description", usage=globals()['__doc__']) parser = argparse.ArgumentParser(description='This is the program description') parser.add_argument('--version', action='version', version='%(prog)s v'+__version__) parser.add_argument ('-v', '--verbose', action='store_true', help='produce verbose output') parser.add_argument ('-t', '--test', action='store_true', help='run test suite') args = parser.parse_args() #if len(args) < 1: # parser.error ('missing argument') if args.verbose: print time.asctime() if args.test: test() else: main() if args.verbose: <|fim_middle|> if args.verbose: print 'TOTAL TIME IN MINUTES:', if args.verbose: print (time.time() - start_time) / 60.0 sys.exit(0) except KeyboardInterrupt, e: # Ctrl-C raise e except SystemExit, e: # sys.exit() raise e except Exception, e: print 'ERROR, UNEXPECTED EXCEPTION' print str(e) traceback.print_exc() os._exit(1) <|fim▁end|>
print time.asctime()
<|file_name|>act_twitter.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # -*- coding: utf-8 -*- # # TODO prog_base.py - A starting template for Python scripts # # Copyright 2013 Robert B. Hawkins # """ SYNOPSIS TODO prog_base [-h,--help] [-v,--verbose] [--version] DESCRIPTION TODO This describes how to use this script. This docstring will be printed by the script if there is an error or if the user requests help (-h or --help). EXAMPLES TODO: Show some examples of how to use this script. EXIT STATUS TODO: List exit codes AUTHOR Rob Hawkins <[email protected]> LICENSE 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. VERSION 1.0.0 """ __author__ = "Rob Hawkins <[email protected]>" __version__ = "1.0.0" __date__ = "2013.12.01" # Version Date Notes # ------- ---------- ------------------------------------------------------- # 1.0.0 2013.12.01 Starting script template # import sys, os, traceback, argparse import time import re #from pexpect import run, spawn def test (): global options, args # TODO: Do something more interesting here... print 'Hello from the test() function!' def main (): global options, args # TODO: Do something more interesting here... print 'Hello world!' if __name__ == '__main__': try: start_time = time.time() #parser = argparse.ArgumentParser(description="This is the program description", usage=globals()['__doc__']) parser = argparse.ArgumentParser(description='This is the program description') parser.add_argument('--version', action='version', version='%(prog)s v'+__version__) parser.add_argument ('-v', '--verbose', action='store_true', help='produce verbose output') parser.add_argument ('-t', '--test', action='store_true', help='run test suite') args = parser.parse_args() #if len(args) < 1: # parser.error ('missing argument') if args.verbose: print time.asctime() if args.test: test() else: main() if args.verbose: print time.asctime() if args.verbose: <|fim_middle|> if args.verbose: print (time.time() - start_time) / 60.0 sys.exit(0) except KeyboardInterrupt, e: # Ctrl-C raise e except SystemExit, e: # sys.exit() raise e except Exception, e: print 'ERROR, UNEXPECTED EXCEPTION' print str(e) traceback.print_exc() os._exit(1) <|fim▁end|>
print 'TOTAL TIME IN MINUTES:',
<|file_name|>act_twitter.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # -*- coding: utf-8 -*- # # TODO prog_base.py - A starting template for Python scripts # # Copyright 2013 Robert B. Hawkins # """ SYNOPSIS TODO prog_base [-h,--help] [-v,--verbose] [--version] DESCRIPTION TODO This describes how to use this script. This docstring will be printed by the script if there is an error or if the user requests help (-h or --help). EXAMPLES TODO: Show some examples of how to use this script. EXIT STATUS TODO: List exit codes AUTHOR Rob Hawkins <[email protected]> LICENSE 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. VERSION 1.0.0 """ __author__ = "Rob Hawkins <[email protected]>" __version__ = "1.0.0" __date__ = "2013.12.01" # Version Date Notes # ------- ---------- ------------------------------------------------------- # 1.0.0 2013.12.01 Starting script template # import sys, os, traceback, argparse import time import re #from pexpect import run, spawn def test (): global options, args # TODO: Do something more interesting here... print 'Hello from the test() function!' def main (): global options, args # TODO: Do something more interesting here... print 'Hello world!' if __name__ == '__main__': try: start_time = time.time() #parser = argparse.ArgumentParser(description="This is the program description", usage=globals()['__doc__']) parser = argparse.ArgumentParser(description='This is the program description') parser.add_argument('--version', action='version', version='%(prog)s v'+__version__) parser.add_argument ('-v', '--verbose', action='store_true', help='produce verbose output') parser.add_argument ('-t', '--test', action='store_true', help='run test suite') args = parser.parse_args() #if len(args) < 1: # parser.error ('missing argument') if args.verbose: print time.asctime() if args.test: test() else: main() if args.verbose: print time.asctime() if args.verbose: print 'TOTAL TIME IN MINUTES:', if args.verbose: <|fim_middle|> sys.exit(0) except KeyboardInterrupt, e: # Ctrl-C raise e except SystemExit, e: # sys.exit() raise e except Exception, e: print 'ERROR, UNEXPECTED EXCEPTION' print str(e) traceback.print_exc() os._exit(1) <|fim▁end|>
print (time.time() - start_time) / 60.0
<|file_name|>act_twitter.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # -*- coding: utf-8 -*- # # TODO prog_base.py - A starting template for Python scripts # # Copyright 2013 Robert B. Hawkins # """ SYNOPSIS TODO prog_base [-h,--help] [-v,--verbose] [--version] DESCRIPTION TODO This describes how to use this script. This docstring will be printed by the script if there is an error or if the user requests help (-h or --help). EXAMPLES TODO: Show some examples of how to use this script. EXIT STATUS TODO: List exit codes AUTHOR Rob Hawkins <[email protected]> LICENSE 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. VERSION 1.0.0 """ __author__ = "Rob Hawkins <[email protected]>" __version__ = "1.0.0" __date__ = "2013.12.01" # Version Date Notes # ------- ---------- ------------------------------------------------------- # 1.0.0 2013.12.01 Starting script template # import sys, os, traceback, argparse import time import re #from pexpect import run, spawn def <|fim_middle|> (): global options, args # TODO: Do something more interesting here... print 'Hello from the test() function!' def main (): global options, args # TODO: Do something more interesting here... print 'Hello world!' if __name__ == '__main__': try: start_time = time.time() #parser = argparse.ArgumentParser(description="This is the program description", usage=globals()['__doc__']) parser = argparse.ArgumentParser(description='This is the program description') parser.add_argument('--version', action='version', version='%(prog)s v'+__version__) parser.add_argument ('-v', '--verbose', action='store_true', help='produce verbose output') parser.add_argument ('-t', '--test', action='store_true', help='run test suite') args = parser.parse_args() #if len(args) < 1: # parser.error ('missing argument') if args.verbose: print time.asctime() if args.test: test() else: main() if args.verbose: print time.asctime() if args.verbose: print 'TOTAL TIME IN MINUTES:', if args.verbose: print (time.time() - start_time) / 60.0 sys.exit(0) except KeyboardInterrupt, e: # Ctrl-C raise e except SystemExit, e: # sys.exit() raise e except Exception, e: print 'ERROR, UNEXPECTED EXCEPTION' print str(e) traceback.print_exc() os._exit(1) <|fim▁end|>
test
<|file_name|>act_twitter.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # -*- coding: utf-8 -*- # # TODO prog_base.py - A starting template for Python scripts # # Copyright 2013 Robert B. Hawkins # """ SYNOPSIS TODO prog_base [-h,--help] [-v,--verbose] [--version] DESCRIPTION TODO This describes how to use this script. This docstring will be printed by the script if there is an error or if the user requests help (-h or --help). EXAMPLES TODO: Show some examples of how to use this script. EXIT STATUS TODO: List exit codes AUTHOR Rob Hawkins <[email protected]> LICENSE 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. VERSION 1.0.0 """ __author__ = "Rob Hawkins <[email protected]>" __version__ = "1.0.0" __date__ = "2013.12.01" # Version Date Notes # ------- ---------- ------------------------------------------------------- # 1.0.0 2013.12.01 Starting script template # import sys, os, traceback, argparse import time import re #from pexpect import run, spawn def test (): global options, args # TODO: Do something more interesting here... print 'Hello from the test() function!' def <|fim_middle|> (): global options, args # TODO: Do something more interesting here... print 'Hello world!' if __name__ == '__main__': try: start_time = time.time() #parser = argparse.ArgumentParser(description="This is the program description", usage=globals()['__doc__']) parser = argparse.ArgumentParser(description='This is the program description') parser.add_argument('--version', action='version', version='%(prog)s v'+__version__) parser.add_argument ('-v', '--verbose', action='store_true', help='produce verbose output') parser.add_argument ('-t', '--test', action='store_true', help='run test suite') args = parser.parse_args() #if len(args) < 1: # parser.error ('missing argument') if args.verbose: print time.asctime() if args.test: test() else: main() if args.verbose: print time.asctime() if args.verbose: print 'TOTAL TIME IN MINUTES:', if args.verbose: print (time.time() - start_time) / 60.0 sys.exit(0) except KeyboardInterrupt, e: # Ctrl-C raise e except SystemExit, e: # sys.exit() raise e except Exception, e: print 'ERROR, UNEXPECTED EXCEPTION' print str(e) traceback.print_exc() os._exit(1) <|fim▁end|>
main
<|file_name|>indexes.py<|end_file_name|><|fim▁begin|># Copyright 2013 Donald Stufft # # 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. from __future__ import absolute_import, division, print_function from __future__ import unicode_literals import hashlib import os from elasticsearch import Elasticsearch, TransportError from elasticsearch.helpers import bulk_index from warehouse.utils import AttributeDict class Index(object): _index = "warehouse" def __init__(self, models, config): self.models = models self.config = config self.es = Elasticsearch( hosts=self.config.hosts, **self.config.get("client_options", {}) ) self.types = AttributeDict() def register(self, type_): obj = type_(self) self.types[obj._type] = obj def reindex(self, index=None, alias=True, keep_old=False): # Generate an Index Name for Warehouse index = "".join([ index if index is not None else self._index, hashlib.md5(os.urandom(16)).hexdigest()[:8], ]) <|fim▁hole|> for doc_type in self.types.values() }, }) # Index everything into the new index for doc_type in self.types.values(): doc_type.index_all(index=index) # Update the alias unless we've been told not to if alias: self.update_alias(self._index, index, keep_old=keep_old) def update_alias(self, alias, index, keep_old=False): # Get the old index from ElasticSearch try: old_index = self.es.indices.get_alias(self._index).keys()[0] except TransportError as exc: if not exc.status_code == 404: raise old_index = None # Remove the alias to the old index if it exists if old_index is not None: actions = [{"remove": {"index": old_index, "alias": alias}}] else: actions = [] # Add the alias to the new index actions += [{"add": {"index": index, "alias": alias}}] # Update To the New Index self.es.indices.update_aliases({"actions": actions}) # Delete the old index if it exists and unless we're keeping it if not keep_old and old_index is not None: self.es.indices.delete(old_index) class BaseMapping(object): SEARCH_LIMIT = 25 def __init__(self, index): self.index = index def get_mapping(self): raise NotImplementedError def get_indexable(self): raise NotImplementedError def extract_id(self, item): raise NotImplementedError def extract_document(self, item): raise NotImplementedError def index_all(self, index=None): # Determine which index we are indexing into _index = index if index is not None else self.index._index # Bulk Index our documents bulk_index( self.index.es, [ { "_index": _index, "_type": self._type, "_id": self.extract_id(item), "_source": self.extract_document(item), } for item in self.get_indexable() ], ) def search(self, query): raise NotImplementedError<|fim▁end|>
# Create this index self.es.indices.create(index, { "mappings": { doc_type._type: doc_type.get_mapping()
<|file_name|>indexes.py<|end_file_name|><|fim▁begin|># Copyright 2013 Donald Stufft # # 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. from __future__ import absolute_import, division, print_function from __future__ import unicode_literals import hashlib import os from elasticsearch import Elasticsearch, TransportError from elasticsearch.helpers import bulk_index from warehouse.utils import AttributeDict class Index(object): <|fim_middle|> class BaseMapping(object): SEARCH_LIMIT = 25 def __init__(self, index): self.index = index def get_mapping(self): raise NotImplementedError def get_indexable(self): raise NotImplementedError def extract_id(self, item): raise NotImplementedError def extract_document(self, item): raise NotImplementedError def index_all(self, index=None): # Determine which index we are indexing into _index = index if index is not None else self.index._index # Bulk Index our documents bulk_index( self.index.es, [ { "_index": _index, "_type": self._type, "_id": self.extract_id(item), "_source": self.extract_document(item), } for item in self.get_indexable() ], ) def search(self, query): raise NotImplementedError <|fim▁end|>
_index = "warehouse" def __init__(self, models, config): self.models = models self.config = config self.es = Elasticsearch( hosts=self.config.hosts, **self.config.get("client_options", {}) ) self.types = AttributeDict() def register(self, type_): obj = type_(self) self.types[obj._type] = obj def reindex(self, index=None, alias=True, keep_old=False): # Generate an Index Name for Warehouse index = "".join([ index if index is not None else self._index, hashlib.md5(os.urandom(16)).hexdigest()[:8], ]) # Create this index self.es.indices.create(index, { "mappings": { doc_type._type: doc_type.get_mapping() for doc_type in self.types.values() }, }) # Index everything into the new index for doc_type in self.types.values(): doc_type.index_all(index=index) # Update the alias unless we've been told not to if alias: self.update_alias(self._index, index, keep_old=keep_old) def update_alias(self, alias, index, keep_old=False): # Get the old index from ElasticSearch try: old_index = self.es.indices.get_alias(self._index).keys()[0] except TransportError as exc: if not exc.status_code == 404: raise old_index = None # Remove the alias to the old index if it exists if old_index is not None: actions = [{"remove": {"index": old_index, "alias": alias}}] else: actions = [] # Add the alias to the new index actions += [{"add": {"index": index, "alias": alias}}] # Update To the New Index self.es.indices.update_aliases({"actions": actions}) # Delete the old index if it exists and unless we're keeping it if not keep_old and old_index is not None: self.es.indices.delete(old_index)
<|file_name|>indexes.py<|end_file_name|><|fim▁begin|># Copyright 2013 Donald Stufft # # 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. from __future__ import absolute_import, division, print_function from __future__ import unicode_literals import hashlib import os from elasticsearch import Elasticsearch, TransportError from elasticsearch.helpers import bulk_index from warehouse.utils import AttributeDict class Index(object): _index = "warehouse" def __init__(self, models, config): <|fim_middle|> def register(self, type_): obj = type_(self) self.types[obj._type] = obj def reindex(self, index=None, alias=True, keep_old=False): # Generate an Index Name for Warehouse index = "".join([ index if index is not None else self._index, hashlib.md5(os.urandom(16)).hexdigest()[:8], ]) # Create this index self.es.indices.create(index, { "mappings": { doc_type._type: doc_type.get_mapping() for doc_type in self.types.values() }, }) # Index everything into the new index for doc_type in self.types.values(): doc_type.index_all(index=index) # Update the alias unless we've been told not to if alias: self.update_alias(self._index, index, keep_old=keep_old) def update_alias(self, alias, index, keep_old=False): # Get the old index from ElasticSearch try: old_index = self.es.indices.get_alias(self._index).keys()[0] except TransportError as exc: if not exc.status_code == 404: raise old_index = None # Remove the alias to the old index if it exists if old_index is not None: actions = [{"remove": {"index": old_index, "alias": alias}}] else: actions = [] # Add the alias to the new index actions += [{"add": {"index": index, "alias": alias}}] # Update To the New Index self.es.indices.update_aliases({"actions": actions}) # Delete the old index if it exists and unless we're keeping it if not keep_old and old_index is not None: self.es.indices.delete(old_index) class BaseMapping(object): SEARCH_LIMIT = 25 def __init__(self, index): self.index = index def get_mapping(self): raise NotImplementedError def get_indexable(self): raise NotImplementedError def extract_id(self, item): raise NotImplementedError def extract_document(self, item): raise NotImplementedError def index_all(self, index=None): # Determine which index we are indexing into _index = index if index is not None else self.index._index # Bulk Index our documents bulk_index( self.index.es, [ { "_index": _index, "_type": self._type, "_id": self.extract_id(item), "_source": self.extract_document(item), } for item in self.get_indexable() ], ) def search(self, query): raise NotImplementedError <|fim▁end|>
self.models = models self.config = config self.es = Elasticsearch( hosts=self.config.hosts, **self.config.get("client_options", {}) ) self.types = AttributeDict()
<|file_name|>indexes.py<|end_file_name|><|fim▁begin|># Copyright 2013 Donald Stufft # # 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. from __future__ import absolute_import, division, print_function from __future__ import unicode_literals import hashlib import os from elasticsearch import Elasticsearch, TransportError from elasticsearch.helpers import bulk_index from warehouse.utils import AttributeDict class Index(object): _index = "warehouse" def __init__(self, models, config): self.models = models self.config = config self.es = Elasticsearch( hosts=self.config.hosts, **self.config.get("client_options", {}) ) self.types = AttributeDict() def register(self, type_): <|fim_middle|> def reindex(self, index=None, alias=True, keep_old=False): # Generate an Index Name for Warehouse index = "".join([ index if index is not None else self._index, hashlib.md5(os.urandom(16)).hexdigest()[:8], ]) # Create this index self.es.indices.create(index, { "mappings": { doc_type._type: doc_type.get_mapping() for doc_type in self.types.values() }, }) # Index everything into the new index for doc_type in self.types.values(): doc_type.index_all(index=index) # Update the alias unless we've been told not to if alias: self.update_alias(self._index, index, keep_old=keep_old) def update_alias(self, alias, index, keep_old=False): # Get the old index from ElasticSearch try: old_index = self.es.indices.get_alias(self._index).keys()[0] except TransportError as exc: if not exc.status_code == 404: raise old_index = None # Remove the alias to the old index if it exists if old_index is not None: actions = [{"remove": {"index": old_index, "alias": alias}}] else: actions = [] # Add the alias to the new index actions += [{"add": {"index": index, "alias": alias}}] # Update To the New Index self.es.indices.update_aliases({"actions": actions}) # Delete the old index if it exists and unless we're keeping it if not keep_old and old_index is not None: self.es.indices.delete(old_index) class BaseMapping(object): SEARCH_LIMIT = 25 def __init__(self, index): self.index = index def get_mapping(self): raise NotImplementedError def get_indexable(self): raise NotImplementedError def extract_id(self, item): raise NotImplementedError def extract_document(self, item): raise NotImplementedError def index_all(self, index=None): # Determine which index we are indexing into _index = index if index is not None else self.index._index # Bulk Index our documents bulk_index( self.index.es, [ { "_index": _index, "_type": self._type, "_id": self.extract_id(item), "_source": self.extract_document(item), } for item in self.get_indexable() ], ) def search(self, query): raise NotImplementedError <|fim▁end|>
obj = type_(self) self.types[obj._type] = obj
<|file_name|>indexes.py<|end_file_name|><|fim▁begin|># Copyright 2013 Donald Stufft # # 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. from __future__ import absolute_import, division, print_function from __future__ import unicode_literals import hashlib import os from elasticsearch import Elasticsearch, TransportError from elasticsearch.helpers import bulk_index from warehouse.utils import AttributeDict class Index(object): _index = "warehouse" def __init__(self, models, config): self.models = models self.config = config self.es = Elasticsearch( hosts=self.config.hosts, **self.config.get("client_options", {}) ) self.types = AttributeDict() def register(self, type_): obj = type_(self) self.types[obj._type] = obj def reindex(self, index=None, alias=True, keep_old=False): # Generate an Index Name for Warehouse <|fim_middle|> def update_alias(self, alias, index, keep_old=False): # Get the old index from ElasticSearch try: old_index = self.es.indices.get_alias(self._index).keys()[0] except TransportError as exc: if not exc.status_code == 404: raise old_index = None # Remove the alias to the old index if it exists if old_index is not None: actions = [{"remove": {"index": old_index, "alias": alias}}] else: actions = [] # Add the alias to the new index actions += [{"add": {"index": index, "alias": alias}}] # Update To the New Index self.es.indices.update_aliases({"actions": actions}) # Delete the old index if it exists and unless we're keeping it if not keep_old and old_index is not None: self.es.indices.delete(old_index) class BaseMapping(object): SEARCH_LIMIT = 25 def __init__(self, index): self.index = index def get_mapping(self): raise NotImplementedError def get_indexable(self): raise NotImplementedError def extract_id(self, item): raise NotImplementedError def extract_document(self, item): raise NotImplementedError def index_all(self, index=None): # Determine which index we are indexing into _index = index if index is not None else self.index._index # Bulk Index our documents bulk_index( self.index.es, [ { "_index": _index, "_type": self._type, "_id": self.extract_id(item), "_source": self.extract_document(item), } for item in self.get_indexable() ], ) def search(self, query): raise NotImplementedError <|fim▁end|>
index = "".join([ index if index is not None else self._index, hashlib.md5(os.urandom(16)).hexdigest()[:8], ]) # Create this index self.es.indices.create(index, { "mappings": { doc_type._type: doc_type.get_mapping() for doc_type in self.types.values() }, }) # Index everything into the new index for doc_type in self.types.values(): doc_type.index_all(index=index) # Update the alias unless we've been told not to if alias: self.update_alias(self._index, index, keep_old=keep_old)
<|file_name|>indexes.py<|end_file_name|><|fim▁begin|># Copyright 2013 Donald Stufft # # 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. from __future__ import absolute_import, division, print_function from __future__ import unicode_literals import hashlib import os from elasticsearch import Elasticsearch, TransportError from elasticsearch.helpers import bulk_index from warehouse.utils import AttributeDict class Index(object): _index = "warehouse" def __init__(self, models, config): self.models = models self.config = config self.es = Elasticsearch( hosts=self.config.hosts, **self.config.get("client_options", {}) ) self.types = AttributeDict() def register(self, type_): obj = type_(self) self.types[obj._type] = obj def reindex(self, index=None, alias=True, keep_old=False): # Generate an Index Name for Warehouse index = "".join([ index if index is not None else self._index, hashlib.md5(os.urandom(16)).hexdigest()[:8], ]) # Create this index self.es.indices.create(index, { "mappings": { doc_type._type: doc_type.get_mapping() for doc_type in self.types.values() }, }) # Index everything into the new index for doc_type in self.types.values(): doc_type.index_all(index=index) # Update the alias unless we've been told not to if alias: self.update_alias(self._index, index, keep_old=keep_old) def update_alias(self, alias, index, keep_old=False): # Get the old index from ElasticSearch <|fim_middle|> class BaseMapping(object): SEARCH_LIMIT = 25 def __init__(self, index): self.index = index def get_mapping(self): raise NotImplementedError def get_indexable(self): raise NotImplementedError def extract_id(self, item): raise NotImplementedError def extract_document(self, item): raise NotImplementedError def index_all(self, index=None): # Determine which index we are indexing into _index = index if index is not None else self.index._index # Bulk Index our documents bulk_index( self.index.es, [ { "_index": _index, "_type": self._type, "_id": self.extract_id(item), "_source": self.extract_document(item), } for item in self.get_indexable() ], ) def search(self, query): raise NotImplementedError <|fim▁end|>
try: old_index = self.es.indices.get_alias(self._index).keys()[0] except TransportError as exc: if not exc.status_code == 404: raise old_index = None # Remove the alias to the old index if it exists if old_index is not None: actions = [{"remove": {"index": old_index, "alias": alias}}] else: actions = [] # Add the alias to the new index actions += [{"add": {"index": index, "alias": alias}}] # Update To the New Index self.es.indices.update_aliases({"actions": actions}) # Delete the old index if it exists and unless we're keeping it if not keep_old and old_index is not None: self.es.indices.delete(old_index)
<|file_name|>indexes.py<|end_file_name|><|fim▁begin|># Copyright 2013 Donald Stufft # # 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. from __future__ import absolute_import, division, print_function from __future__ import unicode_literals import hashlib import os from elasticsearch import Elasticsearch, TransportError from elasticsearch.helpers import bulk_index from warehouse.utils import AttributeDict class Index(object): _index = "warehouse" def __init__(self, models, config): self.models = models self.config = config self.es = Elasticsearch( hosts=self.config.hosts, **self.config.get("client_options", {}) ) self.types = AttributeDict() def register(self, type_): obj = type_(self) self.types[obj._type] = obj def reindex(self, index=None, alias=True, keep_old=False): # Generate an Index Name for Warehouse index = "".join([ index if index is not None else self._index, hashlib.md5(os.urandom(16)).hexdigest()[:8], ]) # Create this index self.es.indices.create(index, { "mappings": { doc_type._type: doc_type.get_mapping() for doc_type in self.types.values() }, }) # Index everything into the new index for doc_type in self.types.values(): doc_type.index_all(index=index) # Update the alias unless we've been told not to if alias: self.update_alias(self._index, index, keep_old=keep_old) def update_alias(self, alias, index, keep_old=False): # Get the old index from ElasticSearch try: old_index = self.es.indices.get_alias(self._index).keys()[0] except TransportError as exc: if not exc.status_code == 404: raise old_index = None # Remove the alias to the old index if it exists if old_index is not None: actions = [{"remove": {"index": old_index, "alias": alias}}] else: actions = [] # Add the alias to the new index actions += [{"add": {"index": index, "alias": alias}}] # Update To the New Index self.es.indices.update_aliases({"actions": actions}) # Delete the old index if it exists and unless we're keeping it if not keep_old and old_index is not None: self.es.indices.delete(old_index) class BaseMapping(object): <|fim_middle|> <|fim▁end|>
SEARCH_LIMIT = 25 def __init__(self, index): self.index = index def get_mapping(self): raise NotImplementedError def get_indexable(self): raise NotImplementedError def extract_id(self, item): raise NotImplementedError def extract_document(self, item): raise NotImplementedError def index_all(self, index=None): # Determine which index we are indexing into _index = index if index is not None else self.index._index # Bulk Index our documents bulk_index( self.index.es, [ { "_index": _index, "_type": self._type, "_id": self.extract_id(item), "_source": self.extract_document(item), } for item in self.get_indexable() ], ) def search(self, query): raise NotImplementedError
<|file_name|>indexes.py<|end_file_name|><|fim▁begin|># Copyright 2013 Donald Stufft # # 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. from __future__ import absolute_import, division, print_function from __future__ import unicode_literals import hashlib import os from elasticsearch import Elasticsearch, TransportError from elasticsearch.helpers import bulk_index from warehouse.utils import AttributeDict class Index(object): _index = "warehouse" def __init__(self, models, config): self.models = models self.config = config self.es = Elasticsearch( hosts=self.config.hosts, **self.config.get("client_options", {}) ) self.types = AttributeDict() def register(self, type_): obj = type_(self) self.types[obj._type] = obj def reindex(self, index=None, alias=True, keep_old=False): # Generate an Index Name for Warehouse index = "".join([ index if index is not None else self._index, hashlib.md5(os.urandom(16)).hexdigest()[:8], ]) # Create this index self.es.indices.create(index, { "mappings": { doc_type._type: doc_type.get_mapping() for doc_type in self.types.values() }, }) # Index everything into the new index for doc_type in self.types.values(): doc_type.index_all(index=index) # Update the alias unless we've been told not to if alias: self.update_alias(self._index, index, keep_old=keep_old) def update_alias(self, alias, index, keep_old=False): # Get the old index from ElasticSearch try: old_index = self.es.indices.get_alias(self._index).keys()[0] except TransportError as exc: if not exc.status_code == 404: raise old_index = None # Remove the alias to the old index if it exists if old_index is not None: actions = [{"remove": {"index": old_index, "alias": alias}}] else: actions = [] # Add the alias to the new index actions += [{"add": {"index": index, "alias": alias}}] # Update To the New Index self.es.indices.update_aliases({"actions": actions}) # Delete the old index if it exists and unless we're keeping it if not keep_old and old_index is not None: self.es.indices.delete(old_index) class BaseMapping(object): SEARCH_LIMIT = 25 def __init__(self, index): <|fim_middle|> def get_mapping(self): raise NotImplementedError def get_indexable(self): raise NotImplementedError def extract_id(self, item): raise NotImplementedError def extract_document(self, item): raise NotImplementedError def index_all(self, index=None): # Determine which index we are indexing into _index = index if index is not None else self.index._index # Bulk Index our documents bulk_index( self.index.es, [ { "_index": _index, "_type": self._type, "_id": self.extract_id(item), "_source": self.extract_document(item), } for item in self.get_indexable() ], ) def search(self, query): raise NotImplementedError <|fim▁end|>
self.index = index
<|file_name|>indexes.py<|end_file_name|><|fim▁begin|># Copyright 2013 Donald Stufft # # 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. from __future__ import absolute_import, division, print_function from __future__ import unicode_literals import hashlib import os from elasticsearch import Elasticsearch, TransportError from elasticsearch.helpers import bulk_index from warehouse.utils import AttributeDict class Index(object): _index = "warehouse" def __init__(self, models, config): self.models = models self.config = config self.es = Elasticsearch( hosts=self.config.hosts, **self.config.get("client_options", {}) ) self.types = AttributeDict() def register(self, type_): obj = type_(self) self.types[obj._type] = obj def reindex(self, index=None, alias=True, keep_old=False): # Generate an Index Name for Warehouse index = "".join([ index if index is not None else self._index, hashlib.md5(os.urandom(16)).hexdigest()[:8], ]) # Create this index self.es.indices.create(index, { "mappings": { doc_type._type: doc_type.get_mapping() for doc_type in self.types.values() }, }) # Index everything into the new index for doc_type in self.types.values(): doc_type.index_all(index=index) # Update the alias unless we've been told not to if alias: self.update_alias(self._index, index, keep_old=keep_old) def update_alias(self, alias, index, keep_old=False): # Get the old index from ElasticSearch try: old_index = self.es.indices.get_alias(self._index).keys()[0] except TransportError as exc: if not exc.status_code == 404: raise old_index = None # Remove the alias to the old index if it exists if old_index is not None: actions = [{"remove": {"index": old_index, "alias": alias}}] else: actions = [] # Add the alias to the new index actions += [{"add": {"index": index, "alias": alias}}] # Update To the New Index self.es.indices.update_aliases({"actions": actions}) # Delete the old index if it exists and unless we're keeping it if not keep_old and old_index is not None: self.es.indices.delete(old_index) class BaseMapping(object): SEARCH_LIMIT = 25 def __init__(self, index): self.index = index def get_mapping(self): <|fim_middle|> def get_indexable(self): raise NotImplementedError def extract_id(self, item): raise NotImplementedError def extract_document(self, item): raise NotImplementedError def index_all(self, index=None): # Determine which index we are indexing into _index = index if index is not None else self.index._index # Bulk Index our documents bulk_index( self.index.es, [ { "_index": _index, "_type": self._type, "_id": self.extract_id(item), "_source": self.extract_document(item), } for item in self.get_indexable() ], ) def search(self, query): raise NotImplementedError <|fim▁end|>
raise NotImplementedError
<|file_name|>indexes.py<|end_file_name|><|fim▁begin|># Copyright 2013 Donald Stufft # # 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. from __future__ import absolute_import, division, print_function from __future__ import unicode_literals import hashlib import os from elasticsearch import Elasticsearch, TransportError from elasticsearch.helpers import bulk_index from warehouse.utils import AttributeDict class Index(object): _index = "warehouse" def __init__(self, models, config): self.models = models self.config = config self.es = Elasticsearch( hosts=self.config.hosts, **self.config.get("client_options", {}) ) self.types = AttributeDict() def register(self, type_): obj = type_(self) self.types[obj._type] = obj def reindex(self, index=None, alias=True, keep_old=False): # Generate an Index Name for Warehouse index = "".join([ index if index is not None else self._index, hashlib.md5(os.urandom(16)).hexdigest()[:8], ]) # Create this index self.es.indices.create(index, { "mappings": { doc_type._type: doc_type.get_mapping() for doc_type in self.types.values() }, }) # Index everything into the new index for doc_type in self.types.values(): doc_type.index_all(index=index) # Update the alias unless we've been told not to if alias: self.update_alias(self._index, index, keep_old=keep_old) def update_alias(self, alias, index, keep_old=False): # Get the old index from ElasticSearch try: old_index = self.es.indices.get_alias(self._index).keys()[0] except TransportError as exc: if not exc.status_code == 404: raise old_index = None # Remove the alias to the old index if it exists if old_index is not None: actions = [{"remove": {"index": old_index, "alias": alias}}] else: actions = [] # Add the alias to the new index actions += [{"add": {"index": index, "alias": alias}}] # Update To the New Index self.es.indices.update_aliases({"actions": actions}) # Delete the old index if it exists and unless we're keeping it if not keep_old and old_index is not None: self.es.indices.delete(old_index) class BaseMapping(object): SEARCH_LIMIT = 25 def __init__(self, index): self.index = index def get_mapping(self): raise NotImplementedError def get_indexable(self): <|fim_middle|> def extract_id(self, item): raise NotImplementedError def extract_document(self, item): raise NotImplementedError def index_all(self, index=None): # Determine which index we are indexing into _index = index if index is not None else self.index._index # Bulk Index our documents bulk_index( self.index.es, [ { "_index": _index, "_type": self._type, "_id": self.extract_id(item), "_source": self.extract_document(item), } for item in self.get_indexable() ], ) def search(self, query): raise NotImplementedError <|fim▁end|>
raise NotImplementedError
<|file_name|>indexes.py<|end_file_name|><|fim▁begin|># Copyright 2013 Donald Stufft # # 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. from __future__ import absolute_import, division, print_function from __future__ import unicode_literals import hashlib import os from elasticsearch import Elasticsearch, TransportError from elasticsearch.helpers import bulk_index from warehouse.utils import AttributeDict class Index(object): _index = "warehouse" def __init__(self, models, config): self.models = models self.config = config self.es = Elasticsearch( hosts=self.config.hosts, **self.config.get("client_options", {}) ) self.types = AttributeDict() def register(self, type_): obj = type_(self) self.types[obj._type] = obj def reindex(self, index=None, alias=True, keep_old=False): # Generate an Index Name for Warehouse index = "".join([ index if index is not None else self._index, hashlib.md5(os.urandom(16)).hexdigest()[:8], ]) # Create this index self.es.indices.create(index, { "mappings": { doc_type._type: doc_type.get_mapping() for doc_type in self.types.values() }, }) # Index everything into the new index for doc_type in self.types.values(): doc_type.index_all(index=index) # Update the alias unless we've been told not to if alias: self.update_alias(self._index, index, keep_old=keep_old) def update_alias(self, alias, index, keep_old=False): # Get the old index from ElasticSearch try: old_index = self.es.indices.get_alias(self._index).keys()[0] except TransportError as exc: if not exc.status_code == 404: raise old_index = None # Remove the alias to the old index if it exists if old_index is not None: actions = [{"remove": {"index": old_index, "alias": alias}}] else: actions = [] # Add the alias to the new index actions += [{"add": {"index": index, "alias": alias}}] # Update To the New Index self.es.indices.update_aliases({"actions": actions}) # Delete the old index if it exists and unless we're keeping it if not keep_old and old_index is not None: self.es.indices.delete(old_index) class BaseMapping(object): SEARCH_LIMIT = 25 def __init__(self, index): self.index = index def get_mapping(self): raise NotImplementedError def get_indexable(self): raise NotImplementedError def extract_id(self, item): <|fim_middle|> def extract_document(self, item): raise NotImplementedError def index_all(self, index=None): # Determine which index we are indexing into _index = index if index is not None else self.index._index # Bulk Index our documents bulk_index( self.index.es, [ { "_index": _index, "_type": self._type, "_id": self.extract_id(item), "_source": self.extract_document(item), } for item in self.get_indexable() ], ) def search(self, query): raise NotImplementedError <|fim▁end|>
raise NotImplementedError
<|file_name|>indexes.py<|end_file_name|><|fim▁begin|># Copyright 2013 Donald Stufft # # 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. from __future__ import absolute_import, division, print_function from __future__ import unicode_literals import hashlib import os from elasticsearch import Elasticsearch, TransportError from elasticsearch.helpers import bulk_index from warehouse.utils import AttributeDict class Index(object): _index = "warehouse" def __init__(self, models, config): self.models = models self.config = config self.es = Elasticsearch( hosts=self.config.hosts, **self.config.get("client_options", {}) ) self.types = AttributeDict() def register(self, type_): obj = type_(self) self.types[obj._type] = obj def reindex(self, index=None, alias=True, keep_old=False): # Generate an Index Name for Warehouse index = "".join([ index if index is not None else self._index, hashlib.md5(os.urandom(16)).hexdigest()[:8], ]) # Create this index self.es.indices.create(index, { "mappings": { doc_type._type: doc_type.get_mapping() for doc_type in self.types.values() }, }) # Index everything into the new index for doc_type in self.types.values(): doc_type.index_all(index=index) # Update the alias unless we've been told not to if alias: self.update_alias(self._index, index, keep_old=keep_old) def update_alias(self, alias, index, keep_old=False): # Get the old index from ElasticSearch try: old_index = self.es.indices.get_alias(self._index).keys()[0] except TransportError as exc: if not exc.status_code == 404: raise old_index = None # Remove the alias to the old index if it exists if old_index is not None: actions = [{"remove": {"index": old_index, "alias": alias}}] else: actions = [] # Add the alias to the new index actions += [{"add": {"index": index, "alias": alias}}] # Update To the New Index self.es.indices.update_aliases({"actions": actions}) # Delete the old index if it exists and unless we're keeping it if not keep_old and old_index is not None: self.es.indices.delete(old_index) class BaseMapping(object): SEARCH_LIMIT = 25 def __init__(self, index): self.index = index def get_mapping(self): raise NotImplementedError def get_indexable(self): raise NotImplementedError def extract_id(self, item): raise NotImplementedError def extract_document(self, item): <|fim_middle|> def index_all(self, index=None): # Determine which index we are indexing into _index = index if index is not None else self.index._index # Bulk Index our documents bulk_index( self.index.es, [ { "_index": _index, "_type": self._type, "_id": self.extract_id(item), "_source": self.extract_document(item), } for item in self.get_indexable() ], ) def search(self, query): raise NotImplementedError <|fim▁end|>
raise NotImplementedError
<|file_name|>indexes.py<|end_file_name|><|fim▁begin|># Copyright 2013 Donald Stufft # # 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. from __future__ import absolute_import, division, print_function from __future__ import unicode_literals import hashlib import os from elasticsearch import Elasticsearch, TransportError from elasticsearch.helpers import bulk_index from warehouse.utils import AttributeDict class Index(object): _index = "warehouse" def __init__(self, models, config): self.models = models self.config = config self.es = Elasticsearch( hosts=self.config.hosts, **self.config.get("client_options", {}) ) self.types = AttributeDict() def register(self, type_): obj = type_(self) self.types[obj._type] = obj def reindex(self, index=None, alias=True, keep_old=False): # Generate an Index Name for Warehouse index = "".join([ index if index is not None else self._index, hashlib.md5(os.urandom(16)).hexdigest()[:8], ]) # Create this index self.es.indices.create(index, { "mappings": { doc_type._type: doc_type.get_mapping() for doc_type in self.types.values() }, }) # Index everything into the new index for doc_type in self.types.values(): doc_type.index_all(index=index) # Update the alias unless we've been told not to if alias: self.update_alias(self._index, index, keep_old=keep_old) def update_alias(self, alias, index, keep_old=False): # Get the old index from ElasticSearch try: old_index = self.es.indices.get_alias(self._index).keys()[0] except TransportError as exc: if not exc.status_code == 404: raise old_index = None # Remove the alias to the old index if it exists if old_index is not None: actions = [{"remove": {"index": old_index, "alias": alias}}] else: actions = [] # Add the alias to the new index actions += [{"add": {"index": index, "alias": alias}}] # Update To the New Index self.es.indices.update_aliases({"actions": actions}) # Delete the old index if it exists and unless we're keeping it if not keep_old and old_index is not None: self.es.indices.delete(old_index) class BaseMapping(object): SEARCH_LIMIT = 25 def __init__(self, index): self.index = index def get_mapping(self): raise NotImplementedError def get_indexable(self): raise NotImplementedError def extract_id(self, item): raise NotImplementedError def extract_document(self, item): raise NotImplementedError def index_all(self, index=None): # Determine which index we are indexing into <|fim_middle|> def search(self, query): raise NotImplementedError <|fim▁end|>
_index = index if index is not None else self.index._index # Bulk Index our documents bulk_index( self.index.es, [ { "_index": _index, "_type": self._type, "_id": self.extract_id(item), "_source": self.extract_document(item), } for item in self.get_indexable() ], )
<|file_name|>indexes.py<|end_file_name|><|fim▁begin|># Copyright 2013 Donald Stufft # # 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. from __future__ import absolute_import, division, print_function from __future__ import unicode_literals import hashlib import os from elasticsearch import Elasticsearch, TransportError from elasticsearch.helpers import bulk_index from warehouse.utils import AttributeDict class Index(object): _index = "warehouse" def __init__(self, models, config): self.models = models self.config = config self.es = Elasticsearch( hosts=self.config.hosts, **self.config.get("client_options", {}) ) self.types = AttributeDict() def register(self, type_): obj = type_(self) self.types[obj._type] = obj def reindex(self, index=None, alias=True, keep_old=False): # Generate an Index Name for Warehouse index = "".join([ index if index is not None else self._index, hashlib.md5(os.urandom(16)).hexdigest()[:8], ]) # Create this index self.es.indices.create(index, { "mappings": { doc_type._type: doc_type.get_mapping() for doc_type in self.types.values() }, }) # Index everything into the new index for doc_type in self.types.values(): doc_type.index_all(index=index) # Update the alias unless we've been told not to if alias: self.update_alias(self._index, index, keep_old=keep_old) def update_alias(self, alias, index, keep_old=False): # Get the old index from ElasticSearch try: old_index = self.es.indices.get_alias(self._index).keys()[0] except TransportError as exc: if not exc.status_code == 404: raise old_index = None # Remove the alias to the old index if it exists if old_index is not None: actions = [{"remove": {"index": old_index, "alias": alias}}] else: actions = [] # Add the alias to the new index actions += [{"add": {"index": index, "alias": alias}}] # Update To the New Index self.es.indices.update_aliases({"actions": actions}) # Delete the old index if it exists and unless we're keeping it if not keep_old and old_index is not None: self.es.indices.delete(old_index) class BaseMapping(object): SEARCH_LIMIT = 25 def __init__(self, index): self.index = index def get_mapping(self): raise NotImplementedError def get_indexable(self): raise NotImplementedError def extract_id(self, item): raise NotImplementedError def extract_document(self, item): raise NotImplementedError def index_all(self, index=None): # Determine which index we are indexing into _index = index if index is not None else self.index._index # Bulk Index our documents bulk_index( self.index.es, [ { "_index": _index, "_type": self._type, "_id": self.extract_id(item), "_source": self.extract_document(item), } for item in self.get_indexable() ], ) def search(self, query): <|fim_middle|> <|fim▁end|>
raise NotImplementedError
<|file_name|>indexes.py<|end_file_name|><|fim▁begin|># Copyright 2013 Donald Stufft # # 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. from __future__ import absolute_import, division, print_function from __future__ import unicode_literals import hashlib import os from elasticsearch import Elasticsearch, TransportError from elasticsearch.helpers import bulk_index from warehouse.utils import AttributeDict class Index(object): _index = "warehouse" def __init__(self, models, config): self.models = models self.config = config self.es = Elasticsearch( hosts=self.config.hosts, **self.config.get("client_options", {}) ) self.types = AttributeDict() def register(self, type_): obj = type_(self) self.types[obj._type] = obj def reindex(self, index=None, alias=True, keep_old=False): # Generate an Index Name for Warehouse index = "".join([ index if index is not None else self._index, hashlib.md5(os.urandom(16)).hexdigest()[:8], ]) # Create this index self.es.indices.create(index, { "mappings": { doc_type._type: doc_type.get_mapping() for doc_type in self.types.values() }, }) # Index everything into the new index for doc_type in self.types.values(): doc_type.index_all(index=index) # Update the alias unless we've been told not to if alias: <|fim_middle|> def update_alias(self, alias, index, keep_old=False): # Get the old index from ElasticSearch try: old_index = self.es.indices.get_alias(self._index).keys()[0] except TransportError as exc: if not exc.status_code == 404: raise old_index = None # Remove the alias to the old index if it exists if old_index is not None: actions = [{"remove": {"index": old_index, "alias": alias}}] else: actions = [] # Add the alias to the new index actions += [{"add": {"index": index, "alias": alias}}] # Update To the New Index self.es.indices.update_aliases({"actions": actions}) # Delete the old index if it exists and unless we're keeping it if not keep_old and old_index is not None: self.es.indices.delete(old_index) class BaseMapping(object): SEARCH_LIMIT = 25 def __init__(self, index): self.index = index def get_mapping(self): raise NotImplementedError def get_indexable(self): raise NotImplementedError def extract_id(self, item): raise NotImplementedError def extract_document(self, item): raise NotImplementedError def index_all(self, index=None): # Determine which index we are indexing into _index = index if index is not None else self.index._index # Bulk Index our documents bulk_index( self.index.es, [ { "_index": _index, "_type": self._type, "_id": self.extract_id(item), "_source": self.extract_document(item), } for item in self.get_indexable() ], ) def search(self, query): raise NotImplementedError <|fim▁end|>
self.update_alias(self._index, index, keep_old=keep_old)
<|file_name|>indexes.py<|end_file_name|><|fim▁begin|># Copyright 2013 Donald Stufft # # 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. from __future__ import absolute_import, division, print_function from __future__ import unicode_literals import hashlib import os from elasticsearch import Elasticsearch, TransportError from elasticsearch.helpers import bulk_index from warehouse.utils import AttributeDict class Index(object): _index = "warehouse" def __init__(self, models, config): self.models = models self.config = config self.es = Elasticsearch( hosts=self.config.hosts, **self.config.get("client_options", {}) ) self.types = AttributeDict() def register(self, type_): obj = type_(self) self.types[obj._type] = obj def reindex(self, index=None, alias=True, keep_old=False): # Generate an Index Name for Warehouse index = "".join([ index if index is not None else self._index, hashlib.md5(os.urandom(16)).hexdigest()[:8], ]) # Create this index self.es.indices.create(index, { "mappings": { doc_type._type: doc_type.get_mapping() for doc_type in self.types.values() }, }) # Index everything into the new index for doc_type in self.types.values(): doc_type.index_all(index=index) # Update the alias unless we've been told not to if alias: self.update_alias(self._index, index, keep_old=keep_old) def update_alias(self, alias, index, keep_old=False): # Get the old index from ElasticSearch try: old_index = self.es.indices.get_alias(self._index).keys()[0] except TransportError as exc: if not exc.status_code == 404: <|fim_middle|> old_index = None # Remove the alias to the old index if it exists if old_index is not None: actions = [{"remove": {"index": old_index, "alias": alias}}] else: actions = [] # Add the alias to the new index actions += [{"add": {"index": index, "alias": alias}}] # Update To the New Index self.es.indices.update_aliases({"actions": actions}) # Delete the old index if it exists and unless we're keeping it if not keep_old and old_index is not None: self.es.indices.delete(old_index) class BaseMapping(object): SEARCH_LIMIT = 25 def __init__(self, index): self.index = index def get_mapping(self): raise NotImplementedError def get_indexable(self): raise NotImplementedError def extract_id(self, item): raise NotImplementedError def extract_document(self, item): raise NotImplementedError def index_all(self, index=None): # Determine which index we are indexing into _index = index if index is not None else self.index._index # Bulk Index our documents bulk_index( self.index.es, [ { "_index": _index, "_type": self._type, "_id": self.extract_id(item), "_source": self.extract_document(item), } for item in self.get_indexable() ], ) def search(self, query): raise NotImplementedError <|fim▁end|>
raise
<|file_name|>indexes.py<|end_file_name|><|fim▁begin|># Copyright 2013 Donald Stufft # # 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. from __future__ import absolute_import, division, print_function from __future__ import unicode_literals import hashlib import os from elasticsearch import Elasticsearch, TransportError from elasticsearch.helpers import bulk_index from warehouse.utils import AttributeDict class Index(object): _index = "warehouse" def __init__(self, models, config): self.models = models self.config = config self.es = Elasticsearch( hosts=self.config.hosts, **self.config.get("client_options", {}) ) self.types = AttributeDict() def register(self, type_): obj = type_(self) self.types[obj._type] = obj def reindex(self, index=None, alias=True, keep_old=False): # Generate an Index Name for Warehouse index = "".join([ index if index is not None else self._index, hashlib.md5(os.urandom(16)).hexdigest()[:8], ]) # Create this index self.es.indices.create(index, { "mappings": { doc_type._type: doc_type.get_mapping() for doc_type in self.types.values() }, }) # Index everything into the new index for doc_type in self.types.values(): doc_type.index_all(index=index) # Update the alias unless we've been told not to if alias: self.update_alias(self._index, index, keep_old=keep_old) def update_alias(self, alias, index, keep_old=False): # Get the old index from ElasticSearch try: old_index = self.es.indices.get_alias(self._index).keys()[0] except TransportError as exc: if not exc.status_code == 404: raise old_index = None # Remove the alias to the old index if it exists if old_index is not None: <|fim_middle|> else: actions = [] # Add the alias to the new index actions += [{"add": {"index": index, "alias": alias}}] # Update To the New Index self.es.indices.update_aliases({"actions": actions}) # Delete the old index if it exists and unless we're keeping it if not keep_old and old_index is not None: self.es.indices.delete(old_index) class BaseMapping(object): SEARCH_LIMIT = 25 def __init__(self, index): self.index = index def get_mapping(self): raise NotImplementedError def get_indexable(self): raise NotImplementedError def extract_id(self, item): raise NotImplementedError def extract_document(self, item): raise NotImplementedError def index_all(self, index=None): # Determine which index we are indexing into _index = index if index is not None else self.index._index # Bulk Index our documents bulk_index( self.index.es, [ { "_index": _index, "_type": self._type, "_id": self.extract_id(item), "_source": self.extract_document(item), } for item in self.get_indexable() ], ) def search(self, query): raise NotImplementedError <|fim▁end|>
actions = [{"remove": {"index": old_index, "alias": alias}}]
<|file_name|>indexes.py<|end_file_name|><|fim▁begin|># Copyright 2013 Donald Stufft # # 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. from __future__ import absolute_import, division, print_function from __future__ import unicode_literals import hashlib import os from elasticsearch import Elasticsearch, TransportError from elasticsearch.helpers import bulk_index from warehouse.utils import AttributeDict class Index(object): _index = "warehouse" def __init__(self, models, config): self.models = models self.config = config self.es = Elasticsearch( hosts=self.config.hosts, **self.config.get("client_options", {}) ) self.types = AttributeDict() def register(self, type_): obj = type_(self) self.types[obj._type] = obj def reindex(self, index=None, alias=True, keep_old=False): # Generate an Index Name for Warehouse index = "".join([ index if index is not None else self._index, hashlib.md5(os.urandom(16)).hexdigest()[:8], ]) # Create this index self.es.indices.create(index, { "mappings": { doc_type._type: doc_type.get_mapping() for doc_type in self.types.values() }, }) # Index everything into the new index for doc_type in self.types.values(): doc_type.index_all(index=index) # Update the alias unless we've been told not to if alias: self.update_alias(self._index, index, keep_old=keep_old) def update_alias(self, alias, index, keep_old=False): # Get the old index from ElasticSearch try: old_index = self.es.indices.get_alias(self._index).keys()[0] except TransportError as exc: if not exc.status_code == 404: raise old_index = None # Remove the alias to the old index if it exists if old_index is not None: actions = [{"remove": {"index": old_index, "alias": alias}}] else: <|fim_middle|> # Add the alias to the new index actions += [{"add": {"index": index, "alias": alias}}] # Update To the New Index self.es.indices.update_aliases({"actions": actions}) # Delete the old index if it exists and unless we're keeping it if not keep_old and old_index is not None: self.es.indices.delete(old_index) class BaseMapping(object): SEARCH_LIMIT = 25 def __init__(self, index): self.index = index def get_mapping(self): raise NotImplementedError def get_indexable(self): raise NotImplementedError def extract_id(self, item): raise NotImplementedError def extract_document(self, item): raise NotImplementedError def index_all(self, index=None): # Determine which index we are indexing into _index = index if index is not None else self.index._index # Bulk Index our documents bulk_index( self.index.es, [ { "_index": _index, "_type": self._type, "_id": self.extract_id(item), "_source": self.extract_document(item), } for item in self.get_indexable() ], ) def search(self, query): raise NotImplementedError <|fim▁end|>
actions = []
<|file_name|>indexes.py<|end_file_name|><|fim▁begin|># Copyright 2013 Donald Stufft # # 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. from __future__ import absolute_import, division, print_function from __future__ import unicode_literals import hashlib import os from elasticsearch import Elasticsearch, TransportError from elasticsearch.helpers import bulk_index from warehouse.utils import AttributeDict class Index(object): _index = "warehouse" def __init__(self, models, config): self.models = models self.config = config self.es = Elasticsearch( hosts=self.config.hosts, **self.config.get("client_options", {}) ) self.types = AttributeDict() def register(self, type_): obj = type_(self) self.types[obj._type] = obj def reindex(self, index=None, alias=True, keep_old=False): # Generate an Index Name for Warehouse index = "".join([ index if index is not None else self._index, hashlib.md5(os.urandom(16)).hexdigest()[:8], ]) # Create this index self.es.indices.create(index, { "mappings": { doc_type._type: doc_type.get_mapping() for doc_type in self.types.values() }, }) # Index everything into the new index for doc_type in self.types.values(): doc_type.index_all(index=index) # Update the alias unless we've been told not to if alias: self.update_alias(self._index, index, keep_old=keep_old) def update_alias(self, alias, index, keep_old=False): # Get the old index from ElasticSearch try: old_index = self.es.indices.get_alias(self._index).keys()[0] except TransportError as exc: if not exc.status_code == 404: raise old_index = None # Remove the alias to the old index if it exists if old_index is not None: actions = [{"remove": {"index": old_index, "alias": alias}}] else: actions = [] # Add the alias to the new index actions += [{"add": {"index": index, "alias": alias}}] # Update To the New Index self.es.indices.update_aliases({"actions": actions}) # Delete the old index if it exists and unless we're keeping it if not keep_old and old_index is not None: <|fim_middle|> class BaseMapping(object): SEARCH_LIMIT = 25 def __init__(self, index): self.index = index def get_mapping(self): raise NotImplementedError def get_indexable(self): raise NotImplementedError def extract_id(self, item): raise NotImplementedError def extract_document(self, item): raise NotImplementedError def index_all(self, index=None): # Determine which index we are indexing into _index = index if index is not None else self.index._index # Bulk Index our documents bulk_index( self.index.es, [ { "_index": _index, "_type": self._type, "_id": self.extract_id(item), "_source": self.extract_document(item), } for item in self.get_indexable() ], ) def search(self, query): raise NotImplementedError <|fim▁end|>
self.es.indices.delete(old_index)
<|file_name|>indexes.py<|end_file_name|><|fim▁begin|># Copyright 2013 Donald Stufft # # 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. from __future__ import absolute_import, division, print_function from __future__ import unicode_literals import hashlib import os from elasticsearch import Elasticsearch, TransportError from elasticsearch.helpers import bulk_index from warehouse.utils import AttributeDict class Index(object): _index = "warehouse" def <|fim_middle|>(self, models, config): self.models = models self.config = config self.es = Elasticsearch( hosts=self.config.hosts, **self.config.get("client_options", {}) ) self.types = AttributeDict() def register(self, type_): obj = type_(self) self.types[obj._type] = obj def reindex(self, index=None, alias=True, keep_old=False): # Generate an Index Name for Warehouse index = "".join([ index if index is not None else self._index, hashlib.md5(os.urandom(16)).hexdigest()[:8], ]) # Create this index self.es.indices.create(index, { "mappings": { doc_type._type: doc_type.get_mapping() for doc_type in self.types.values() }, }) # Index everything into the new index for doc_type in self.types.values(): doc_type.index_all(index=index) # Update the alias unless we've been told not to if alias: self.update_alias(self._index, index, keep_old=keep_old) def update_alias(self, alias, index, keep_old=False): # Get the old index from ElasticSearch try: old_index = self.es.indices.get_alias(self._index).keys()[0] except TransportError as exc: if not exc.status_code == 404: raise old_index = None # Remove the alias to the old index if it exists if old_index is not None: actions = [{"remove": {"index": old_index, "alias": alias}}] else: actions = [] # Add the alias to the new index actions += [{"add": {"index": index, "alias": alias}}] # Update To the New Index self.es.indices.update_aliases({"actions": actions}) # Delete the old index if it exists and unless we're keeping it if not keep_old and old_index is not None: self.es.indices.delete(old_index) class BaseMapping(object): SEARCH_LIMIT = 25 def __init__(self, index): self.index = index def get_mapping(self): raise NotImplementedError def get_indexable(self): raise NotImplementedError def extract_id(self, item): raise NotImplementedError def extract_document(self, item): raise NotImplementedError def index_all(self, index=None): # Determine which index we are indexing into _index = index if index is not None else self.index._index # Bulk Index our documents bulk_index( self.index.es, [ { "_index": _index, "_type": self._type, "_id": self.extract_id(item), "_source": self.extract_document(item), } for item in self.get_indexable() ], ) def search(self, query): raise NotImplementedError <|fim▁end|>
__init__
<|file_name|>indexes.py<|end_file_name|><|fim▁begin|># Copyright 2013 Donald Stufft # # 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. from __future__ import absolute_import, division, print_function from __future__ import unicode_literals import hashlib import os from elasticsearch import Elasticsearch, TransportError from elasticsearch.helpers import bulk_index from warehouse.utils import AttributeDict class Index(object): _index = "warehouse" def __init__(self, models, config): self.models = models self.config = config self.es = Elasticsearch( hosts=self.config.hosts, **self.config.get("client_options", {}) ) self.types = AttributeDict() def <|fim_middle|>(self, type_): obj = type_(self) self.types[obj._type] = obj def reindex(self, index=None, alias=True, keep_old=False): # Generate an Index Name for Warehouse index = "".join([ index if index is not None else self._index, hashlib.md5(os.urandom(16)).hexdigest()[:8], ]) # Create this index self.es.indices.create(index, { "mappings": { doc_type._type: doc_type.get_mapping() for doc_type in self.types.values() }, }) # Index everything into the new index for doc_type in self.types.values(): doc_type.index_all(index=index) # Update the alias unless we've been told not to if alias: self.update_alias(self._index, index, keep_old=keep_old) def update_alias(self, alias, index, keep_old=False): # Get the old index from ElasticSearch try: old_index = self.es.indices.get_alias(self._index).keys()[0] except TransportError as exc: if not exc.status_code == 404: raise old_index = None # Remove the alias to the old index if it exists if old_index is not None: actions = [{"remove": {"index": old_index, "alias": alias}}] else: actions = [] # Add the alias to the new index actions += [{"add": {"index": index, "alias": alias}}] # Update To the New Index self.es.indices.update_aliases({"actions": actions}) # Delete the old index if it exists and unless we're keeping it if not keep_old and old_index is not None: self.es.indices.delete(old_index) class BaseMapping(object): SEARCH_LIMIT = 25 def __init__(self, index): self.index = index def get_mapping(self): raise NotImplementedError def get_indexable(self): raise NotImplementedError def extract_id(self, item): raise NotImplementedError def extract_document(self, item): raise NotImplementedError def index_all(self, index=None): # Determine which index we are indexing into _index = index if index is not None else self.index._index # Bulk Index our documents bulk_index( self.index.es, [ { "_index": _index, "_type": self._type, "_id": self.extract_id(item), "_source": self.extract_document(item), } for item in self.get_indexable() ], ) def search(self, query): raise NotImplementedError <|fim▁end|>
register
<|file_name|>indexes.py<|end_file_name|><|fim▁begin|># Copyright 2013 Donald Stufft # # 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. from __future__ import absolute_import, division, print_function from __future__ import unicode_literals import hashlib import os from elasticsearch import Elasticsearch, TransportError from elasticsearch.helpers import bulk_index from warehouse.utils import AttributeDict class Index(object): _index = "warehouse" def __init__(self, models, config): self.models = models self.config = config self.es = Elasticsearch( hosts=self.config.hosts, **self.config.get("client_options", {}) ) self.types = AttributeDict() def register(self, type_): obj = type_(self) self.types[obj._type] = obj def <|fim_middle|>(self, index=None, alias=True, keep_old=False): # Generate an Index Name for Warehouse index = "".join([ index if index is not None else self._index, hashlib.md5(os.urandom(16)).hexdigest()[:8], ]) # Create this index self.es.indices.create(index, { "mappings": { doc_type._type: doc_type.get_mapping() for doc_type in self.types.values() }, }) # Index everything into the new index for doc_type in self.types.values(): doc_type.index_all(index=index) # Update the alias unless we've been told not to if alias: self.update_alias(self._index, index, keep_old=keep_old) def update_alias(self, alias, index, keep_old=False): # Get the old index from ElasticSearch try: old_index = self.es.indices.get_alias(self._index).keys()[0] except TransportError as exc: if not exc.status_code == 404: raise old_index = None # Remove the alias to the old index if it exists if old_index is not None: actions = [{"remove": {"index": old_index, "alias": alias}}] else: actions = [] # Add the alias to the new index actions += [{"add": {"index": index, "alias": alias}}] # Update To the New Index self.es.indices.update_aliases({"actions": actions}) # Delete the old index if it exists and unless we're keeping it if not keep_old and old_index is not None: self.es.indices.delete(old_index) class BaseMapping(object): SEARCH_LIMIT = 25 def __init__(self, index): self.index = index def get_mapping(self): raise NotImplementedError def get_indexable(self): raise NotImplementedError def extract_id(self, item): raise NotImplementedError def extract_document(self, item): raise NotImplementedError def index_all(self, index=None): # Determine which index we are indexing into _index = index if index is not None else self.index._index # Bulk Index our documents bulk_index( self.index.es, [ { "_index": _index, "_type": self._type, "_id": self.extract_id(item), "_source": self.extract_document(item), } for item in self.get_indexable() ], ) def search(self, query): raise NotImplementedError <|fim▁end|>
reindex
<|file_name|>indexes.py<|end_file_name|><|fim▁begin|># Copyright 2013 Donald Stufft # # 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. from __future__ import absolute_import, division, print_function from __future__ import unicode_literals import hashlib import os from elasticsearch import Elasticsearch, TransportError from elasticsearch.helpers import bulk_index from warehouse.utils import AttributeDict class Index(object): _index = "warehouse" def __init__(self, models, config): self.models = models self.config = config self.es = Elasticsearch( hosts=self.config.hosts, **self.config.get("client_options", {}) ) self.types = AttributeDict() def register(self, type_): obj = type_(self) self.types[obj._type] = obj def reindex(self, index=None, alias=True, keep_old=False): # Generate an Index Name for Warehouse index = "".join([ index if index is not None else self._index, hashlib.md5(os.urandom(16)).hexdigest()[:8], ]) # Create this index self.es.indices.create(index, { "mappings": { doc_type._type: doc_type.get_mapping() for doc_type in self.types.values() }, }) # Index everything into the new index for doc_type in self.types.values(): doc_type.index_all(index=index) # Update the alias unless we've been told not to if alias: self.update_alias(self._index, index, keep_old=keep_old) def <|fim_middle|>(self, alias, index, keep_old=False): # Get the old index from ElasticSearch try: old_index = self.es.indices.get_alias(self._index).keys()[0] except TransportError as exc: if not exc.status_code == 404: raise old_index = None # Remove the alias to the old index if it exists if old_index is not None: actions = [{"remove": {"index": old_index, "alias": alias}}] else: actions = [] # Add the alias to the new index actions += [{"add": {"index": index, "alias": alias}}] # Update To the New Index self.es.indices.update_aliases({"actions": actions}) # Delete the old index if it exists and unless we're keeping it if not keep_old and old_index is not None: self.es.indices.delete(old_index) class BaseMapping(object): SEARCH_LIMIT = 25 def __init__(self, index): self.index = index def get_mapping(self): raise NotImplementedError def get_indexable(self): raise NotImplementedError def extract_id(self, item): raise NotImplementedError def extract_document(self, item): raise NotImplementedError def index_all(self, index=None): # Determine which index we are indexing into _index = index if index is not None else self.index._index # Bulk Index our documents bulk_index( self.index.es, [ { "_index": _index, "_type": self._type, "_id": self.extract_id(item), "_source": self.extract_document(item), } for item in self.get_indexable() ], ) def search(self, query): raise NotImplementedError <|fim▁end|>
update_alias
<|file_name|>indexes.py<|end_file_name|><|fim▁begin|># Copyright 2013 Donald Stufft # # 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. from __future__ import absolute_import, division, print_function from __future__ import unicode_literals import hashlib import os from elasticsearch import Elasticsearch, TransportError from elasticsearch.helpers import bulk_index from warehouse.utils import AttributeDict class Index(object): _index = "warehouse" def __init__(self, models, config): self.models = models self.config = config self.es = Elasticsearch( hosts=self.config.hosts, **self.config.get("client_options", {}) ) self.types = AttributeDict() def register(self, type_): obj = type_(self) self.types[obj._type] = obj def reindex(self, index=None, alias=True, keep_old=False): # Generate an Index Name for Warehouse index = "".join([ index if index is not None else self._index, hashlib.md5(os.urandom(16)).hexdigest()[:8], ]) # Create this index self.es.indices.create(index, { "mappings": { doc_type._type: doc_type.get_mapping() for doc_type in self.types.values() }, }) # Index everything into the new index for doc_type in self.types.values(): doc_type.index_all(index=index) # Update the alias unless we've been told not to if alias: self.update_alias(self._index, index, keep_old=keep_old) def update_alias(self, alias, index, keep_old=False): # Get the old index from ElasticSearch try: old_index = self.es.indices.get_alias(self._index).keys()[0] except TransportError as exc: if not exc.status_code == 404: raise old_index = None # Remove the alias to the old index if it exists if old_index is not None: actions = [{"remove": {"index": old_index, "alias": alias}}] else: actions = [] # Add the alias to the new index actions += [{"add": {"index": index, "alias": alias}}] # Update To the New Index self.es.indices.update_aliases({"actions": actions}) # Delete the old index if it exists and unless we're keeping it if not keep_old and old_index is not None: self.es.indices.delete(old_index) class BaseMapping(object): SEARCH_LIMIT = 25 def <|fim_middle|>(self, index): self.index = index def get_mapping(self): raise NotImplementedError def get_indexable(self): raise NotImplementedError def extract_id(self, item): raise NotImplementedError def extract_document(self, item): raise NotImplementedError def index_all(self, index=None): # Determine which index we are indexing into _index = index if index is not None else self.index._index # Bulk Index our documents bulk_index( self.index.es, [ { "_index": _index, "_type": self._type, "_id": self.extract_id(item), "_source": self.extract_document(item), } for item in self.get_indexable() ], ) def search(self, query): raise NotImplementedError <|fim▁end|>
__init__
<|file_name|>indexes.py<|end_file_name|><|fim▁begin|># Copyright 2013 Donald Stufft # # 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. from __future__ import absolute_import, division, print_function from __future__ import unicode_literals import hashlib import os from elasticsearch import Elasticsearch, TransportError from elasticsearch.helpers import bulk_index from warehouse.utils import AttributeDict class Index(object): _index = "warehouse" def __init__(self, models, config): self.models = models self.config = config self.es = Elasticsearch( hosts=self.config.hosts, **self.config.get("client_options", {}) ) self.types = AttributeDict() def register(self, type_): obj = type_(self) self.types[obj._type] = obj def reindex(self, index=None, alias=True, keep_old=False): # Generate an Index Name for Warehouse index = "".join([ index if index is not None else self._index, hashlib.md5(os.urandom(16)).hexdigest()[:8], ]) # Create this index self.es.indices.create(index, { "mappings": { doc_type._type: doc_type.get_mapping() for doc_type in self.types.values() }, }) # Index everything into the new index for doc_type in self.types.values(): doc_type.index_all(index=index) # Update the alias unless we've been told not to if alias: self.update_alias(self._index, index, keep_old=keep_old) def update_alias(self, alias, index, keep_old=False): # Get the old index from ElasticSearch try: old_index = self.es.indices.get_alias(self._index).keys()[0] except TransportError as exc: if not exc.status_code == 404: raise old_index = None # Remove the alias to the old index if it exists if old_index is not None: actions = [{"remove": {"index": old_index, "alias": alias}}] else: actions = [] # Add the alias to the new index actions += [{"add": {"index": index, "alias": alias}}] # Update To the New Index self.es.indices.update_aliases({"actions": actions}) # Delete the old index if it exists and unless we're keeping it if not keep_old and old_index is not None: self.es.indices.delete(old_index) class BaseMapping(object): SEARCH_LIMIT = 25 def __init__(self, index): self.index = index def <|fim_middle|>(self): raise NotImplementedError def get_indexable(self): raise NotImplementedError def extract_id(self, item): raise NotImplementedError def extract_document(self, item): raise NotImplementedError def index_all(self, index=None): # Determine which index we are indexing into _index = index if index is not None else self.index._index # Bulk Index our documents bulk_index( self.index.es, [ { "_index": _index, "_type": self._type, "_id": self.extract_id(item), "_source": self.extract_document(item), } for item in self.get_indexable() ], ) def search(self, query): raise NotImplementedError <|fim▁end|>
get_mapping
<|file_name|>indexes.py<|end_file_name|><|fim▁begin|># Copyright 2013 Donald Stufft # # 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. from __future__ import absolute_import, division, print_function from __future__ import unicode_literals import hashlib import os from elasticsearch import Elasticsearch, TransportError from elasticsearch.helpers import bulk_index from warehouse.utils import AttributeDict class Index(object): _index = "warehouse" def __init__(self, models, config): self.models = models self.config = config self.es = Elasticsearch( hosts=self.config.hosts, **self.config.get("client_options", {}) ) self.types = AttributeDict() def register(self, type_): obj = type_(self) self.types[obj._type] = obj def reindex(self, index=None, alias=True, keep_old=False): # Generate an Index Name for Warehouse index = "".join([ index if index is not None else self._index, hashlib.md5(os.urandom(16)).hexdigest()[:8], ]) # Create this index self.es.indices.create(index, { "mappings": { doc_type._type: doc_type.get_mapping() for doc_type in self.types.values() }, }) # Index everything into the new index for doc_type in self.types.values(): doc_type.index_all(index=index) # Update the alias unless we've been told not to if alias: self.update_alias(self._index, index, keep_old=keep_old) def update_alias(self, alias, index, keep_old=False): # Get the old index from ElasticSearch try: old_index = self.es.indices.get_alias(self._index).keys()[0] except TransportError as exc: if not exc.status_code == 404: raise old_index = None # Remove the alias to the old index if it exists if old_index is not None: actions = [{"remove": {"index": old_index, "alias": alias}}] else: actions = [] # Add the alias to the new index actions += [{"add": {"index": index, "alias": alias}}] # Update To the New Index self.es.indices.update_aliases({"actions": actions}) # Delete the old index if it exists and unless we're keeping it if not keep_old and old_index is not None: self.es.indices.delete(old_index) class BaseMapping(object): SEARCH_LIMIT = 25 def __init__(self, index): self.index = index def get_mapping(self): raise NotImplementedError def <|fim_middle|>(self): raise NotImplementedError def extract_id(self, item): raise NotImplementedError def extract_document(self, item): raise NotImplementedError def index_all(self, index=None): # Determine which index we are indexing into _index = index if index is not None else self.index._index # Bulk Index our documents bulk_index( self.index.es, [ { "_index": _index, "_type": self._type, "_id": self.extract_id(item), "_source": self.extract_document(item), } for item in self.get_indexable() ], ) def search(self, query): raise NotImplementedError <|fim▁end|>
get_indexable
<|file_name|>indexes.py<|end_file_name|><|fim▁begin|># Copyright 2013 Donald Stufft # # 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. from __future__ import absolute_import, division, print_function from __future__ import unicode_literals import hashlib import os from elasticsearch import Elasticsearch, TransportError from elasticsearch.helpers import bulk_index from warehouse.utils import AttributeDict class Index(object): _index = "warehouse" def __init__(self, models, config): self.models = models self.config = config self.es = Elasticsearch( hosts=self.config.hosts, **self.config.get("client_options", {}) ) self.types = AttributeDict() def register(self, type_): obj = type_(self) self.types[obj._type] = obj def reindex(self, index=None, alias=True, keep_old=False): # Generate an Index Name for Warehouse index = "".join([ index if index is not None else self._index, hashlib.md5(os.urandom(16)).hexdigest()[:8], ]) # Create this index self.es.indices.create(index, { "mappings": { doc_type._type: doc_type.get_mapping() for doc_type in self.types.values() }, }) # Index everything into the new index for doc_type in self.types.values(): doc_type.index_all(index=index) # Update the alias unless we've been told not to if alias: self.update_alias(self._index, index, keep_old=keep_old) def update_alias(self, alias, index, keep_old=False): # Get the old index from ElasticSearch try: old_index = self.es.indices.get_alias(self._index).keys()[0] except TransportError as exc: if not exc.status_code == 404: raise old_index = None # Remove the alias to the old index if it exists if old_index is not None: actions = [{"remove": {"index": old_index, "alias": alias}}] else: actions = [] # Add the alias to the new index actions += [{"add": {"index": index, "alias": alias}}] # Update To the New Index self.es.indices.update_aliases({"actions": actions}) # Delete the old index if it exists and unless we're keeping it if not keep_old and old_index is not None: self.es.indices.delete(old_index) class BaseMapping(object): SEARCH_LIMIT = 25 def __init__(self, index): self.index = index def get_mapping(self): raise NotImplementedError def get_indexable(self): raise NotImplementedError def <|fim_middle|>(self, item): raise NotImplementedError def extract_document(self, item): raise NotImplementedError def index_all(self, index=None): # Determine which index we are indexing into _index = index if index is not None else self.index._index # Bulk Index our documents bulk_index( self.index.es, [ { "_index": _index, "_type": self._type, "_id": self.extract_id(item), "_source": self.extract_document(item), } for item in self.get_indexable() ], ) def search(self, query): raise NotImplementedError <|fim▁end|>
extract_id
<|file_name|>indexes.py<|end_file_name|><|fim▁begin|># Copyright 2013 Donald Stufft # # 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. from __future__ import absolute_import, division, print_function from __future__ import unicode_literals import hashlib import os from elasticsearch import Elasticsearch, TransportError from elasticsearch.helpers import bulk_index from warehouse.utils import AttributeDict class Index(object): _index = "warehouse" def __init__(self, models, config): self.models = models self.config = config self.es = Elasticsearch( hosts=self.config.hosts, **self.config.get("client_options", {}) ) self.types = AttributeDict() def register(self, type_): obj = type_(self) self.types[obj._type] = obj def reindex(self, index=None, alias=True, keep_old=False): # Generate an Index Name for Warehouse index = "".join([ index if index is not None else self._index, hashlib.md5(os.urandom(16)).hexdigest()[:8], ]) # Create this index self.es.indices.create(index, { "mappings": { doc_type._type: doc_type.get_mapping() for doc_type in self.types.values() }, }) # Index everything into the new index for doc_type in self.types.values(): doc_type.index_all(index=index) # Update the alias unless we've been told not to if alias: self.update_alias(self._index, index, keep_old=keep_old) def update_alias(self, alias, index, keep_old=False): # Get the old index from ElasticSearch try: old_index = self.es.indices.get_alias(self._index).keys()[0] except TransportError as exc: if not exc.status_code == 404: raise old_index = None # Remove the alias to the old index if it exists if old_index is not None: actions = [{"remove": {"index": old_index, "alias": alias}}] else: actions = [] # Add the alias to the new index actions += [{"add": {"index": index, "alias": alias}}] # Update To the New Index self.es.indices.update_aliases({"actions": actions}) # Delete the old index if it exists and unless we're keeping it if not keep_old and old_index is not None: self.es.indices.delete(old_index) class BaseMapping(object): SEARCH_LIMIT = 25 def __init__(self, index): self.index = index def get_mapping(self): raise NotImplementedError def get_indexable(self): raise NotImplementedError def extract_id(self, item): raise NotImplementedError def <|fim_middle|>(self, item): raise NotImplementedError def index_all(self, index=None): # Determine which index we are indexing into _index = index if index is not None else self.index._index # Bulk Index our documents bulk_index( self.index.es, [ { "_index": _index, "_type": self._type, "_id": self.extract_id(item), "_source": self.extract_document(item), } for item in self.get_indexable() ], ) def search(self, query): raise NotImplementedError <|fim▁end|>
extract_document
<|file_name|>indexes.py<|end_file_name|><|fim▁begin|># Copyright 2013 Donald Stufft # # 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. from __future__ import absolute_import, division, print_function from __future__ import unicode_literals import hashlib import os from elasticsearch import Elasticsearch, TransportError from elasticsearch.helpers import bulk_index from warehouse.utils import AttributeDict class Index(object): _index = "warehouse" def __init__(self, models, config): self.models = models self.config = config self.es = Elasticsearch( hosts=self.config.hosts, **self.config.get("client_options", {}) ) self.types = AttributeDict() def register(self, type_): obj = type_(self) self.types[obj._type] = obj def reindex(self, index=None, alias=True, keep_old=False): # Generate an Index Name for Warehouse index = "".join([ index if index is not None else self._index, hashlib.md5(os.urandom(16)).hexdigest()[:8], ]) # Create this index self.es.indices.create(index, { "mappings": { doc_type._type: doc_type.get_mapping() for doc_type in self.types.values() }, }) # Index everything into the new index for doc_type in self.types.values(): doc_type.index_all(index=index) # Update the alias unless we've been told not to if alias: self.update_alias(self._index, index, keep_old=keep_old) def update_alias(self, alias, index, keep_old=False): # Get the old index from ElasticSearch try: old_index = self.es.indices.get_alias(self._index).keys()[0] except TransportError as exc: if not exc.status_code == 404: raise old_index = None # Remove the alias to the old index if it exists if old_index is not None: actions = [{"remove": {"index": old_index, "alias": alias}}] else: actions = [] # Add the alias to the new index actions += [{"add": {"index": index, "alias": alias}}] # Update To the New Index self.es.indices.update_aliases({"actions": actions}) # Delete the old index if it exists and unless we're keeping it if not keep_old and old_index is not None: self.es.indices.delete(old_index) class BaseMapping(object): SEARCH_LIMIT = 25 def __init__(self, index): self.index = index def get_mapping(self): raise NotImplementedError def get_indexable(self): raise NotImplementedError def extract_id(self, item): raise NotImplementedError def extract_document(self, item): raise NotImplementedError def <|fim_middle|>(self, index=None): # Determine which index we are indexing into _index = index if index is not None else self.index._index # Bulk Index our documents bulk_index( self.index.es, [ { "_index": _index, "_type": self._type, "_id": self.extract_id(item), "_source": self.extract_document(item), } for item in self.get_indexable() ], ) def search(self, query): raise NotImplementedError <|fim▁end|>
index_all
<|file_name|>indexes.py<|end_file_name|><|fim▁begin|># Copyright 2013 Donald Stufft # # 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. from __future__ import absolute_import, division, print_function from __future__ import unicode_literals import hashlib import os from elasticsearch import Elasticsearch, TransportError from elasticsearch.helpers import bulk_index from warehouse.utils import AttributeDict class Index(object): _index = "warehouse" def __init__(self, models, config): self.models = models self.config = config self.es = Elasticsearch( hosts=self.config.hosts, **self.config.get("client_options", {}) ) self.types = AttributeDict() def register(self, type_): obj = type_(self) self.types[obj._type] = obj def reindex(self, index=None, alias=True, keep_old=False): # Generate an Index Name for Warehouse index = "".join([ index if index is not None else self._index, hashlib.md5(os.urandom(16)).hexdigest()[:8], ]) # Create this index self.es.indices.create(index, { "mappings": { doc_type._type: doc_type.get_mapping() for doc_type in self.types.values() }, }) # Index everything into the new index for doc_type in self.types.values(): doc_type.index_all(index=index) # Update the alias unless we've been told not to if alias: self.update_alias(self._index, index, keep_old=keep_old) def update_alias(self, alias, index, keep_old=False): # Get the old index from ElasticSearch try: old_index = self.es.indices.get_alias(self._index).keys()[0] except TransportError as exc: if not exc.status_code == 404: raise old_index = None # Remove the alias to the old index if it exists if old_index is not None: actions = [{"remove": {"index": old_index, "alias": alias}}] else: actions = [] # Add the alias to the new index actions += [{"add": {"index": index, "alias": alias}}] # Update To the New Index self.es.indices.update_aliases({"actions": actions}) # Delete the old index if it exists and unless we're keeping it if not keep_old and old_index is not None: self.es.indices.delete(old_index) class BaseMapping(object): SEARCH_LIMIT = 25 def __init__(self, index): self.index = index def get_mapping(self): raise NotImplementedError def get_indexable(self): raise NotImplementedError def extract_id(self, item): raise NotImplementedError def extract_document(self, item): raise NotImplementedError def index_all(self, index=None): # Determine which index we are indexing into _index = index if index is not None else self.index._index # Bulk Index our documents bulk_index( self.index.es, [ { "_index": _index, "_type": self._type, "_id": self.extract_id(item), "_source": self.extract_document(item), } for item in self.get_indexable() ], ) def <|fim_middle|>(self, query): raise NotImplementedError <|fim▁end|>
search
<|file_name|>Extension.py<|end_file_name|><|fim▁begin|>class Extension(object): """ Base class for creating extensions. Args: kwargs[dict]: All key, value pairings are stored as "configuration" options, see getConfigs. """ def __init__(self, **kwargs): #: Configure options self._configs = kwargs self._configs.setdefault('headings', ['section', 'subsection', 'subsubsection', 'textbf', 'underline', 'emph']) def getConfigs(self): """ Return the dictionary of configure options. """ return self._configs def extend(self, translator): """ Elements should be added to the storage of the Translator instance within this function.<|fim▁hole|> """ pass<|fim▁end|>
Args: translator[Translator]: The object to be used for converting the html.
<|file_name|>Extension.py<|end_file_name|><|fim▁begin|>class Extension(object): <|fim_middle|> <|fim▁end|>
""" Base class for creating extensions. Args: kwargs[dict]: All key, value pairings are stored as "configuration" options, see getConfigs. """ def __init__(self, **kwargs): #: Configure options self._configs = kwargs self._configs.setdefault('headings', ['section', 'subsection', 'subsubsection', 'textbf', 'underline', 'emph']) def getConfigs(self): """ Return the dictionary of configure options. """ return self._configs def extend(self, translator): """ Elements should be added to the storage of the Translator instance within this function. Args: translator[Translator]: The object to be used for converting the html. """ pass
<|file_name|>Extension.py<|end_file_name|><|fim▁begin|>class Extension(object): """ Base class for creating extensions. Args: kwargs[dict]: All key, value pairings are stored as "configuration" options, see getConfigs. """ def __init__(self, **kwargs): #: Configure options <|fim_middle|> def getConfigs(self): """ Return the dictionary of configure options. """ return self._configs def extend(self, translator): """ Elements should be added to the storage of the Translator instance within this function. Args: translator[Translator]: The object to be used for converting the html. """ pass <|fim▁end|>
self._configs = kwargs self._configs.setdefault('headings', ['section', 'subsection', 'subsubsection', 'textbf', 'underline', 'emph'])
<|file_name|>Extension.py<|end_file_name|><|fim▁begin|>class Extension(object): """ Base class for creating extensions. Args: kwargs[dict]: All key, value pairings are stored as "configuration" options, see getConfigs. """ def __init__(self, **kwargs): #: Configure options self._configs = kwargs self._configs.setdefault('headings', ['section', 'subsection', 'subsubsection', 'textbf', 'underline', 'emph']) def getConfigs(self): <|fim_middle|> def extend(self, translator): """ Elements should be added to the storage of the Translator instance within this function. Args: translator[Translator]: The object to be used for converting the html. """ pass <|fim▁end|>
""" Return the dictionary of configure options. """ return self._configs
<|file_name|>Extension.py<|end_file_name|><|fim▁begin|>class Extension(object): """ Base class for creating extensions. Args: kwargs[dict]: All key, value pairings are stored as "configuration" options, see getConfigs. """ def __init__(self, **kwargs): #: Configure options self._configs = kwargs self._configs.setdefault('headings', ['section', 'subsection', 'subsubsection', 'textbf', 'underline', 'emph']) def getConfigs(self): """ Return the dictionary of configure options. """ return self._configs def extend(self, translator): <|fim_middle|> <|fim▁end|>
""" Elements should be added to the storage of the Translator instance within this function. Args: translator[Translator]: The object to be used for converting the html. """ pass
<|file_name|>Extension.py<|end_file_name|><|fim▁begin|>class Extension(object): """ Base class for creating extensions. Args: kwargs[dict]: All key, value pairings are stored as "configuration" options, see getConfigs. """ def <|fim_middle|>(self, **kwargs): #: Configure options self._configs = kwargs self._configs.setdefault('headings', ['section', 'subsection', 'subsubsection', 'textbf', 'underline', 'emph']) def getConfigs(self): """ Return the dictionary of configure options. """ return self._configs def extend(self, translator): """ Elements should be added to the storage of the Translator instance within this function. Args: translator[Translator]: The object to be used for converting the html. """ pass <|fim▁end|>
__init__
<|file_name|>Extension.py<|end_file_name|><|fim▁begin|>class Extension(object): """ Base class for creating extensions. Args: kwargs[dict]: All key, value pairings are stored as "configuration" options, see getConfigs. """ def __init__(self, **kwargs): #: Configure options self._configs = kwargs self._configs.setdefault('headings', ['section', 'subsection', 'subsubsection', 'textbf', 'underline', 'emph']) def <|fim_middle|>(self): """ Return the dictionary of configure options. """ return self._configs def extend(self, translator): """ Elements should be added to the storage of the Translator instance within this function. Args: translator[Translator]: The object to be used for converting the html. """ pass <|fim▁end|>
getConfigs
<|file_name|>Extension.py<|end_file_name|><|fim▁begin|>class Extension(object): """ Base class for creating extensions. Args: kwargs[dict]: All key, value pairings are stored as "configuration" options, see getConfigs. """ def __init__(self, **kwargs): #: Configure options self._configs = kwargs self._configs.setdefault('headings', ['section', 'subsection', 'subsubsection', 'textbf', 'underline', 'emph']) def getConfigs(self): """ Return the dictionary of configure options. """ return self._configs def <|fim_middle|>(self, translator): """ Elements should be added to the storage of the Translator instance within this function. Args: translator[Translator]: The object to be used for converting the html. """ pass <|fim▁end|>
extend
<|file_name|>templating.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python3 import argparse<|fim▁hole|>import netaddr import requests from flask import Flask, request from jinja2 import Environment, FileSystemLoader, TemplateNotFound endpoints = "read/networks read/oplog read/snmp read/switches-management public/distro-tree public/config public/dhcp public/dhcp-summary public/ping public/switches public/switch-state".split() objects = {} def getEndpoint(endpoint): r = requests.get("http://localhost:80/api/{}".format(endpoint)) if r.status_code != 200: raise Exception("Bad status code for endpoint {}: {}".format(endpoint, r.status_code)) return r.json() def updateData(): for a in endpoints: objects[a] = getEndpoint(a) env = Environment(loader=FileSystemLoader([]), trim_blocks=True) env.filters["netmask"] = lambda ip: netaddr.IPNetwork(ip).netmask env.filters["cidr"] = lambda ip: netaddr.IPNetwork(ip).prefixlen env.filters["networkId"] = lambda ip: netaddr.IPNetwork(ip).ip env.filters["getFirstDhcpIp"] = lambda ip: netaddr.IPNetwork(ip)[3] env.filters["getLastDhcpIp"] = lambda ip: netaddr.IPNetwork(ip)[-1] env.filters["agentDistro"] = lambda src: src.split(":")[0] env.filters["agentPort"] = lambda src: src.split(":")[1] env.filters["getFirstFapIP"] = lambda ip: netaddr.IPNetwork(ip)[netaddr.IPNetwork(ip).size / 2] app = Flask(__name__) @app.after_request def add_header(response): if response.status_code == 200: response.cache_control.max_age = 5 response.cache_control.s_maxage = 1 return response @app.route("/<path>", methods=["GET"]) def root_get(path): updateData() try: template = env.get_template(path) body = template.render(objects=objects, options=request.args) except TemplateNotFound: return 'Template "{}" not found\n'.format(path), 404 except Exception as err: return 'Templating of "{}" failed to render. Most likely due to an error in the template. Error transcript:\n\n{}\n----\n\n{}\n'.format(path, err, traceback.format_exc()), 400 return body, 200 @app.route("/<path>", methods=["POST"]) def root_post(path): updateData() try: content = request.stream.read(int(request.headers["Content-Length"])) template = env.from_string(content.decode("utf-8")) body = template.render(objects=objects, options=request.args) except Exception as err: return 'Templating of "{}" failed to render. Most likely due to an error in the template. Error transcript:\n\n{}\n----\n\n{}\n'.format(path, err, traceback.format_exc()), 400 return body, 200 parser = argparse.ArgumentParser(description="Process templates for gondul.", add_help=False) parser.add_argument("-t", "--templates", type=str, nargs="+", help="location of templates") parser.add_argument("-h", "--host", type=str, default="127.0.0.1", help="host address") parser.add_argument("-p", "--port", type=int, default=8080, help="host port") parser.add_argument("-d", "--debug", action="store_true", help="enable debug mode") args = parser.parse_args() env.loader.searchpath = args.templates if not sys.argv[1:]: parser.print_help() app.run(host=args.host, port=args.port, debug=args.debug)<|fim▁end|>
import traceback import sys
<|file_name|>templating.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python3 import argparse import traceback import sys import netaddr import requests from flask import Flask, request from jinja2 import Environment, FileSystemLoader, TemplateNotFound endpoints = "read/networks read/oplog read/snmp read/switches-management public/distro-tree public/config public/dhcp public/dhcp-summary public/ping public/switches public/switch-state".split() objects = {} def getEndpoint(endpoint): <|fim_middle|> def updateData(): for a in endpoints: objects[a] = getEndpoint(a) env = Environment(loader=FileSystemLoader([]), trim_blocks=True) env.filters["netmask"] = lambda ip: netaddr.IPNetwork(ip).netmask env.filters["cidr"] = lambda ip: netaddr.IPNetwork(ip).prefixlen env.filters["networkId"] = lambda ip: netaddr.IPNetwork(ip).ip env.filters["getFirstDhcpIp"] = lambda ip: netaddr.IPNetwork(ip)[3] env.filters["getLastDhcpIp"] = lambda ip: netaddr.IPNetwork(ip)[-1] env.filters["agentDistro"] = lambda src: src.split(":")[0] env.filters["agentPort"] = lambda src: src.split(":")[1] env.filters["getFirstFapIP"] = lambda ip: netaddr.IPNetwork(ip)[netaddr.IPNetwork(ip).size / 2] app = Flask(__name__) @app.after_request def add_header(response): if response.status_code == 200: response.cache_control.max_age = 5 response.cache_control.s_maxage = 1 return response @app.route("/<path>", methods=["GET"]) def root_get(path): updateData() try: template = env.get_template(path) body = template.render(objects=objects, options=request.args) except TemplateNotFound: return 'Template "{}" not found\n'.format(path), 404 except Exception as err: return 'Templating of "{}" failed to render. Most likely due to an error in the template. Error transcript:\n\n{}\n----\n\n{}\n'.format(path, err, traceback.format_exc()), 400 return body, 200 @app.route("/<path>", methods=["POST"]) def root_post(path): updateData() try: content = request.stream.read(int(request.headers["Content-Length"])) template = env.from_string(content.decode("utf-8")) body = template.render(objects=objects, options=request.args) except Exception as err: return 'Templating of "{}" failed to render. Most likely due to an error in the template. Error transcript:\n\n{}\n----\n\n{}\n'.format(path, err, traceback.format_exc()), 400 return body, 200 parser = argparse.ArgumentParser(description="Process templates for gondul.", add_help=False) parser.add_argument("-t", "--templates", type=str, nargs="+", help="location of templates") parser.add_argument("-h", "--host", type=str, default="127.0.0.1", help="host address") parser.add_argument("-p", "--port", type=int, default=8080, help="host port") parser.add_argument("-d", "--debug", action="store_true", help="enable debug mode") args = parser.parse_args() env.loader.searchpath = args.templates if not sys.argv[1:]: parser.print_help() app.run(host=args.host, port=args.port, debug=args.debug) <|fim▁end|>
r = requests.get("http://localhost:80/api/{}".format(endpoint)) if r.status_code != 200: raise Exception("Bad status code for endpoint {}: {}".format(endpoint, r.status_code)) return r.json()
<|file_name|>templating.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python3 import argparse import traceback import sys import netaddr import requests from flask import Flask, request from jinja2 import Environment, FileSystemLoader, TemplateNotFound endpoints = "read/networks read/oplog read/snmp read/switches-management public/distro-tree public/config public/dhcp public/dhcp-summary public/ping public/switches public/switch-state".split() objects = {} def getEndpoint(endpoint): r = requests.get("http://localhost:80/api/{}".format(endpoint)) if r.status_code != 200: raise Exception("Bad status code for endpoint {}: {}".format(endpoint, r.status_code)) return r.json() def updateData(): <|fim_middle|> env = Environment(loader=FileSystemLoader([]), trim_blocks=True) env.filters["netmask"] = lambda ip: netaddr.IPNetwork(ip).netmask env.filters["cidr"] = lambda ip: netaddr.IPNetwork(ip).prefixlen env.filters["networkId"] = lambda ip: netaddr.IPNetwork(ip).ip env.filters["getFirstDhcpIp"] = lambda ip: netaddr.IPNetwork(ip)[3] env.filters["getLastDhcpIp"] = lambda ip: netaddr.IPNetwork(ip)[-1] env.filters["agentDistro"] = lambda src: src.split(":")[0] env.filters["agentPort"] = lambda src: src.split(":")[1] env.filters["getFirstFapIP"] = lambda ip: netaddr.IPNetwork(ip)[netaddr.IPNetwork(ip).size / 2] app = Flask(__name__) @app.after_request def add_header(response): if response.status_code == 200: response.cache_control.max_age = 5 response.cache_control.s_maxage = 1 return response @app.route("/<path>", methods=["GET"]) def root_get(path): updateData() try: template = env.get_template(path) body = template.render(objects=objects, options=request.args) except TemplateNotFound: return 'Template "{}" not found\n'.format(path), 404 except Exception as err: return 'Templating of "{}" failed to render. Most likely due to an error in the template. Error transcript:\n\n{}\n----\n\n{}\n'.format(path, err, traceback.format_exc()), 400 return body, 200 @app.route("/<path>", methods=["POST"]) def root_post(path): updateData() try: content = request.stream.read(int(request.headers["Content-Length"])) template = env.from_string(content.decode("utf-8")) body = template.render(objects=objects, options=request.args) except Exception as err: return 'Templating of "{}" failed to render. Most likely due to an error in the template. Error transcript:\n\n{}\n----\n\n{}\n'.format(path, err, traceback.format_exc()), 400 return body, 200 parser = argparse.ArgumentParser(description="Process templates for gondul.", add_help=False) parser.add_argument("-t", "--templates", type=str, nargs="+", help="location of templates") parser.add_argument("-h", "--host", type=str, default="127.0.0.1", help="host address") parser.add_argument("-p", "--port", type=int, default=8080, help="host port") parser.add_argument("-d", "--debug", action="store_true", help="enable debug mode") args = parser.parse_args() env.loader.searchpath = args.templates if not sys.argv[1:]: parser.print_help() app.run(host=args.host, port=args.port, debug=args.debug) <|fim▁end|>
for a in endpoints: objects[a] = getEndpoint(a)
<|file_name|>templating.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python3 import argparse import traceback import sys import netaddr import requests from flask import Flask, request from jinja2 import Environment, FileSystemLoader, TemplateNotFound endpoints = "read/networks read/oplog read/snmp read/switches-management public/distro-tree public/config public/dhcp public/dhcp-summary public/ping public/switches public/switch-state".split() objects = {} def getEndpoint(endpoint): r = requests.get("http://localhost:80/api/{}".format(endpoint)) if r.status_code != 200: raise Exception("Bad status code for endpoint {}: {}".format(endpoint, r.status_code)) return r.json() def updateData(): for a in endpoints: objects[a] = getEndpoint(a) env = Environment(loader=FileSystemLoader([]), trim_blocks=True) env.filters["netmask"] = lambda ip: netaddr.IPNetwork(ip).netmask env.filters["cidr"] = lambda ip: netaddr.IPNetwork(ip).prefixlen env.filters["networkId"] = lambda ip: netaddr.IPNetwork(ip).ip env.filters["getFirstDhcpIp"] = lambda ip: netaddr.IPNetwork(ip)[3] env.filters["getLastDhcpIp"] = lambda ip: netaddr.IPNetwork(ip)[-1] env.filters["agentDistro"] = lambda src: src.split(":")[0] env.filters["agentPort"] = lambda src: src.split(":")[1] env.filters["getFirstFapIP"] = lambda ip: netaddr.IPNetwork(ip)[netaddr.IPNetwork(ip).size / 2] app = Flask(__name__) @app.after_request def add_header(response): <|fim_middle|> @app.route("/<path>", methods=["GET"]) def root_get(path): updateData() try: template = env.get_template(path) body = template.render(objects=objects, options=request.args) except TemplateNotFound: return 'Template "{}" not found\n'.format(path), 404 except Exception as err: return 'Templating of "{}" failed to render. Most likely due to an error in the template. Error transcript:\n\n{}\n----\n\n{}\n'.format(path, err, traceback.format_exc()), 400 return body, 200 @app.route("/<path>", methods=["POST"]) def root_post(path): updateData() try: content = request.stream.read(int(request.headers["Content-Length"])) template = env.from_string(content.decode("utf-8")) body = template.render(objects=objects, options=request.args) except Exception as err: return 'Templating of "{}" failed to render. Most likely due to an error in the template. Error transcript:\n\n{}\n----\n\n{}\n'.format(path, err, traceback.format_exc()), 400 return body, 200 parser = argparse.ArgumentParser(description="Process templates for gondul.", add_help=False) parser.add_argument("-t", "--templates", type=str, nargs="+", help="location of templates") parser.add_argument("-h", "--host", type=str, default="127.0.0.1", help="host address") parser.add_argument("-p", "--port", type=int, default=8080, help="host port") parser.add_argument("-d", "--debug", action="store_true", help="enable debug mode") args = parser.parse_args() env.loader.searchpath = args.templates if not sys.argv[1:]: parser.print_help() app.run(host=args.host, port=args.port, debug=args.debug) <|fim▁end|>
if response.status_code == 200: response.cache_control.max_age = 5 response.cache_control.s_maxage = 1 return response
<|file_name|>templating.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python3 import argparse import traceback import sys import netaddr import requests from flask import Flask, request from jinja2 import Environment, FileSystemLoader, TemplateNotFound endpoints = "read/networks read/oplog read/snmp read/switches-management public/distro-tree public/config public/dhcp public/dhcp-summary public/ping public/switches public/switch-state".split() objects = {} def getEndpoint(endpoint): r = requests.get("http://localhost:80/api/{}".format(endpoint)) if r.status_code != 200: raise Exception("Bad status code for endpoint {}: {}".format(endpoint, r.status_code)) return r.json() def updateData(): for a in endpoints: objects[a] = getEndpoint(a) env = Environment(loader=FileSystemLoader([]), trim_blocks=True) env.filters["netmask"] = lambda ip: netaddr.IPNetwork(ip).netmask env.filters["cidr"] = lambda ip: netaddr.IPNetwork(ip).prefixlen env.filters["networkId"] = lambda ip: netaddr.IPNetwork(ip).ip env.filters["getFirstDhcpIp"] = lambda ip: netaddr.IPNetwork(ip)[3] env.filters["getLastDhcpIp"] = lambda ip: netaddr.IPNetwork(ip)[-1] env.filters["agentDistro"] = lambda src: src.split(":")[0] env.filters["agentPort"] = lambda src: src.split(":")[1] env.filters["getFirstFapIP"] = lambda ip: netaddr.IPNetwork(ip)[netaddr.IPNetwork(ip).size / 2] app = Flask(__name__) @app.after_request def add_header(response): if response.status_code == 200: response.cache_control.max_age = 5 response.cache_control.s_maxage = 1 return response @app.route("/<path>", methods=["GET"]) def root_get(path): <|fim_middle|> @app.route("/<path>", methods=["POST"]) def root_post(path): updateData() try: content = request.stream.read(int(request.headers["Content-Length"])) template = env.from_string(content.decode("utf-8")) body = template.render(objects=objects, options=request.args) except Exception as err: return 'Templating of "{}" failed to render. Most likely due to an error in the template. Error transcript:\n\n{}\n----\n\n{}\n'.format(path, err, traceback.format_exc()), 400 return body, 200 parser = argparse.ArgumentParser(description="Process templates for gondul.", add_help=False) parser.add_argument("-t", "--templates", type=str, nargs="+", help="location of templates") parser.add_argument("-h", "--host", type=str, default="127.0.0.1", help="host address") parser.add_argument("-p", "--port", type=int, default=8080, help="host port") parser.add_argument("-d", "--debug", action="store_true", help="enable debug mode") args = parser.parse_args() env.loader.searchpath = args.templates if not sys.argv[1:]: parser.print_help() app.run(host=args.host, port=args.port, debug=args.debug) <|fim▁end|>
updateData() try: template = env.get_template(path) body = template.render(objects=objects, options=request.args) except TemplateNotFound: return 'Template "{}" not found\n'.format(path), 404 except Exception as err: return 'Templating of "{}" failed to render. Most likely due to an error in the template. Error transcript:\n\n{}\n----\n\n{}\n'.format(path, err, traceback.format_exc()), 400 return body, 200
<|file_name|>templating.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python3 import argparse import traceback import sys import netaddr import requests from flask import Flask, request from jinja2 import Environment, FileSystemLoader, TemplateNotFound endpoints = "read/networks read/oplog read/snmp read/switches-management public/distro-tree public/config public/dhcp public/dhcp-summary public/ping public/switches public/switch-state".split() objects = {} def getEndpoint(endpoint): r = requests.get("http://localhost:80/api/{}".format(endpoint)) if r.status_code != 200: raise Exception("Bad status code for endpoint {}: {}".format(endpoint, r.status_code)) return r.json() def updateData(): for a in endpoints: objects[a] = getEndpoint(a) env = Environment(loader=FileSystemLoader([]), trim_blocks=True) env.filters["netmask"] = lambda ip: netaddr.IPNetwork(ip).netmask env.filters["cidr"] = lambda ip: netaddr.IPNetwork(ip).prefixlen env.filters["networkId"] = lambda ip: netaddr.IPNetwork(ip).ip env.filters["getFirstDhcpIp"] = lambda ip: netaddr.IPNetwork(ip)[3] env.filters["getLastDhcpIp"] = lambda ip: netaddr.IPNetwork(ip)[-1] env.filters["agentDistro"] = lambda src: src.split(":")[0] env.filters["agentPort"] = lambda src: src.split(":")[1] env.filters["getFirstFapIP"] = lambda ip: netaddr.IPNetwork(ip)[netaddr.IPNetwork(ip).size / 2] app = Flask(__name__) @app.after_request def add_header(response): if response.status_code == 200: response.cache_control.max_age = 5 response.cache_control.s_maxage = 1 return response @app.route("/<path>", methods=["GET"]) def root_get(path): updateData() try: template = env.get_template(path) body = template.render(objects=objects, options=request.args) except TemplateNotFound: return 'Template "{}" not found\n'.format(path), 404 except Exception as err: return 'Templating of "{}" failed to render. Most likely due to an error in the template. Error transcript:\n\n{}\n----\n\n{}\n'.format(path, err, traceback.format_exc()), 400 return body, 200 @app.route("/<path>", methods=["POST"]) def root_post(path): <|fim_middle|> parser = argparse.ArgumentParser(description="Process templates for gondul.", add_help=False) parser.add_argument("-t", "--templates", type=str, nargs="+", help="location of templates") parser.add_argument("-h", "--host", type=str, default="127.0.0.1", help="host address") parser.add_argument("-p", "--port", type=int, default=8080, help="host port") parser.add_argument("-d", "--debug", action="store_true", help="enable debug mode") args = parser.parse_args() env.loader.searchpath = args.templates if not sys.argv[1:]: parser.print_help() app.run(host=args.host, port=args.port, debug=args.debug) <|fim▁end|>
updateData() try: content = request.stream.read(int(request.headers["Content-Length"])) template = env.from_string(content.decode("utf-8")) body = template.render(objects=objects, options=request.args) except Exception as err: return 'Templating of "{}" failed to render. Most likely due to an error in the template. Error transcript:\n\n{}\n----\n\n{}\n'.format(path, err, traceback.format_exc()), 400 return body, 200
<|file_name|>templating.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python3 import argparse import traceback import sys import netaddr import requests from flask import Flask, request from jinja2 import Environment, FileSystemLoader, TemplateNotFound endpoints = "read/networks read/oplog read/snmp read/switches-management public/distro-tree public/config public/dhcp public/dhcp-summary public/ping public/switches public/switch-state".split() objects = {} def getEndpoint(endpoint): r = requests.get("http://localhost:80/api/{}".format(endpoint)) if r.status_code != 200: <|fim_middle|> return r.json() def updateData(): for a in endpoints: objects[a] = getEndpoint(a) env = Environment(loader=FileSystemLoader([]), trim_blocks=True) env.filters["netmask"] = lambda ip: netaddr.IPNetwork(ip).netmask env.filters["cidr"] = lambda ip: netaddr.IPNetwork(ip).prefixlen env.filters["networkId"] = lambda ip: netaddr.IPNetwork(ip).ip env.filters["getFirstDhcpIp"] = lambda ip: netaddr.IPNetwork(ip)[3] env.filters["getLastDhcpIp"] = lambda ip: netaddr.IPNetwork(ip)[-1] env.filters["agentDistro"] = lambda src: src.split(":")[0] env.filters["agentPort"] = lambda src: src.split(":")[1] env.filters["getFirstFapIP"] = lambda ip: netaddr.IPNetwork(ip)[netaddr.IPNetwork(ip).size / 2] app = Flask(__name__) @app.after_request def add_header(response): if response.status_code == 200: response.cache_control.max_age = 5 response.cache_control.s_maxage = 1 return response @app.route("/<path>", methods=["GET"]) def root_get(path): updateData() try: template = env.get_template(path) body = template.render(objects=objects, options=request.args) except TemplateNotFound: return 'Template "{}" not found\n'.format(path), 404 except Exception as err: return 'Templating of "{}" failed to render. Most likely due to an error in the template. Error transcript:\n\n{}\n----\n\n{}\n'.format(path, err, traceback.format_exc()), 400 return body, 200 @app.route("/<path>", methods=["POST"]) def root_post(path): updateData() try: content = request.stream.read(int(request.headers["Content-Length"])) template = env.from_string(content.decode("utf-8")) body = template.render(objects=objects, options=request.args) except Exception as err: return 'Templating of "{}" failed to render. Most likely due to an error in the template. Error transcript:\n\n{}\n----\n\n{}\n'.format(path, err, traceback.format_exc()), 400 return body, 200 parser = argparse.ArgumentParser(description="Process templates for gondul.", add_help=False) parser.add_argument("-t", "--templates", type=str, nargs="+", help="location of templates") parser.add_argument("-h", "--host", type=str, default="127.0.0.1", help="host address") parser.add_argument("-p", "--port", type=int, default=8080, help="host port") parser.add_argument("-d", "--debug", action="store_true", help="enable debug mode") args = parser.parse_args() env.loader.searchpath = args.templates if not sys.argv[1:]: parser.print_help() app.run(host=args.host, port=args.port, debug=args.debug) <|fim▁end|>
raise Exception("Bad status code for endpoint {}: {}".format(endpoint, r.status_code))
<|file_name|>templating.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python3 import argparse import traceback import sys import netaddr import requests from flask import Flask, request from jinja2 import Environment, FileSystemLoader, TemplateNotFound endpoints = "read/networks read/oplog read/snmp read/switches-management public/distro-tree public/config public/dhcp public/dhcp-summary public/ping public/switches public/switch-state".split() objects = {} def getEndpoint(endpoint): r = requests.get("http://localhost:80/api/{}".format(endpoint)) if r.status_code != 200: raise Exception("Bad status code for endpoint {}: {}".format(endpoint, r.status_code)) return r.json() def updateData(): for a in endpoints: objects[a] = getEndpoint(a) env = Environment(loader=FileSystemLoader([]), trim_blocks=True) env.filters["netmask"] = lambda ip: netaddr.IPNetwork(ip).netmask env.filters["cidr"] = lambda ip: netaddr.IPNetwork(ip).prefixlen env.filters["networkId"] = lambda ip: netaddr.IPNetwork(ip).ip env.filters["getFirstDhcpIp"] = lambda ip: netaddr.IPNetwork(ip)[3] env.filters["getLastDhcpIp"] = lambda ip: netaddr.IPNetwork(ip)[-1] env.filters["agentDistro"] = lambda src: src.split(":")[0] env.filters["agentPort"] = lambda src: src.split(":")[1] env.filters["getFirstFapIP"] = lambda ip: netaddr.IPNetwork(ip)[netaddr.IPNetwork(ip).size / 2] app = Flask(__name__) @app.after_request def add_header(response): if response.status_code == 200: <|fim_middle|> return response @app.route("/<path>", methods=["GET"]) def root_get(path): updateData() try: template = env.get_template(path) body = template.render(objects=objects, options=request.args) except TemplateNotFound: return 'Template "{}" not found\n'.format(path), 404 except Exception as err: return 'Templating of "{}" failed to render. Most likely due to an error in the template. Error transcript:\n\n{}\n----\n\n{}\n'.format(path, err, traceback.format_exc()), 400 return body, 200 @app.route("/<path>", methods=["POST"]) def root_post(path): updateData() try: content = request.stream.read(int(request.headers["Content-Length"])) template = env.from_string(content.decode("utf-8")) body = template.render(objects=objects, options=request.args) except Exception as err: return 'Templating of "{}" failed to render. Most likely due to an error in the template. Error transcript:\n\n{}\n----\n\n{}\n'.format(path, err, traceback.format_exc()), 400 return body, 200 parser = argparse.ArgumentParser(description="Process templates for gondul.", add_help=False) parser.add_argument("-t", "--templates", type=str, nargs="+", help="location of templates") parser.add_argument("-h", "--host", type=str, default="127.0.0.1", help="host address") parser.add_argument("-p", "--port", type=int, default=8080, help="host port") parser.add_argument("-d", "--debug", action="store_true", help="enable debug mode") args = parser.parse_args() env.loader.searchpath = args.templates if not sys.argv[1:]: parser.print_help() app.run(host=args.host, port=args.port, debug=args.debug) <|fim▁end|>
response.cache_control.max_age = 5 response.cache_control.s_maxage = 1
<|file_name|>templating.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python3 import argparse import traceback import sys import netaddr import requests from flask import Flask, request from jinja2 import Environment, FileSystemLoader, TemplateNotFound endpoints = "read/networks read/oplog read/snmp read/switches-management public/distro-tree public/config public/dhcp public/dhcp-summary public/ping public/switches public/switch-state".split() objects = {} def getEndpoint(endpoint): r = requests.get("http://localhost:80/api/{}".format(endpoint)) if r.status_code != 200: raise Exception("Bad status code for endpoint {}: {}".format(endpoint, r.status_code)) return r.json() def updateData(): for a in endpoints: objects[a] = getEndpoint(a) env = Environment(loader=FileSystemLoader([]), trim_blocks=True) env.filters["netmask"] = lambda ip: netaddr.IPNetwork(ip).netmask env.filters["cidr"] = lambda ip: netaddr.IPNetwork(ip).prefixlen env.filters["networkId"] = lambda ip: netaddr.IPNetwork(ip).ip env.filters["getFirstDhcpIp"] = lambda ip: netaddr.IPNetwork(ip)[3] env.filters["getLastDhcpIp"] = lambda ip: netaddr.IPNetwork(ip)[-1] env.filters["agentDistro"] = lambda src: src.split(":")[0] env.filters["agentPort"] = lambda src: src.split(":")[1] env.filters["getFirstFapIP"] = lambda ip: netaddr.IPNetwork(ip)[netaddr.IPNetwork(ip).size / 2] app = Flask(__name__) @app.after_request def add_header(response): if response.status_code == 200: response.cache_control.max_age = 5 response.cache_control.s_maxage = 1 return response @app.route("/<path>", methods=["GET"]) def root_get(path): updateData() try: template = env.get_template(path) body = template.render(objects=objects, options=request.args) except TemplateNotFound: return 'Template "{}" not found\n'.format(path), 404 except Exception as err: return 'Templating of "{}" failed to render. Most likely due to an error in the template. Error transcript:\n\n{}\n----\n\n{}\n'.format(path, err, traceback.format_exc()), 400 return body, 200 @app.route("/<path>", methods=["POST"]) def root_post(path): updateData() try: content = request.stream.read(int(request.headers["Content-Length"])) template = env.from_string(content.decode("utf-8")) body = template.render(objects=objects, options=request.args) except Exception as err: return 'Templating of "{}" failed to render. Most likely due to an error in the template. Error transcript:\n\n{}\n----\n\n{}\n'.format(path, err, traceback.format_exc()), 400 return body, 200 parser = argparse.ArgumentParser(description="Process templates for gondul.", add_help=False) parser.add_argument("-t", "--templates", type=str, nargs="+", help="location of templates") parser.add_argument("-h", "--host", type=str, default="127.0.0.1", help="host address") parser.add_argument("-p", "--port", type=int, default=8080, help="host port") parser.add_argument("-d", "--debug", action="store_true", help="enable debug mode") args = parser.parse_args() env.loader.searchpath = args.templates if not sys.argv[1:]: <|fim_middle|> app.run(host=args.host, port=args.port, debug=args.debug) <|fim▁end|>
parser.print_help()
<|file_name|>templating.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python3 import argparse import traceback import sys import netaddr import requests from flask import Flask, request from jinja2 import Environment, FileSystemLoader, TemplateNotFound endpoints = "read/networks read/oplog read/snmp read/switches-management public/distro-tree public/config public/dhcp public/dhcp-summary public/ping public/switches public/switch-state".split() objects = {} def <|fim_middle|>(endpoint): r = requests.get("http://localhost:80/api/{}".format(endpoint)) if r.status_code != 200: raise Exception("Bad status code for endpoint {}: {}".format(endpoint, r.status_code)) return r.json() def updateData(): for a in endpoints: objects[a] = getEndpoint(a) env = Environment(loader=FileSystemLoader([]), trim_blocks=True) env.filters["netmask"] = lambda ip: netaddr.IPNetwork(ip).netmask env.filters["cidr"] = lambda ip: netaddr.IPNetwork(ip).prefixlen env.filters["networkId"] = lambda ip: netaddr.IPNetwork(ip).ip env.filters["getFirstDhcpIp"] = lambda ip: netaddr.IPNetwork(ip)[3] env.filters["getLastDhcpIp"] = lambda ip: netaddr.IPNetwork(ip)[-1] env.filters["agentDistro"] = lambda src: src.split(":")[0] env.filters["agentPort"] = lambda src: src.split(":")[1] env.filters["getFirstFapIP"] = lambda ip: netaddr.IPNetwork(ip)[netaddr.IPNetwork(ip).size / 2] app = Flask(__name__) @app.after_request def add_header(response): if response.status_code == 200: response.cache_control.max_age = 5 response.cache_control.s_maxage = 1 return response @app.route("/<path>", methods=["GET"]) def root_get(path): updateData() try: template = env.get_template(path) body = template.render(objects=objects, options=request.args) except TemplateNotFound: return 'Template "{}" not found\n'.format(path), 404 except Exception as err: return 'Templating of "{}" failed to render. Most likely due to an error in the template. Error transcript:\n\n{}\n----\n\n{}\n'.format(path, err, traceback.format_exc()), 400 return body, 200 @app.route("/<path>", methods=["POST"]) def root_post(path): updateData() try: content = request.stream.read(int(request.headers["Content-Length"])) template = env.from_string(content.decode("utf-8")) body = template.render(objects=objects, options=request.args) except Exception as err: return 'Templating of "{}" failed to render. Most likely due to an error in the template. Error transcript:\n\n{}\n----\n\n{}\n'.format(path, err, traceback.format_exc()), 400 return body, 200 parser = argparse.ArgumentParser(description="Process templates for gondul.", add_help=False) parser.add_argument("-t", "--templates", type=str, nargs="+", help="location of templates") parser.add_argument("-h", "--host", type=str, default="127.0.0.1", help="host address") parser.add_argument("-p", "--port", type=int, default=8080, help="host port") parser.add_argument("-d", "--debug", action="store_true", help="enable debug mode") args = parser.parse_args() env.loader.searchpath = args.templates if not sys.argv[1:]: parser.print_help() app.run(host=args.host, port=args.port, debug=args.debug) <|fim▁end|>
getEndpoint
<|file_name|>templating.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python3 import argparse import traceback import sys import netaddr import requests from flask import Flask, request from jinja2 import Environment, FileSystemLoader, TemplateNotFound endpoints = "read/networks read/oplog read/snmp read/switches-management public/distro-tree public/config public/dhcp public/dhcp-summary public/ping public/switches public/switch-state".split() objects = {} def getEndpoint(endpoint): r = requests.get("http://localhost:80/api/{}".format(endpoint)) if r.status_code != 200: raise Exception("Bad status code for endpoint {}: {}".format(endpoint, r.status_code)) return r.json() def <|fim_middle|>(): for a in endpoints: objects[a] = getEndpoint(a) env = Environment(loader=FileSystemLoader([]), trim_blocks=True) env.filters["netmask"] = lambda ip: netaddr.IPNetwork(ip).netmask env.filters["cidr"] = lambda ip: netaddr.IPNetwork(ip).prefixlen env.filters["networkId"] = lambda ip: netaddr.IPNetwork(ip).ip env.filters["getFirstDhcpIp"] = lambda ip: netaddr.IPNetwork(ip)[3] env.filters["getLastDhcpIp"] = lambda ip: netaddr.IPNetwork(ip)[-1] env.filters["agentDistro"] = lambda src: src.split(":")[0] env.filters["agentPort"] = lambda src: src.split(":")[1] env.filters["getFirstFapIP"] = lambda ip: netaddr.IPNetwork(ip)[netaddr.IPNetwork(ip).size / 2] app = Flask(__name__) @app.after_request def add_header(response): if response.status_code == 200: response.cache_control.max_age = 5 response.cache_control.s_maxage = 1 return response @app.route("/<path>", methods=["GET"]) def root_get(path): updateData() try: template = env.get_template(path) body = template.render(objects=objects, options=request.args) except TemplateNotFound: return 'Template "{}" not found\n'.format(path), 404 except Exception as err: return 'Templating of "{}" failed to render. Most likely due to an error in the template. Error transcript:\n\n{}\n----\n\n{}\n'.format(path, err, traceback.format_exc()), 400 return body, 200 @app.route("/<path>", methods=["POST"]) def root_post(path): updateData() try: content = request.stream.read(int(request.headers["Content-Length"])) template = env.from_string(content.decode("utf-8")) body = template.render(objects=objects, options=request.args) except Exception as err: return 'Templating of "{}" failed to render. Most likely due to an error in the template. Error transcript:\n\n{}\n----\n\n{}\n'.format(path, err, traceback.format_exc()), 400 return body, 200 parser = argparse.ArgumentParser(description="Process templates for gondul.", add_help=False) parser.add_argument("-t", "--templates", type=str, nargs="+", help="location of templates") parser.add_argument("-h", "--host", type=str, default="127.0.0.1", help="host address") parser.add_argument("-p", "--port", type=int, default=8080, help="host port") parser.add_argument("-d", "--debug", action="store_true", help="enable debug mode") args = parser.parse_args() env.loader.searchpath = args.templates if not sys.argv[1:]: parser.print_help() app.run(host=args.host, port=args.port, debug=args.debug) <|fim▁end|>
updateData
<|file_name|>templating.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python3 import argparse import traceback import sys import netaddr import requests from flask import Flask, request from jinja2 import Environment, FileSystemLoader, TemplateNotFound endpoints = "read/networks read/oplog read/snmp read/switches-management public/distro-tree public/config public/dhcp public/dhcp-summary public/ping public/switches public/switch-state".split() objects = {} def getEndpoint(endpoint): r = requests.get("http://localhost:80/api/{}".format(endpoint)) if r.status_code != 200: raise Exception("Bad status code for endpoint {}: {}".format(endpoint, r.status_code)) return r.json() def updateData(): for a in endpoints: objects[a] = getEndpoint(a) env = Environment(loader=FileSystemLoader([]), trim_blocks=True) env.filters["netmask"] = lambda ip: netaddr.IPNetwork(ip).netmask env.filters["cidr"] = lambda ip: netaddr.IPNetwork(ip).prefixlen env.filters["networkId"] = lambda ip: netaddr.IPNetwork(ip).ip env.filters["getFirstDhcpIp"] = lambda ip: netaddr.IPNetwork(ip)[3] env.filters["getLastDhcpIp"] = lambda ip: netaddr.IPNetwork(ip)[-1] env.filters["agentDistro"] = lambda src: src.split(":")[0] env.filters["agentPort"] = lambda src: src.split(":")[1] env.filters["getFirstFapIP"] = lambda ip: netaddr.IPNetwork(ip)[netaddr.IPNetwork(ip).size / 2] app = Flask(__name__) @app.after_request def <|fim_middle|>(response): if response.status_code == 200: response.cache_control.max_age = 5 response.cache_control.s_maxage = 1 return response @app.route("/<path>", methods=["GET"]) def root_get(path): updateData() try: template = env.get_template(path) body = template.render(objects=objects, options=request.args) except TemplateNotFound: return 'Template "{}" not found\n'.format(path), 404 except Exception as err: return 'Templating of "{}" failed to render. Most likely due to an error in the template. Error transcript:\n\n{}\n----\n\n{}\n'.format(path, err, traceback.format_exc()), 400 return body, 200 @app.route("/<path>", methods=["POST"]) def root_post(path): updateData() try: content = request.stream.read(int(request.headers["Content-Length"])) template = env.from_string(content.decode("utf-8")) body = template.render(objects=objects, options=request.args) except Exception as err: return 'Templating of "{}" failed to render. Most likely due to an error in the template. Error transcript:\n\n{}\n----\n\n{}\n'.format(path, err, traceback.format_exc()), 400 return body, 200 parser = argparse.ArgumentParser(description="Process templates for gondul.", add_help=False) parser.add_argument("-t", "--templates", type=str, nargs="+", help="location of templates") parser.add_argument("-h", "--host", type=str, default="127.0.0.1", help="host address") parser.add_argument("-p", "--port", type=int, default=8080, help="host port") parser.add_argument("-d", "--debug", action="store_true", help="enable debug mode") args = parser.parse_args() env.loader.searchpath = args.templates if not sys.argv[1:]: parser.print_help() app.run(host=args.host, port=args.port, debug=args.debug) <|fim▁end|>
add_header
<|file_name|>templating.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python3 import argparse import traceback import sys import netaddr import requests from flask import Flask, request from jinja2 import Environment, FileSystemLoader, TemplateNotFound endpoints = "read/networks read/oplog read/snmp read/switches-management public/distro-tree public/config public/dhcp public/dhcp-summary public/ping public/switches public/switch-state".split() objects = {} def getEndpoint(endpoint): r = requests.get("http://localhost:80/api/{}".format(endpoint)) if r.status_code != 200: raise Exception("Bad status code for endpoint {}: {}".format(endpoint, r.status_code)) return r.json() def updateData(): for a in endpoints: objects[a] = getEndpoint(a) env = Environment(loader=FileSystemLoader([]), trim_blocks=True) env.filters["netmask"] = lambda ip: netaddr.IPNetwork(ip).netmask env.filters["cidr"] = lambda ip: netaddr.IPNetwork(ip).prefixlen env.filters["networkId"] = lambda ip: netaddr.IPNetwork(ip).ip env.filters["getFirstDhcpIp"] = lambda ip: netaddr.IPNetwork(ip)[3] env.filters["getLastDhcpIp"] = lambda ip: netaddr.IPNetwork(ip)[-1] env.filters["agentDistro"] = lambda src: src.split(":")[0] env.filters["agentPort"] = lambda src: src.split(":")[1] env.filters["getFirstFapIP"] = lambda ip: netaddr.IPNetwork(ip)[netaddr.IPNetwork(ip).size / 2] app = Flask(__name__) @app.after_request def add_header(response): if response.status_code == 200: response.cache_control.max_age = 5 response.cache_control.s_maxage = 1 return response @app.route("/<path>", methods=["GET"]) def <|fim_middle|>(path): updateData() try: template = env.get_template(path) body = template.render(objects=objects, options=request.args) except TemplateNotFound: return 'Template "{}" not found\n'.format(path), 404 except Exception as err: return 'Templating of "{}" failed to render. Most likely due to an error in the template. Error transcript:\n\n{}\n----\n\n{}\n'.format(path, err, traceback.format_exc()), 400 return body, 200 @app.route("/<path>", methods=["POST"]) def root_post(path): updateData() try: content = request.stream.read(int(request.headers["Content-Length"])) template = env.from_string(content.decode("utf-8")) body = template.render(objects=objects, options=request.args) except Exception as err: return 'Templating of "{}" failed to render. Most likely due to an error in the template. Error transcript:\n\n{}\n----\n\n{}\n'.format(path, err, traceback.format_exc()), 400 return body, 200 parser = argparse.ArgumentParser(description="Process templates for gondul.", add_help=False) parser.add_argument("-t", "--templates", type=str, nargs="+", help="location of templates") parser.add_argument("-h", "--host", type=str, default="127.0.0.1", help="host address") parser.add_argument("-p", "--port", type=int, default=8080, help="host port") parser.add_argument("-d", "--debug", action="store_true", help="enable debug mode") args = parser.parse_args() env.loader.searchpath = args.templates if not sys.argv[1:]: parser.print_help() app.run(host=args.host, port=args.port, debug=args.debug) <|fim▁end|>
root_get
<|file_name|>templating.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python3 import argparse import traceback import sys import netaddr import requests from flask import Flask, request from jinja2 import Environment, FileSystemLoader, TemplateNotFound endpoints = "read/networks read/oplog read/snmp read/switches-management public/distro-tree public/config public/dhcp public/dhcp-summary public/ping public/switches public/switch-state".split() objects = {} def getEndpoint(endpoint): r = requests.get("http://localhost:80/api/{}".format(endpoint)) if r.status_code != 200: raise Exception("Bad status code for endpoint {}: {}".format(endpoint, r.status_code)) return r.json() def updateData(): for a in endpoints: objects[a] = getEndpoint(a) env = Environment(loader=FileSystemLoader([]), trim_blocks=True) env.filters["netmask"] = lambda ip: netaddr.IPNetwork(ip).netmask env.filters["cidr"] = lambda ip: netaddr.IPNetwork(ip).prefixlen env.filters["networkId"] = lambda ip: netaddr.IPNetwork(ip).ip env.filters["getFirstDhcpIp"] = lambda ip: netaddr.IPNetwork(ip)[3] env.filters["getLastDhcpIp"] = lambda ip: netaddr.IPNetwork(ip)[-1] env.filters["agentDistro"] = lambda src: src.split(":")[0] env.filters["agentPort"] = lambda src: src.split(":")[1] env.filters["getFirstFapIP"] = lambda ip: netaddr.IPNetwork(ip)[netaddr.IPNetwork(ip).size / 2] app = Flask(__name__) @app.after_request def add_header(response): if response.status_code == 200: response.cache_control.max_age = 5 response.cache_control.s_maxage = 1 return response @app.route("/<path>", methods=["GET"]) def root_get(path): updateData() try: template = env.get_template(path) body = template.render(objects=objects, options=request.args) except TemplateNotFound: return 'Template "{}" not found\n'.format(path), 404 except Exception as err: return 'Templating of "{}" failed to render. Most likely due to an error in the template. Error transcript:\n\n{}\n----\n\n{}\n'.format(path, err, traceback.format_exc()), 400 return body, 200 @app.route("/<path>", methods=["POST"]) def <|fim_middle|>(path): updateData() try: content = request.stream.read(int(request.headers["Content-Length"])) template = env.from_string(content.decode("utf-8")) body = template.render(objects=objects, options=request.args) except Exception as err: return 'Templating of "{}" failed to render. Most likely due to an error in the template. Error transcript:\n\n{}\n----\n\n{}\n'.format(path, err, traceback.format_exc()), 400 return body, 200 parser = argparse.ArgumentParser(description="Process templates for gondul.", add_help=False) parser.add_argument("-t", "--templates", type=str, nargs="+", help="location of templates") parser.add_argument("-h", "--host", type=str, default="127.0.0.1", help="host address") parser.add_argument("-p", "--port", type=int, default=8080, help="host port") parser.add_argument("-d", "--debug", action="store_true", help="enable debug mode") args = parser.parse_args() env.loader.searchpath = args.templates if not sys.argv[1:]: parser.print_help() app.run(host=args.host, port=args.port, debug=args.debug) <|fim▁end|>
root_post
<|file_name|>help.py<|end_file_name|><|fim▁begin|># Author: Nick Raptis <[email protected]> """ Module for listing commands and help. """ from basemodule import BaseModule, BaseCommandContext from alternatives import _ class HelpContext(BaseCommandContext): def cmd_list(self, argument): """List commands""" arg = argument.lower() index = self.bot.help_index public = "public commands -- %s" % " ".join(index['public']) private = "private commands -- %s" % " ".join(index['private']) if 'all' in arg or 'both' in arg: output = "\n".join((public, private)) elif 'pub' in arg or self.target.startswith('#'): output = public elif 'priv' in arg or not self.target.startswith('#'): output = private else: # we shouldn't be here self.logger.error("cmd_list") return self.send(self.target, output) def cmd_modules(self, argument): """List active modules""" index = self.bot.help_index output = "active modules -- %s" % " ".join(index['modules'].keys()) self.send(self.target, output) def cmd_help(self, argument): """Get help on a command or module""" arg = argument.lower() index = self.bot.help_index target = self.target args = arg.split() if not args: s = "usage: help <command> [public|private] / help module <module>" self.send(target, s) elif args[0] == 'module': args.pop(0) if not args: self.send(target, "usage: help module <module>") else: help_item = index['modules'].get(args[0]) if help_item: self.send(target, help_item['summary']) else: self.send(target, _("No help for %s"), args[0]) else: args.append("") cmd = args.pop(0) cmd_type = args.pop(0) if 'pu' in cmd_type or self.target.startswith('#'): cmd_type = 'public' elif 'pr' in cmd_type or not self.target.startswith('#'): cmd_type = 'private' else: # we shouldn't be here self.logger.error("cmd_list")<|fim▁hole|> if help_item: self.send(target, index[cmd_type][cmd]['summary']) else: self.send(target, _("No help for %s"), cmd) class HelpModule(BaseModule): context_class = HelpContext module = HelpModule<|fim▁end|>
return help_item = index[cmd_type].get(cmd)
<|file_name|>help.py<|end_file_name|><|fim▁begin|># Author: Nick Raptis <[email protected]> """ Module for listing commands and help. """ from basemodule import BaseModule, BaseCommandContext from alternatives import _ class HelpContext(BaseCommandContext): <|fim_middle|> class HelpModule(BaseModule): context_class = HelpContext module = HelpModule <|fim▁end|>
def cmd_list(self, argument): """List commands""" arg = argument.lower() index = self.bot.help_index public = "public commands -- %s" % " ".join(index['public']) private = "private commands -- %s" % " ".join(index['private']) if 'all' in arg or 'both' in arg: output = "\n".join((public, private)) elif 'pub' in arg or self.target.startswith('#'): output = public elif 'priv' in arg or not self.target.startswith('#'): output = private else: # we shouldn't be here self.logger.error("cmd_list") return self.send(self.target, output) def cmd_modules(self, argument): """List active modules""" index = self.bot.help_index output = "active modules -- %s" % " ".join(index['modules'].keys()) self.send(self.target, output) def cmd_help(self, argument): """Get help on a command or module""" arg = argument.lower() index = self.bot.help_index target = self.target args = arg.split() if not args: s = "usage: help <command> [public|private] / help module <module>" self.send(target, s) elif args[0] == 'module': args.pop(0) if not args: self.send(target, "usage: help module <module>") else: help_item = index['modules'].get(args[0]) if help_item: self.send(target, help_item['summary']) else: self.send(target, _("No help for %s"), args[0]) else: args.append("") cmd = args.pop(0) cmd_type = args.pop(0) if 'pu' in cmd_type or self.target.startswith('#'): cmd_type = 'public' elif 'pr' in cmd_type or not self.target.startswith('#'): cmd_type = 'private' else: # we shouldn't be here self.logger.error("cmd_list") return help_item = index[cmd_type].get(cmd) if help_item: self.send(target, index[cmd_type][cmd]['summary']) else: self.send(target, _("No help for %s"), cmd)
<|file_name|>help.py<|end_file_name|><|fim▁begin|># Author: Nick Raptis <[email protected]> """ Module for listing commands and help. """ from basemodule import BaseModule, BaseCommandContext from alternatives import _ class HelpContext(BaseCommandContext): def cmd_list(self, argument): <|fim_middle|> def cmd_modules(self, argument): """List active modules""" index = self.bot.help_index output = "active modules -- %s" % " ".join(index['modules'].keys()) self.send(self.target, output) def cmd_help(self, argument): """Get help on a command or module""" arg = argument.lower() index = self.bot.help_index target = self.target args = arg.split() if not args: s = "usage: help <command> [public|private] / help module <module>" self.send(target, s) elif args[0] == 'module': args.pop(0) if not args: self.send(target, "usage: help module <module>") else: help_item = index['modules'].get(args[0]) if help_item: self.send(target, help_item['summary']) else: self.send(target, _("No help for %s"), args[0]) else: args.append("") cmd = args.pop(0) cmd_type = args.pop(0) if 'pu' in cmd_type or self.target.startswith('#'): cmd_type = 'public' elif 'pr' in cmd_type or not self.target.startswith('#'): cmd_type = 'private' else: # we shouldn't be here self.logger.error("cmd_list") return help_item = index[cmd_type].get(cmd) if help_item: self.send(target, index[cmd_type][cmd]['summary']) else: self.send(target, _("No help for %s"), cmd) class HelpModule(BaseModule): context_class = HelpContext module = HelpModule <|fim▁end|>
"""List commands""" arg = argument.lower() index = self.bot.help_index public = "public commands -- %s" % " ".join(index['public']) private = "private commands -- %s" % " ".join(index['private']) if 'all' in arg or 'both' in arg: output = "\n".join((public, private)) elif 'pub' in arg or self.target.startswith('#'): output = public elif 'priv' in arg or not self.target.startswith('#'): output = private else: # we shouldn't be here self.logger.error("cmd_list") return self.send(self.target, output)
<|file_name|>help.py<|end_file_name|><|fim▁begin|># Author: Nick Raptis <[email protected]> """ Module for listing commands and help. """ from basemodule import BaseModule, BaseCommandContext from alternatives import _ class HelpContext(BaseCommandContext): def cmd_list(self, argument): """List commands""" arg = argument.lower() index = self.bot.help_index public = "public commands -- %s" % " ".join(index['public']) private = "private commands -- %s" % " ".join(index['private']) if 'all' in arg or 'both' in arg: output = "\n".join((public, private)) elif 'pub' in arg or self.target.startswith('#'): output = public elif 'priv' in arg or not self.target.startswith('#'): output = private else: # we shouldn't be here self.logger.error("cmd_list") return self.send(self.target, output) def cmd_modules(self, argument): <|fim_middle|> def cmd_help(self, argument): """Get help on a command or module""" arg = argument.lower() index = self.bot.help_index target = self.target args = arg.split() if not args: s = "usage: help <command> [public|private] / help module <module>" self.send(target, s) elif args[0] == 'module': args.pop(0) if not args: self.send(target, "usage: help module <module>") else: help_item = index['modules'].get(args[0]) if help_item: self.send(target, help_item['summary']) else: self.send(target, _("No help for %s"), args[0]) else: args.append("") cmd = args.pop(0) cmd_type = args.pop(0) if 'pu' in cmd_type or self.target.startswith('#'): cmd_type = 'public' elif 'pr' in cmd_type or not self.target.startswith('#'): cmd_type = 'private' else: # we shouldn't be here self.logger.error("cmd_list") return help_item = index[cmd_type].get(cmd) if help_item: self.send(target, index[cmd_type][cmd]['summary']) else: self.send(target, _("No help for %s"), cmd) class HelpModule(BaseModule): context_class = HelpContext module = HelpModule <|fim▁end|>
"""List active modules""" index = self.bot.help_index output = "active modules -- %s" % " ".join(index['modules'].keys()) self.send(self.target, output)
<|file_name|>help.py<|end_file_name|><|fim▁begin|># Author: Nick Raptis <[email protected]> """ Module for listing commands and help. """ from basemodule import BaseModule, BaseCommandContext from alternatives import _ class HelpContext(BaseCommandContext): def cmd_list(self, argument): """List commands""" arg = argument.lower() index = self.bot.help_index public = "public commands -- %s" % " ".join(index['public']) private = "private commands -- %s" % " ".join(index['private']) if 'all' in arg or 'both' in arg: output = "\n".join((public, private)) elif 'pub' in arg or self.target.startswith('#'): output = public elif 'priv' in arg or not self.target.startswith('#'): output = private else: # we shouldn't be here self.logger.error("cmd_list") return self.send(self.target, output) def cmd_modules(self, argument): """List active modules""" index = self.bot.help_index output = "active modules -- %s" % " ".join(index['modules'].keys()) self.send(self.target, output) def cmd_help(self, argument): <|fim_middle|> class HelpModule(BaseModule): context_class = HelpContext module = HelpModule <|fim▁end|>
"""Get help on a command or module""" arg = argument.lower() index = self.bot.help_index target = self.target args = arg.split() if not args: s = "usage: help <command> [public|private] / help module <module>" self.send(target, s) elif args[0] == 'module': args.pop(0) if not args: self.send(target, "usage: help module <module>") else: help_item = index['modules'].get(args[0]) if help_item: self.send(target, help_item['summary']) else: self.send(target, _("No help for %s"), args[0]) else: args.append("") cmd = args.pop(0) cmd_type = args.pop(0) if 'pu' in cmd_type or self.target.startswith('#'): cmd_type = 'public' elif 'pr' in cmd_type or not self.target.startswith('#'): cmd_type = 'private' else: # we shouldn't be here self.logger.error("cmd_list") return help_item = index[cmd_type].get(cmd) if help_item: self.send(target, index[cmd_type][cmd]['summary']) else: self.send(target, _("No help for %s"), cmd)
<|file_name|>help.py<|end_file_name|><|fim▁begin|># Author: Nick Raptis <[email protected]> """ Module for listing commands and help. """ from basemodule import BaseModule, BaseCommandContext from alternatives import _ class HelpContext(BaseCommandContext): def cmd_list(self, argument): """List commands""" arg = argument.lower() index = self.bot.help_index public = "public commands -- %s" % " ".join(index['public']) private = "private commands -- %s" % " ".join(index['private']) if 'all' in arg or 'both' in arg: output = "\n".join((public, private)) elif 'pub' in arg or self.target.startswith('#'): output = public elif 'priv' in arg or not self.target.startswith('#'): output = private else: # we shouldn't be here self.logger.error("cmd_list") return self.send(self.target, output) def cmd_modules(self, argument): """List active modules""" index = self.bot.help_index output = "active modules -- %s" % " ".join(index['modules'].keys()) self.send(self.target, output) def cmd_help(self, argument): """Get help on a command or module""" arg = argument.lower() index = self.bot.help_index target = self.target args = arg.split() if not args: s = "usage: help <command> [public|private] / help module <module>" self.send(target, s) elif args[0] == 'module': args.pop(0) if not args: self.send(target, "usage: help module <module>") else: help_item = index['modules'].get(args[0]) if help_item: self.send(target, help_item['summary']) else: self.send(target, _("No help for %s"), args[0]) else: args.append("") cmd = args.pop(0) cmd_type = args.pop(0) if 'pu' in cmd_type or self.target.startswith('#'): cmd_type = 'public' elif 'pr' in cmd_type or not self.target.startswith('#'): cmd_type = 'private' else: # we shouldn't be here self.logger.error("cmd_list") return help_item = index[cmd_type].get(cmd) if help_item: self.send(target, index[cmd_type][cmd]['summary']) else: self.send(target, _("No help for %s"), cmd) class HelpModule(BaseModule): <|fim_middle|> module = HelpModule <|fim▁end|>
context_class = HelpContext
<|file_name|>help.py<|end_file_name|><|fim▁begin|># Author: Nick Raptis <[email protected]> """ Module for listing commands and help. """ from basemodule import BaseModule, BaseCommandContext from alternatives import _ class HelpContext(BaseCommandContext): def cmd_list(self, argument): """List commands""" arg = argument.lower() index = self.bot.help_index public = "public commands -- %s" % " ".join(index['public']) private = "private commands -- %s" % " ".join(index['private']) if 'all' in arg or 'both' in arg: <|fim_middle|> elif 'pub' in arg or self.target.startswith('#'): output = public elif 'priv' in arg or not self.target.startswith('#'): output = private else: # we shouldn't be here self.logger.error("cmd_list") return self.send(self.target, output) def cmd_modules(self, argument): """List active modules""" index = self.bot.help_index output = "active modules -- %s" % " ".join(index['modules'].keys()) self.send(self.target, output) def cmd_help(self, argument): """Get help on a command or module""" arg = argument.lower() index = self.bot.help_index target = self.target args = arg.split() if not args: s = "usage: help <command> [public|private] / help module <module>" self.send(target, s) elif args[0] == 'module': args.pop(0) if not args: self.send(target, "usage: help module <module>") else: help_item = index['modules'].get(args[0]) if help_item: self.send(target, help_item['summary']) else: self.send(target, _("No help for %s"), args[0]) else: args.append("") cmd = args.pop(0) cmd_type = args.pop(0) if 'pu' in cmd_type or self.target.startswith('#'): cmd_type = 'public' elif 'pr' in cmd_type or not self.target.startswith('#'): cmd_type = 'private' else: # we shouldn't be here self.logger.error("cmd_list") return help_item = index[cmd_type].get(cmd) if help_item: self.send(target, index[cmd_type][cmd]['summary']) else: self.send(target, _("No help for %s"), cmd) class HelpModule(BaseModule): context_class = HelpContext module = HelpModule <|fim▁end|>
output = "\n".join((public, private))
<|file_name|>help.py<|end_file_name|><|fim▁begin|># Author: Nick Raptis <[email protected]> """ Module for listing commands and help. """ from basemodule import BaseModule, BaseCommandContext from alternatives import _ class HelpContext(BaseCommandContext): def cmd_list(self, argument): """List commands""" arg = argument.lower() index = self.bot.help_index public = "public commands -- %s" % " ".join(index['public']) private = "private commands -- %s" % " ".join(index['private']) if 'all' in arg or 'both' in arg: output = "\n".join((public, private)) elif 'pub' in arg or self.target.startswith('#'): <|fim_middle|> elif 'priv' in arg or not self.target.startswith('#'): output = private else: # we shouldn't be here self.logger.error("cmd_list") return self.send(self.target, output) def cmd_modules(self, argument): """List active modules""" index = self.bot.help_index output = "active modules -- %s" % " ".join(index['modules'].keys()) self.send(self.target, output) def cmd_help(self, argument): """Get help on a command or module""" arg = argument.lower() index = self.bot.help_index target = self.target args = arg.split() if not args: s = "usage: help <command> [public|private] / help module <module>" self.send(target, s) elif args[0] == 'module': args.pop(0) if not args: self.send(target, "usage: help module <module>") else: help_item = index['modules'].get(args[0]) if help_item: self.send(target, help_item['summary']) else: self.send(target, _("No help for %s"), args[0]) else: args.append("") cmd = args.pop(0) cmd_type = args.pop(0) if 'pu' in cmd_type or self.target.startswith('#'): cmd_type = 'public' elif 'pr' in cmd_type or not self.target.startswith('#'): cmd_type = 'private' else: # we shouldn't be here self.logger.error("cmd_list") return help_item = index[cmd_type].get(cmd) if help_item: self.send(target, index[cmd_type][cmd]['summary']) else: self.send(target, _("No help for %s"), cmd) class HelpModule(BaseModule): context_class = HelpContext module = HelpModule <|fim▁end|>
output = public
<|file_name|>help.py<|end_file_name|><|fim▁begin|># Author: Nick Raptis <[email protected]> """ Module for listing commands and help. """ from basemodule import BaseModule, BaseCommandContext from alternatives import _ class HelpContext(BaseCommandContext): def cmd_list(self, argument): """List commands""" arg = argument.lower() index = self.bot.help_index public = "public commands -- %s" % " ".join(index['public']) private = "private commands -- %s" % " ".join(index['private']) if 'all' in arg or 'both' in arg: output = "\n".join((public, private)) elif 'pub' in arg or self.target.startswith('#'): output = public elif 'priv' in arg or not self.target.startswith('#'): <|fim_middle|> else: # we shouldn't be here self.logger.error("cmd_list") return self.send(self.target, output) def cmd_modules(self, argument): """List active modules""" index = self.bot.help_index output = "active modules -- %s" % " ".join(index['modules'].keys()) self.send(self.target, output) def cmd_help(self, argument): """Get help on a command or module""" arg = argument.lower() index = self.bot.help_index target = self.target args = arg.split() if not args: s = "usage: help <command> [public|private] / help module <module>" self.send(target, s) elif args[0] == 'module': args.pop(0) if not args: self.send(target, "usage: help module <module>") else: help_item = index['modules'].get(args[0]) if help_item: self.send(target, help_item['summary']) else: self.send(target, _("No help for %s"), args[0]) else: args.append("") cmd = args.pop(0) cmd_type = args.pop(0) if 'pu' in cmd_type or self.target.startswith('#'): cmd_type = 'public' elif 'pr' in cmd_type or not self.target.startswith('#'): cmd_type = 'private' else: # we shouldn't be here self.logger.error("cmd_list") return help_item = index[cmd_type].get(cmd) if help_item: self.send(target, index[cmd_type][cmd]['summary']) else: self.send(target, _("No help for %s"), cmd) class HelpModule(BaseModule): context_class = HelpContext module = HelpModule <|fim▁end|>
output = private
<|file_name|>help.py<|end_file_name|><|fim▁begin|># Author: Nick Raptis <[email protected]> """ Module for listing commands and help. """ from basemodule import BaseModule, BaseCommandContext from alternatives import _ class HelpContext(BaseCommandContext): def cmd_list(self, argument): """List commands""" arg = argument.lower() index = self.bot.help_index public = "public commands -- %s" % " ".join(index['public']) private = "private commands -- %s" % " ".join(index['private']) if 'all' in arg or 'both' in arg: output = "\n".join((public, private)) elif 'pub' in arg or self.target.startswith('#'): output = public elif 'priv' in arg or not self.target.startswith('#'): output = private else: # we shouldn't be here <|fim_middle|> self.send(self.target, output) def cmd_modules(self, argument): """List active modules""" index = self.bot.help_index output = "active modules -- %s" % " ".join(index['modules'].keys()) self.send(self.target, output) def cmd_help(self, argument): """Get help on a command or module""" arg = argument.lower() index = self.bot.help_index target = self.target args = arg.split() if not args: s = "usage: help <command> [public|private] / help module <module>" self.send(target, s) elif args[0] == 'module': args.pop(0) if not args: self.send(target, "usage: help module <module>") else: help_item = index['modules'].get(args[0]) if help_item: self.send(target, help_item['summary']) else: self.send(target, _("No help for %s"), args[0]) else: args.append("") cmd = args.pop(0) cmd_type = args.pop(0) if 'pu' in cmd_type or self.target.startswith('#'): cmd_type = 'public' elif 'pr' in cmd_type or not self.target.startswith('#'): cmd_type = 'private' else: # we shouldn't be here self.logger.error("cmd_list") return help_item = index[cmd_type].get(cmd) if help_item: self.send(target, index[cmd_type][cmd]['summary']) else: self.send(target, _("No help for %s"), cmd) class HelpModule(BaseModule): context_class = HelpContext module = HelpModule <|fim▁end|>
self.logger.error("cmd_list") return