function
stringlengths 11
56k
| repo_name
stringlengths 5
60
| features
sequence |
---|---|---|
def testSourceApplyMacros2(self):
"""
Test applymacros
"""
recipestr1 = """ | sassoftware/conary | [
47,
9,
47,
4,
1396904066
] |
def cleanup(r, builddir, destdir):
pass | sassoftware/conary | [
47,
9,
47,
4,
1396904066
] |
def setup(r):
# avoid cleanup
r.macros.sourcemacros = 'source-apply-macros'
r.addSource('myfile', contents="%(sourcemacros)s %(destdir)s",
macros=True)
r.macros.a = 'XXX'
r.macros.b = 'YYY'
r.macros.c = 'ZZZ'
r.addSource('sourcefile', macros=True, mode=0676) | sassoftware/conary | [
47,
9,
47,
4,
1396904066
] |
def testPatchFilter(self):
recipestr = """ | sassoftware/conary | [
47,
9,
47,
4,
1396904066
] |
def setup(r):
# avoid cleanup
r.addSource('unpatched1')
r.addSource('unpatched2')
r.addPatch('patchToFilter.patch') | sassoftware/conary | [
47,
9,
47,
4,
1396904066
] |
def setup(r):
# avoid cleanup
r.addSource('unpatched1')
r.addSource('unpatched2')
r.addPatch('patchToFilter.patch', filter='sed s/Oops// |cat | cat') | sassoftware/conary | [
47,
9,
47,
4,
1396904066
] |
def testAction(self):
recipestr1 = """ | sassoftware/conary | [
47,
9,
47,
4,
1396904066
] |
def cleanup(r, builddir, destdir):
pass | sassoftware/conary | [
47,
9,
47,
4,
1396904066
] |
def findInFile(self, filename, key):
f = open(filename)
contents = f.read()
return contents.find(key) | sassoftware/conary | [
47,
9,
47,
4,
1396904066
] |
def setup(r):
r.addSource('dc_client.init', rpm='distcache-1.4.5-2.src.rpm')
r.Run('test -x dc_client.init')
# get rid of "cowardlily refusing" message
r.Create('/foo') | sassoftware/conary | [
47,
9,
47,
4,
1396904066
] |
def testAutoMainDir(self):
"""
Test mainDir automagic guessing.
"""
recipestr1 = """ | sassoftware/conary | [
47,
9,
47,
4,
1396904066
] |
def setup(r):
# asdf.tar.gz contains asdf/fdsa and bam, not test-1/fdsa
r.addArchive('asdf.tar.gz')
# the next line will only work if mainDir was auto-set to asdf
r.Install('fdsa', '/') | sassoftware/conary | [
47,
9,
47,
4,
1396904066
] |
def setup(r):
# asdf.tar.gz contains asdf/fdsa and bam, not test-1/fdsa
r.addArchive('asdf.tar.gz', dir='blah')
# the next line will only work if mainDir was auto-set to blah
r.Install('asdf/fdsa', '/') | sassoftware/conary | [
47,
9,
47,
4,
1396904066
] |
def setup(r):
# foo-1.0.tar.gz has foo-1.0/a and blah/b
r.addArchive('foo-1.0.tar.gz')
r.Install('a', '/') | sassoftware/conary | [
47,
9,
47,
4,
1396904066
] |
def setup(r):
# foo-1.0.tar.gz has foo-1.0/a and blah/b
r.addArchive('foo-1.0&;.tar.gz')
r.Install('a', '/') | sassoftware/conary | [
47,
9,
47,
4,
1396904066
] |
def testAutoMainDirGuessFailure(self):
recipestr = """ | sassoftware/conary | [
47,
9,
47,
4,
1396904066
] |
def setup(r):
# foo-1.0.tar.gz has foo-1.0/a and blah/b
r.addSource('macros')
r.addArchive('distcc-2.9.tar.bz2') | sassoftware/conary | [
47,
9,
47,
4,
1396904066
] |
def testSourceMagic(self):
d = tempfile.mkdtemp()
try:
# copy setup.tar.gz to a file without .gz extension
shutil.copyfile(resources.get_archive() + '/asdf.tar.gz',
d + '/asdf')
# look in our new source directory for sources
self.cfg.sourceSearchDir = d
r = policytest.DummyRecipe(self.cfg)
# test the Archive class when the archive does not end in .gz
os.mkdir('/'.join((r.macros.builddir, r.theMainDir)))
a = source.Archive(r, 'asdf')
a.doAction()
assert(os.path.isdir(r.macros.builddir + '/asdf'))
assert(os.path.isfile(r.macros.builddir + '/asdf/fdsa'))
finally:
shutil.rmtree(d) | sassoftware/conary | [
47,
9,
47,
4,
1396904066
] |
def setup(r):
r.addArchive('tmpwatch-2.9.0.tar.gz', rpm='tmpwatch-2.9.0-2.src.rpm')
r.addPatch('unrelated.patch') | sassoftware/conary | [
47,
9,
47,
4,
1396904066
] |
def testAddGoodPatch(self):
recipestr1 = """\ | sassoftware/conary | [
47,
9,
47,
4,
1396904066
] |
def setup(r):
r.addArchive('tmpwatch-2.9.0.tar.gz', rpm='tmpwatch-2.9.0-2.src.rpm')
r.addPatch('tmpwatch.fakebug.patch') | sassoftware/conary | [
47,
9,
47,
4,
1396904066
] |
def testAddGoodLevel0Patch(self):
recipestr1 = """\ | sassoftware/conary | [
47,
9,
47,
4,
1396904066
] |
def setup(r):
r.addArchive('tmpwatch-2.9.0.tar.gz', rpm='tmpwatch-2.9.0-2.src.rpm')
r.addPatch('tmpwatch.fakebug.level0.patch') | sassoftware/conary | [
47,
9,
47,
4,
1396904066
] |
def testAddGoodButRejectedPatch(self):
recipestr1 = """\ | sassoftware/conary | [
47,
9,
47,
4,
1396904066
] |
def setup(r):
r.addArchive('tmpwatch-2.9.0.tar.gz', rpm='tmpwatch-2.9.0-2.src.rpm')
r.addPatch('tmpwatch.fakebug.rej.patch') | sassoftware/conary | [
47,
9,
47,
4,
1396904066
] |
def testAddPartiallyApplicablePatch(self):
# patch partially applies at level one and completely
# applies at level 2.
recipestr1 = """\ | sassoftware/conary | [
47,
9,
47,
4,
1396904066
] |
def setup(r):
contents = '\\n'.join(str(x) for x in range(1, 21)) + '\\n'
r.addSource('foo', contents=contents)
r.addSource('bar', contents=contents)
r.addAction('mkdir subdir; cp foo subdir/; touch subdir/bar')
r.addPatch('partial.patch') | sassoftware/conary | [
47,
9,
47,
4,
1396904066
] |
def testPatchSameFileTwiceInOnePatch(self):
# CNY-2142
recipestr1 = """\ | sassoftware/conary | [
47,
9,
47,
4,
1396904066
] |
def setup(r):
contents = '\\n'.join(str(x) for x in range(1, 11)) + '\\n'
r.addSource('foo', contents=contents)
r.addPatch('patches/foo.patch') | sassoftware/conary | [
47,
9,
47,
4,
1396904066
] |
def testLargePatch(self):
# Test a patch that's large enough to cause our patch pipe
# to be full - this "patch" would hang if we didn't have good
# pipe handling. Done correctly, it just fails.
recipestr1 = """\ | sassoftware/conary | [
47,
9,
47,
4,
1396904066
] |
def setup(r):
r.addArchive('tmpwatch-2.9.0.tar.gz', rpm = 'tmpwatch-2.9.0-2.src.rpm')
r.addPatch('tmpwatch-2.9.0.tar.gz', rpm = 'tmpwatch-2.9.0-2.src.rpm') | sassoftware/conary | [
47,
9,
47,
4,
1396904066
] |
def testMissingPatchProgram(self):
recipestr = """\ | sassoftware/conary | [
47,
9,
47,
4,
1396904066
] |
def setup(r):
r.addPatch('tmpwatch.fakebug.patch', patchName='noSuchPatchProgram') | sassoftware/conary | [
47,
9,
47,
4,
1396904066
] |
def testTarPermissions(self):
r = policytest.DummyRecipe(self.cfg)
os.mkdir('/'.join((r.macros.builddir, r.theMainDir)))
# add an archive that has a file with group write permissions
a = source.Archive(r, 'group-write.tar.gz', dir='/')
a.doAction()
sb = os.stat(r.macros.destdir + '/foo/foo')
# make sure that the group write bit is set
assert(sb.st_mode & stat.S_IWGRP) | sassoftware/conary | [
47,
9,
47,
4,
1396904066
] |
def testBzipDeb(self):
r = policytest.DummyRecipe(self.cfg)
os.mkdir('/'.join((r.macros.builddir, r.theMainDir)))
# add an archive that has a file with group write permissions
a = source.Archive(r, 'test.deb', dir='/')
a.doAction()
self.assertTrue(os.path.isfile(r.macros.destdir + '/testme')) | sassoftware/conary | [
47,
9,
47,
4,
1396904066
] |
def testLZMADeb(self):
r = policytest.DummyRecipe(self.cfg)
os.mkdir('/'.join((r.macros.builddir, r.theMainDir)))
a = source.Archive(r, 'testlzma.deb', dir='/')
a.doAction()
self.assertTrue(os.path.isfile(r.macros.destdir + '/testme')) | sassoftware/conary | [
47,
9,
47,
4,
1396904066
] |
def testEmptyDeb(self):
r = policytest.DummyRecipe(self.cfg)
os.mkdir('/'.join((r.macros.builddir, r.theMainDir)))
# add an archive that has a file with group write permissions
a = source.Archive(r, 'testempty.deb', dir='/')
self.assertRaises(source.SourceError, a.doAction) | sassoftware/conary | [
47,
9,
47,
4,
1396904066
] |
def setup(r):
r.addArchive('allperms.tar', dir = '/tar',
preserveOwnership = True,
preserveSetid = True,
preserveDirectories = True)
r.ExcludeDirectories(exceptions = [ '.*/foo' ] ) | sassoftware/conary | [
47,
9,
47,
4,
1396904066
] |
def testOwnershipRetention(self):
recipestr = """ | sassoftware/conary | [
47,
9,
47,
4,
1396904066
] |
def setup(r):
r.addArchive('ownerships.tar', dir = '/tar',
preserveOwnership = True) | sassoftware/conary | [
47,
9,
47,
4,
1396904066
] |
def setup(r):
r.addArchive('ownerships.tar', preserveOwnership = True) | sassoftware/conary | [
47,
9,
47,
4,
1396904066
] |
def setup(r):
r.addArchive('rrcd.iso', preserveOwnership = True, dir = '/') | sassoftware/conary | [
47,
9,
47,
4,
1396904066
] |
def setup(r):
r.addArchive('ownerships.zip', preserveOwnership = True, dir = '/') | sassoftware/conary | [
47,
9,
47,
4,
1396904066
] |
def testSourceLzop(self):
recipestr = """ | sassoftware/conary | [
47,
9,
47,
4,
1396904066
] |
def setup(r):
r.addArchive('foo.tar.lzo', dir='/') | sassoftware/conary | [
47,
9,
47,
4,
1396904066
] |
def testBadaddSource(self):
recipestr=""" | sassoftware/conary | [
47,
9,
47,
4,
1396904066
] |
def setup(r):
r.addSource('http://foo.bar.com/directory/', dest='/mumble/') | sassoftware/conary | [
47,
9,
47,
4,
1396904066
] |
def testAddSourceDir(self):
recipeStr = """ | sassoftware/conary | [
47,
9,
47,
4,
1396904066
] |
def setup(r):
r.addSource('test', sourceDir = '')"""
class Stop(Exception):
pass
def mockDoDownload(x):
f = x._findSource(x.httpHeaders)
self.assertEquals(f, os.path.join(x.builddir,
x.recipe.macros.maindir,
'test'))
raise Stop
def mockFindAll(*args, **kwargs):
raise AssertionError('lookaside cache should not have been used')
self.mock(source.addSource, 'doDownload', mockDoDownload)
self.mock(lookaside, 'findAll', mockFindAll)
self.assertRaises(Stop, self.buildRecipe,
recipeStr, "TestAddSourceDir") | sassoftware/conary | [
47,
9,
47,
4,
1396904066
] |
def setup(r):
r.addArchive('tmpwatch-2.9.0.tar.gz', rpm='tmpwatch-2.9.0-2.src.rpm')
r.addSource('mkinitrd.spec', rpm='rpm-with-bzip-5.0.29-1.src.rpm')
r.addArchive('rpm-with-bzip-5.0.29-1.i386.rpm')
# add patch file so it exists in builddir
r.addArchive('tmpwatch.fakebug.patch.tgz', dir = '%(maindir)s')
# test applying a patch using sourceDir
r.addPatch('tmpwatch.fakebug.patch', sourceDir='')"""
# this line will fail if the patch cannot be added
self.buildRecipe(recipestr, "TestSource") | sassoftware/conary | [
47,
9,
47,
4,
1396904066
] |
def setup(r):
r.addArchive('tmpwatch-2.9.0.tar.gz', rpm='tmpwatch-2.9.0-2.src.rpm')
r.addSource('mkinitrd.spec', rpm='rpm-with-bzip-5.0.29-1.src.rpm')
r.addArchive('rpm-with-bzip-5.0.29-1.i386.rpm')
# add patch file so it exists in builddir
r.addArchive('tmpwatch.fakebug.patch.tgz', dir = '%(maindir)s')
# test applying a patch using globs and sourceDir
r.addPatch('tmpwatch.fakebug.*', sourceDir='')"""
# this line will fail if the patch cannot be added
self.buildRecipe(recipestr, "TestSource") | sassoftware/conary | [
47,
9,
47,
4,
1396904066
] |
def setup(r):
# test applying a patch using globs without sourceDir. this will fail
r.addPatch('tmpwatch.fakebug.*')"""
# globs for addPatch are only used if soruceDir is defined.
try:
self.buildRecipe(recipestr, "TestSource")
except OSError, e:
if e.errno != 2:
raise
self.assertEquals(str(e),
"[Errno 2] No such file or directory: 'tmpwatch.fakebug.*'")
else:
self.fail("addPatch on bad filename should have failed") | sassoftware/conary | [
47,
9,
47,
4,
1396904066
] |
def __init__(x):
pass | sassoftware/conary | [
47,
9,
47,
4,
1396904066
] |
def doFile(x, path):
self.orderedCalls.append(path) | sassoftware/conary | [
47,
9,
47,
4,
1396904066
] |
def _getHTTPServer(self, logFile):
class FileHandler(SimpleHTTPServer.SimpleHTTPRequestHandler):
count = 0
def log_message(slf, *args, **kw):
file(logFile, "a").write("%s\n" % slf.path)
def do_GET(slf):
if slf.path.endswith('/count'):
contentType = 'text/plain'
archpath = self.workDir + '/count'
FileHandler.count += 1
open(archpath, 'w').write('%s\n' % slf.count)
elif (slf.path.startswith("/bad/") or
not slf.path.endswith('.tar.gz')):
#if (slf.path.startswith("/bad/") or
# not (slf.path.endswith('.tar.gz') or
# slf.path.endswith('.tar.gz.asc'))):
slf.send_response(404)
slf.end_headers()
return
elif slf.path.endswith('.tar.gz'):
archpath = os.path.join(resources.get_archive(), "foo-1.0.tar.gz")
contentType = "application/x-gzip"
else:
archpath = os.path.join(self.workDir, "foo.asc")
file(archpath, "w+").write("Pretend this is a PGP sig")
contentType = 'application/pgp-signature'
fileSize = os.stat(archpath).st_size
slf.send_response(200)
slf.send_header("Content-Type", contentType)
slf.send_header("Content-Length", fileSize)
slf.end_headers()
util.copyStream(open(archpath), slf.wfile)
hs = rephelp.HTTPServerController(FileHandler)
return hs | sassoftware/conary | [
47,
9,
47,
4,
1396904066
] |
def setup(r):
r.addArchive([
"http://localhost:%(port)s/bad/",
"http://localhost:%(port)s/good/",
], dir="/usr/share/foo/") | sassoftware/conary | [
47,
9,
47,
4,
1396904066
] |
def setup(r):
r.addSource([
"http://localhost:%(port)s/bad/foo-1.99.tar.gz",
"http://localhost:%(port)s/good/",
], dir="/usr/share/foo/") | sassoftware/conary | [
47,
9,
47,
4,
1396904066
] |
def testAddArchivePassword(self):
recipestr = """ | sassoftware/conary | [
47,
9,
47,
4,
1396904066
] |
def setup(r):
r.addSource("http://foo:bar@localhost:%(port)s/good/count",
dest='/foo') | sassoftware/conary | [
47,
9,
47,
4,
1396904066
] |
def testMultiURLMirror(self):
recipestr = """ | sassoftware/conary | [
47,
9,
47,
4,
1396904066
] |
def setup(r):
r.addArchive([
"mirror://alif/%(rest)s",
"mirror://ba/%(rest)s",
], dir="/usr/share/foo/") | sassoftware/conary | [
47,
9,
47,
4,
1396904066
] |
def testMirrorLookaside(self):
# CNY-2696
# There was a bug in the way the mirror name was computed
recipestr = """ | sassoftware/conary | [
47,
9,
47,
4,
1396904066
] |
def setup(r):
r.addArchive("mirror://alif/blah/", keyid = 'DEADBEEF',
dir="/usr/share/foo/") | sassoftware/conary | [
47,
9,
47,
4,
1396904066
] |
def testRpmLookaside(self):
recipeStr = """ | sassoftware/conary | [
47,
9,
47,
4,
1396904066
] |
def setup(r):
# prove that the sourcedir level foo isn't even looked up if rpm is
# specified
r.addArchive('foo-1.0-1.src.rpm')
r.addSource('foo', dir = '/bar', rpm = 'foo-1.0-1.src.rpm') | sassoftware/conary | [
47,
9,
47,
4,
1396904066
] |
def testRpmLookaside2(self):
recipeStr = """ | sassoftware/conary | [
47,
9,
47,
4,
1396904066
] |
def setup(r):
# now prove that both can be used at the same time
r.addArchive('foo-1.0-1.src.rpm')
# add the sorucedir foo first to "poison" the lookaside
r.addSource('foo', dir = '/baz')
r.addSource('foo', dir = '/bar', rpm = 'foo-1.0-1.src.rpm') | sassoftware/conary | [
47,
9,
47,
4,
1396904066
] |
def testRpmLookaside3(self):
recipeStr = """ | sassoftware/conary | [
47,
9,
47,
4,
1396904066
] |
def setup(r):
# now prove that two rpm's can have distinct contents at once
r.addArchive('foo-1.0-1.src.rpm')
r.addArchive('foo-1.0-2.src.rpm')
r.addSource('foo.spec', dir = '/1', rpm = 'foo-1.0-1.src.rpm')
r.addSource('foo.spec', dir = '/2', rpm = 'foo-1.0-2.src.rpm') | sassoftware/conary | [
47,
9,
47,
4,
1396904066
] |
def testRpmLookaside4(self):
recipeStr = """ | sassoftware/conary | [
47,
9,
47,
4,
1396904066
] |
def setup(r):
# ensure missing files within the rpm respond sensibly
r.addArchive('foo-1.0-1.src.rpm')
r.addSource('notfound', dir = '/bar', rpm = 'foo-1.0-1.src.rpm') | sassoftware/conary | [
47,
9,
47,
4,
1396904066
] |
def testRepositoryCookNoDownload(self):
# CNY-3221, RMK-995
# We want to make sure that repositoy cooks don't re-download the
# content (nor do they try to download wrong guesses)
recipestr = """ | sassoftware/conary | [
47,
9,
47,
4,
1396904066
] |
def setup(r):
# ensure missing files within the rpm respond sensibly
r.addArchive('http://localhost:%(port)s/good/', dir = "/usr") | sassoftware/conary | [
47,
9,
47,
4,
1396904066
] |
def test_extractFilesFromXzRPM(self):
if not os.path.exists('/usr/bin/xz'):
raise testhelp.SkipTestException('The /usr/bin/xz binary is required to run this test')
recipestr = """ | sassoftware/conary | [
47,
9,
47,
4,
1396904066
] |
def setup(r):
# ensure missing files within the rpm respond sensibly
r.addArchive('popt-1.13-6.fc12.i686.rpm', dir = '/') | sassoftware/conary | [
47,
9,
47,
4,
1396904066
] |
def process(self, response):
soup = bs(response.m_response.content, 'lxml')
province_div_list = soup.select('div.city-list div.cap-city > div.fn-clear')
for province_div in province_div_list:
province_name = province_div.select('span.capital a')[0].text
city_list = province_div.select('div.city a')
for city in city_list:
city_name = city.text
pinyin = city['href'].strip('/').split('/')[0]
request = Request(
url='http://www.che168.com/handler/usedcarlistv5.ashx?action=brandlist&area=%s' % pinyin,
priority=1, callback=self.process_page_1)
request.meta['province'] = province_name
request.meta['city'] = city_name
yield request | DarkSand/Sasila | [
294,
75,
294,
2,
1484044688
] |
def process_page_1(self, response):
brand_list = list(json.loads(response.m_response.content.decode('gb2312')))
for brand in brand_list:
brand_dict = dict(brand)
brand_name = brand_dict['name']
url = response.nice_join(brand_dict['url']) + '/'
request = Request(url=url, priority=2, callback=self.process_page_2)
request.meta['province'] = response.request.meta['province']
request.meta['city'] = response.request.meta['city']
request.meta['brand'] = brand_name
yield request | DarkSand/Sasila | [
294,
75,
294,
2,
1484044688
] |
def process_page_2(self, response):
soup = bs(response.m_response.content, 'lxml')
cars_line_list = soup.select('div#series div.content-area dl.model-list dd a')
for cars_line in cars_line_list:
cars_line_name = cars_line.text
url = 'http://www.che168.com' + cars_line['href']
request = Request(url=url, priority=3, callback=self.process_page_3)
request.meta['province'] = response.request.meta['province']
request.meta['city'] = response.request.meta['city']
request.meta['brand'] = response.request.meta['brand']
request.meta['cars_line'] = cars_line_name
yield request | DarkSand/Sasila | [
294,
75,
294,
2,
1484044688
] |
def process_page_3(self, response):
soup = bs(response.m_response.content, 'lxml')
car_info_list = soup.select('div#a2 ul#viewlist_ul li a.carinfo')
for car_info in car_info_list:
url = 'http://www.che168.com' + car_info['href']
request = Request(url=url, priority=4, callback=self.process_page_4)
request.meta['province'] = response.request.meta['province']
request.meta['city'] = response.request.meta['city']
request.meta['brand'] = response.request.meta['brand']
request.meta['cars_line'] = response.request.meta['cars_line']
yield request
next_page = soup.find(lambda tag: tag.name == 'a' and '下一页' in tag.text)
if next_page:
url = 'http://www.che168.com' + next_page['href']
request = Request(url=url, priority=3, callback=self.process_page_3)
request.meta['province'] = response.request.meta['province']
request.meta['city'] = response.request.meta['city']
request.meta['brand'] = response.request.meta['brand']
request.meta['cars_line'] = response.request.meta['cars_line']
yield request | DarkSand/Sasila | [
294,
75,
294,
2,
1484044688
] |
def process_page_4(self, response):
soup = bs(response.m_response.content, 'lxml')
# <html><head><title>Object moved</title></head><body>
# <h2>Object moved to <a href="/CarDetail/wrong.aspx?errorcode=5&backurl=/&infoid=21415515">here</a>.</h2>
# </body></html>
if len(soup.select('div.car-title h2')) != 0:
car = soup.select('div.car-title h2')[0].text
detail_list = soup.select('div.details li')
if len(detail_list) == 0:
soup = bs(response.m_response.content, 'html5lib')
detail_list = soup.select('div.details li')
mileage = detail_list[0].select('span')[0].text.replace('万公里', '')
first_borad_date = detail_list[1].select('span')[0].text
gear = detail_list[2].select('span')[0].text.split('/')[0]
displacement = detail_list[2].select('span')[0].text.split('/')[1]
price = soup.select('div.car-price ins')[0].text.replace('¥', '')
crawl_date = time.strftime('%Y-%m-%d', time.localtime(time.time()))
item = dict()
item['car'] = car
item['mileage'] = mileage
item['first_borad_date'] = first_borad_date
item['gear'] = gear
item['displacement'] = displacement
item['price'] = price
item['crawl_date'] = crawl_date
item['province'] = response.request.meta['province']
item['city'] = response.request.meta['city']
item['brand'] = response.request.meta['brand']
item['cars_line'] = response.request.meta['cars_line']
yield item | DarkSand/Sasila | [
294,
75,
294,
2,
1484044688
] |
def __init__(self, handler, request, protocols):
self._handler = handler
self._deferred = None
self.device_id = request.id
self._name = request.name
self._url = request.url
self._crc = request.crc
self._version = request.image_version
self._local = request.local_dir
self._save_config = request.save_config
self._supported_protocols = protocols
self._download_state = ImageDownload.DOWNLOAD_UNKNOWN
self._failure_reason = ImageDownload.UNKNOWN_ERROR
self._image_state = ImageDownload.IMAGE_UNKNOWN
self._additional_info = ''
self._downloaded_octets = 0
# Server profile info
self._server_profile_name = None
self._scheme = None
self._host = ''
self._port = None
self._path = ''
self._auth = None
# Download job info
self._download_job_name = None
self._age_out_period = DEFAULT_AUTO_AGE_MINUTES
self._max_execution = DEFAULT_MAX_JOB_RUN_SECONDS | opencord/voltha | [
73,
117,
73,
17,
1484694318
] |
def create(handler, request, supported_protocols):
"""
Create and start a new image download
:param handler: (AdtranDeviceHandler) Device download is for
:param request: (ImageDownload) Request
:param supported_protocols: (list) download methods allowed (http, tftp, ...)
"""
download = Download(handler, request, supported_protocols)
download._deferred = reactor.callLater(0, download.start_download)
return download | opencord/voltha | [
73,
117,
73,
17,
1484694318
] |
def name(self):
return self._name | opencord/voltha | [
73,
117,
73,
17,
1484694318
] |
def download_state(self):
return self._download_state | opencord/voltha | [
73,
117,
73,
17,
1484694318
] |
def failure_reason(self):
return self._failure_reason | opencord/voltha | [
73,
117,
73,
17,
1484694318
] |
def image_state(self):
return self._image_state | opencord/voltha | [
73,
117,
73,
17,
1484694318
] |
def additional_info(self):
return self._additional_info | opencord/voltha | [
73,
117,
73,
17,
1484694318
] |
def downloaded_bytes(self):
return self._downloaded_octets | opencord/voltha | [
73,
117,
73,
17,
1484694318
] |
def profile_name(self):
return self._server_profile_name | opencord/voltha | [
73,
117,
73,
17,
1484694318
] |
def start_download(self):
import uuid
log.info('download-start', name=self.name)
if not self.parse_url():
self._download_failed()
returnValue('failed url parsing')
self._download_state = ImageDownload.DOWNLOAD_STARTED
self._failure_reason = ImageDownload.NO_ERROR
##############################################################
# Configure the file server profile
try:
self._additional_info = 'Configuring Download Server profile'
self._server_profile_name = 'VOLTHA.download.{}'.format(uuid.uuid4())
profile = self.server_profile_xml
yield self._handler.netconf_client.edit_config(profile)
except Exception as e:
log.exception('server-profile', e=e)
self._server_profile_name = None
self._failure_reason = ImageDownload.UNKNOWN_ERROR
self._additional_info += ': Failure: {}'.format(e.message)
self._download_failed()
raise
##############################################################
# Configure the software download maintenance job
try:
self._additional_info = 'Configuring Image Download Job'
self._download_job_name = 'VOLTHA.download.{}'.format(uuid.uuid4())
job = self.download_job_xml
yield self._handler.netconf_client.edit_config(job)
except Exception as e:
log.exception('server-profile', e=e)
self._download_job_name = None
self._failure_reason = ImageDownload.UNKNOWN_ERROR
self._additional_info += ': Failure: {}'.format(e.message)
self._download_failed()
raise
##############################################################
# Schedule a task to monitor the download
try:
self._additional_info = 'Monitoring download status'
self._deferred = reactor.callLater(0.5, self.monitor_download_status)
except Exception as e:
log.exception('server-profile', e=e)
self._failure_reason = ImageDownload.UNKNOWN_ERROR
self._additional_info += ': Failure: {}'.format(e.message)
self._download_failed()
raise
returnValue('started') | opencord/voltha | [
73,
117,
73,
17,
1484694318
] |
def server_profile_xml(self):
assert self._scheme in ['http', 'https', 'ftp', 'sftp', 'tftp'], 'Invalid protocol'
xml = """
<file-servers xmlns="http://www.adtran.com/ns/yang/adtran-file-servers">
<profiles>
<profile>"""
xml += '<name>{}</name>'.format(self._server_profile_name)
xml += '<connection-profile>'
xml += ' <host>{}</host>'.format(self._host)
xml += ' <port>{}</port>'.format(self._port) if self._port is not None else '<use-standard-port/>'
if self._scheme in ['http', 'https']:
xml += ' <protocol '
xml += 'xmlns:adtn-file-srv-https="http://www.adtran.com/ns/yang/adtran-file-servers-https">' +\
'adtn-file-srv-https:{}'.format(self._scheme)
xml += ' </protocol>'
elif self._scheme == 'sftp':
xml += ' <protocol '
xml += 'xmlns:adtn-file-srv-sftp="http://www.adtran.com/ns/yang/adtran-file-servers-sftp">' +\
'adtn-file-srv-sftp:sftp'
xml += ' </protocol>'
elif self._scheme in ['ftp', 'tftp']:
xml += '<protocol>adtn-file-srv:{}</protocol>'.format(self._scheme)
if self._auth is not None:
user_pass = self._auth.split(':')
xml += '<username>{}</username>'.format(user_pass[0])
xml += '<password>$0${}</password>'.format("".join(user_pass[1:]))
# And the trailer
xml += """
</connection-profile>
</profile>
</profiles>
</file-servers>
"""
return xml | opencord/voltha | [
73,
117,
73,
17,
1484694318
] |
def download_job_xml(self):
# TODO: May want to support notifications
# TODO: Not sure about this name for the entity
entity = 'main 0'
xml = """
<maintenance-jobs xmlns="http://www.adtran.com/ns/yang/adtran-maintenance-jobs" xmlns:adtn-phys-sw-mnt="http://www.adtran.com/ns/yang/adtran-physical-software-maintenance">
<maintenance-job>
<name>{}</name>
<enabled>true</enabled>
<notify-enabled>false</notify-enabled>
<maximum-execution-time>{}</maximum-execution-time>
<run-once>true</run-once>
<adtn-phys-sw-mnt:download-software>
<adtn-phys-sw-mnt:physical-entity>{}</adtn-phys-sw-mnt:physical-entity>
<adtn-phys-sw-mnt:software-name>software</adtn-phys-sw-mnt:software-name>
<adtn-phys-sw-mnt:remote-file>
<adtn-phys-sw-mnt:file-server-profile>{}</adtn-phys-sw-mnt:file-server-profile>
<adtn-phys-sw-mnt:filename>{}</adtn-phys-sw-mnt:filename>
""".format(self._download_job_name, self._max_execution, entity,
self._server_profile_name, self._name)
if self._path is not None:
xml += """
<adtn-phys-sw-mnt:filepath>{}</adtn-phys-sw-mnt:filepath>
""".format(self._path)
xml += """
</adtn-phys-sw-mnt:remote-file>
</adtn-phys-sw-mnt:download-software>
</maintenance-job>
</maintenance-jobs>
"""
return xml | opencord/voltha | [
73,
117,
73,
17,
1484694318
] |
def download_status_xml(self):
xml = """
<filter>
<maintenance-jobs-state xmlns="http://www.adtran.com/ns/yang/adtran-maintenance-jobs">
<maintenance-job>
<name>{}</name>
</maintenance-job>
</maintenance-jobs-state>
</filter>
""".format(self._download_job_name)
return xml | opencord/voltha | [
73,
117,
73,
17,
1484694318
] |
def delete_server_profile_xml(self):
xml = """
<file-servers xmlns="http://www.adtran.com/ns/yang/adtran-file-servers">
<profiles operation="delete">
<profile>
<name>{}</name>
</profile>
</profiles>
</file-servers>
""".format(self._server_profile_name)
return xml | opencord/voltha | [
73,
117,
73,
17,
1484694318
] |
def delete_download_job_xml(self):
xml = """
<maintenance-jobs xmlns="http://www.adtran.com/ns/yang/adtran-maintenance-jobs">
<maintenance-job operation="delete">>
<name>{}</name>
</maintenance-job>
</maintenance-jobs>
""".format(self._download_job_name)
return xml | opencord/voltha | [
73,
117,
73,
17,
1484694318
] |
def monitor_download_status(self):
log.debug('monitor-download', name=self.name)
try:
results = yield self._handler.netconf_client.get(self.download_status_xml)
result_dict = xmltodict.parse(results.data_xml)
entries = result_dict['data']['maintenance-jobs-state']['maintenance-job']
name = entries.get('name')
assert name == self._download_job_name, 'The job status name does not match. {} != {}'.format(name, self.name)
self._download_state = self.monitor_state_to_download_state(entries['state']['#text'])
completed = entries['timestamps'].get('completed-timestamp')
started = entries['timestamps'].get('start-timestamp')
if self._download_state == ImageDownload.DOWNLOAD_FAILED:
self._failure_reason = ImageDownload.UNKNOWN_ERROR
self._additional_info = entries['error'].get('error-message')
elif self._download_state == ImageDownload.INSUFFICIENT_SPACE:
self._failure_reason = ImageDownload.INSUFFICIENT_SPACE
self._additional_info = entries['error'].get('error-message')
elif self._download_state == ImageDownload.DOWNLOAD_STARTED:
self._failure_reason = ImageDownload.NO_ERROR
self._additional_info = 'Download started at {}'.format(started)
elif self._download_state == ImageDownload.DOWNLOAD_SUCCEEDED:
self._failure_reason = ImageDownload.NO_ERROR
self._additional_info = 'Download completed at {}'.format(completed)
else:
raise NotImplemented('Unsupported state')
done = self._download_state in [ImageDownload.DOWNLOAD_FAILED,
ImageDownload.DOWNLOAD_SUCCEEDED,
ImageDownload.INSUFFICIENT_SPACE]
except Exception as e:
log.exception('protocols', e=e)
done = False
if not done:
self._deferred = reactor.callLater(1, self.monitor_download_status)
returnValue('done' if done else 'not-done-yet') | opencord/voltha | [
73,
117,
73,
17,
1484694318
] |
def _download_complete(self):
log.info('download-completed', name=self.name)
self._cancel_deferred()
self._download_state = ImageDownload.DOWNLOAD_SUCCEEDED
self._downloaded_octets = 123456
self._failure_reason = ImageDownload.NO_ERROR
reactor.callLater(0, self._cleanup_download_job, 20)
reactor.callLater(0, self._cleanup_server_profile, 20)
# TODO: How do we signal completion?
device = self._handler.adapter_agent.get_device(self.device_id)
if device is not None:
# restore admin state to enabled
device.admin_state = AdminState.ENABLED
self._handler.adapter_agent.update_device(device) | opencord/voltha | [
73,
117,
73,
17,
1484694318
] |
def _cleanup_server_profile(self, retries, attempt=1):
log.info('cleanup-server', name=self.name,
profile=self._server_profile_name,
attempt=attempt, remaining=retries)
if self._server_profile_name is not None:
try:
profile = self.delete_server_profile_xml
yield self._handler.netconf_client.edit_config(profile)
self._server_profile_name = None
except Exception as e:
log.exception(e.message)
if retries > 0:
reactor.callLater(attempt * 60, self._cleanup_download_job,
retries - 1, attempt + 1) | opencord/voltha | [
73,
117,
73,
17,
1484694318
] |
def _cleanup_download_job(self, retries, attempt=1):
log.info('cleanup-download', name=self.name,
profile=self._download_job_name,
attempt=attempt, remaining=retries)
if self._download_job_name is not None:
try:
job = self.delete_download_job_xml
yield self._handler.netconf_client.edit_config(job)
self._download_job_name = None
except Exception as e:
log.exception(e.message)
if retries > 0:
reactor.callLater(attempt * 60, self._cleanup_download_job,
retries - 1, attempt + 1) | opencord/voltha | [
73,
117,
73,
17,
1484694318
] |
def activate_image(self):
log.info('download-activate', name=self.name)
if self._download_state == ImageDownload.DOWNLOAD_SUCCEEDED:
pass # TODO: Implement
self._image_state = ImageDownload.IMAGE_ACTIVE
returnValue('TODO: Implement this') | opencord/voltha | [
73,
117,
73,
17,
1484694318
] |
Subsets and Splits