Debian Codegraph @

devtools/hpilo_mirror

raw
1 #!/usr/bin/python3
2 #
3 # Mirror the iLO firmware directory and create firmware.conf for the hpilo
4 # repository. Not meant to be used by end users.
5 #
6 # (c) 2011-2021 Dennis Kaarsemaker <[email protected]>
7 # see COPYING for license details
8
9 import configparser
10 import ftplib
11 import glob
12 import io
13 import optparse
14 import os
15 import re
16 import requests
17 import sys
18 import tarfile
19 from whelk import Shell
20 try:
21 git = Shell(redirect=False, encoding='utf-8').git
22 except AttributeError:
23 git = lambda *args: True
24
25 def main():
26 p = optparse.OptionParser()
27 p.add_option('-v', '--verbose', dest="verbose", action="store_true", default=False,
28 help="Be more verbose")
29 p.add_option('-q', '--quiet', dest="quiet", action="count", default=0,
30 help="no output except errors and updates. Repeat to get only errors")
31 p.add_option('--blank-files', dest='blank_files', action="store_true", default=False,
32 help="Delete downloaded content after processing")
33 p.add_option('--reset', dest='reset', action="store_true", default=False,
34 help="Reset git tree to origin/master before mirroring")
35 p.add_option('--fetch', dest='fetch', action="store_true", default=False,
36 help="Fetch git data before mirroring")
37 p.add_option('--keep', dest='keep', action="store_true", default=False,
38 help="Keep changes")
39 opts, args = p.parse_args()
40
41 repo = os.path.abspath(os.path.dirname(__file__))
42 repo = git('-C', repo, 'rev-parse', '--show-toplevel', stdout=Shell.PIPE).stdout.strip()
43 os.chdir(repo)
44
45 # Do we need to update?
46 if opts.fetch:
47 git('fetch', '--quiet')
48
49 if opts.reset:
50 git('reset', '--quiet', '--hard', 'origin/master')
51
52 # Abort if there are local changes
53 if not git('diff', '--quiet', '--exit-code', '--', 'firmware.conf'):
54 print("Local changes to firmware.conf, aborting")
55 return
56
57 # Mirror all files and write config
58 ftproot = ('ftp.hp.com', '/pub/softlib2/software1/sc-linux-fw-ilo')
59 conf = os.path.join(repo, 'firmware.conf')
60 root = os.path.join(repo, 'devtools', 'firmware')
61
62 ftp = FTP(ftproot[0], conf=conf, verbosity = 0 if opts.quiet else 2 if opts.verbose else 1, blank_files=opts.blank_files)
63
64 # ftp.login('anonymous','anonymous')
65 # ftp.mirror(ftproot[1], root)
66 resp = requests.get('http://pingtool.org/latest-hp-ilo-firmwares/')
67 ftp.mirror_urls(re.findall('http://downloads.hpe.com[^ "<]*', resp.text), root)
68
69 os.chdir(repo)
70 result = git('diff', '--quiet', '--exit-code', '--', 'firmware.conf')
71 if not result:
72 git('--no-pager', 'diff', '--color=never', '--', 'firmware.conf')
73 if not opts.keep:
74 git('checkout', '--', 'firmware.conf')
75
76 class FTP(ftplib.FTP):
77 def __init__(self, *args, **kwargs):
78 self.host = args[0]
79 self.conf = kwargs.pop('conf', None)
80 self.verbosity = kwargs.pop('verbosity', None)
81 self.blank_files = kwargs.pop('blank_files', None)
82 # super(FTP, self).__init__(*args, **kwargs)
83 self.configparser = configparser.ConfigParser()
84 self.configparser.read(self.conf)
85
86 def log(self, level, msg):
87 if self.verbosity >= level:
88 print(msg)
89
90 def mirror(self, remote, local):
91 if not os.path.exists(local):
92 os.mkdir(local)
93 os.chdir(local)
94 self.cwd(remote)
95
96 lines = []
97 self.retrlines('LIST', lines.append)
98 for line in lines:
99 if line.startswith('total'):
100 continue
101 mode, _, _, _, _, _, _, _, name = line.split(None, 8)
102 if name in ('.', '..'):
103 continue
104 if mode.startswith('d'):
105 self.log(1, "Mirroring %s" % name)
106 if os.path.exists(name) and name.startswith('v'):
107 os.chdir(name)
108 if glob.glob('*scexe'):
109 scexe = glob.glob('*.scexe')[0]
110 self.extract(scexe)
111 bin = glob.glob('*.bin')[0]
112 self.add_version("%s/%s" % (remote, name), scexe, bin)
113 if self.blank_files:
114 for file in os.listdir('.'):
115 if os.path.isfile(file):
116 open(file, 'w').close()
117 os.chdir('..')
118 continue
119 self.mirror(os.path.join(remote, name), os.path.join(local, name))
120 if self.blank_files:
121 for file in os.listdir('.'):
122 if os.path.isfile(file):
123 open(file, 'w').close()
124 self.cwd('..')
125 os.chdir('..')
126 else:
127 if not os.path.exists(name):
128 self.log(1, "Downloading %s" % name)
129 with open(name, 'wb') as fd:
130 self.retrbinary('RETR %s' % name, fd.write)
131 if name.endswith('.scexe'):
132 self.extract(name)
133 bin = glob.glob('*.bin')[0]
134 self.add_version(remote, name, bin)
135 for k in sorted(self.configparser._sections.keys()):
136 self.configparser._sections.move_to_end(k)
137 with open(self.conf, 'w') as fd:
138 self.configparser.write(fd)
139
140 def mirror_urls(self, urls, local):
141 if not os.path.exists(local):
142 os.mkdir(local)
143 os.chdir(local)
144
145 for url in urls:
146 path = url.split('/')[-3:]
147 dn = os.sep.join(path[-3:-1])
148 if not os.path.exists(dn):
149 os.makedirs(dn)
150 fn = os.sep.join(path[-3:])
151 if not os.path.exists(fn):
152 self.log(1, "Downloading %s" % url)
153 resp = requests.get(url, stream=True)
154 if resp.status_code != 200:
155 continue
156 with open(fn, 'wb') as fd:
157 for chunk in resp.iter_content(chunk_size=4096):
158 fd.write(chunk)
159 os.chdir(dn)
160
161 if glob.glob('*scexe'):
162 scexe = glob.glob('*.scexe')[0]
163 self.extract(scexe)
164 bin = glob.glob('*.bin')[0]
165 self.add_version(url, scexe, bin)
166
167 if self.blank_files:
168 for file in os.listdir('.'):
169 if os.path.isfile(file):
170 open(file, 'w').close()
171 if self.blank_files:
172 for file in os.listdir('.'):
173 if os.path.isfile(file):
174 open(file, 'w').close()
175
176 os.chdir(local)
177
178 for k in sorted(self.configparser._sections.keys()):
179 self.configparser._sections.move_to_end(k)
180 with open(self.conf, 'w') as fd:
181 self.configparser.write(fd)
182
183 def extract(self, name):
184 if glob.glob('*.xml'):
185 return
186 self.log(2, "Processing %s" % name)
187 with open(name, 'rb') as fd:
188 scexe = fd.read()
189 # An scexe is a shell script with an embedded compressed tarball. Find the tarball.
190 skip_start = scexe.index(b'_SKIP=') + 6
191 skip_end = scexe.index(b'\n', skip_start)
192 skip = int(scexe[skip_start:skip_end]) - 1
193 tarball = scexe.split(b'\n', skip)[-1]
194
195 # Now uncompress it
196 if tarball[:2] != b'\x1f\x8b':
197 raise ValueError("Downloaded scexe file %s seems corrupt" % name)
198
199 tf = tarfile.open(fileobj=io.BytesIO(tarball), mode='r:gz')
200 for bf in tf.getnames():
201 self.log(2, " Extracting %s" % bf)
202 tf.extract(bf, '.')
203
204 def add_version(self, remote, scexe, bin):
205 bin = bin.lower()
206 url = remote if remote.startswith('http://') else 'http://%s%s/%s' % (self.host, remote, scexe)
207 if '_' in bin:
208 ilo, version = os.path.splitext(bin)[0].split('_')
209 else:
210 ilo, version = 'ilo', os.path.splitext(bin)[0].replace('ilo', '')
211 version = '%s.%s' % (version[0], version[1:])
212 if version.endswith('j'):
213 return
214 vsection = '%s %s' % (ilo, version)
215 if not self.configparser.has_section(vsection):
216 self.configparser.add_section(vsection)
217 self.configparser.set(vsection, 'version', version)
218 self.configparser.set(vsection, 'url', url)
219 self.configparser.set(vsection, 'file', bin)
220 if not self.configparser.has_section(ilo):
221 self.configparser.add_section(ilo)
222 if self.configparser.has_option(ilo, 'version') and version <= self.configparser.get(ilo, 'version'):
223 return
224 self.log(1, "New %s firmware version: %s (%s)" % (ilo, version, url))
225 self.configparser.set(ilo, 'version', version)
226 self.configparser.set(ilo, 'url', url)
227 self.configparser.set(ilo, 'file', bin)
228
229 main()