1 | from jinja2 import Environment |
---|
2 | from jinja2.loaders import FileSystemLoader |
---|
3 | from jinja2 import Template |
---|
4 | |
---|
5 | import tempfile |
---|
6 | import shutil |
---|
7 | import subprocess |
---|
8 | |
---|
9 | import os |
---|
10 | import threading |
---|
11 | import datetime |
---|
12 | import ConfigParser |
---|
13 | import pexpect |
---|
14 | import re |
---|
15 | import json |
---|
16 | |
---|
17 | import BaseHTTPServer |
---|
18 | from SimpleHTTPServer import SimpleHTTPRequestHandler |
---|
19 | from multiprocessing import Process |
---|
20 | |
---|
21 | class LliurexMirror: |
---|
22 | |
---|
23 | |
---|
24 | def __init__(self): |
---|
25 | #Default values |
---|
26 | self.defaultpath = '/etc/lliurex-mirror/' |
---|
27 | self.debmirrorconfpath = os.path.join(self.defaultpath,'debmirror') |
---|
28 | self.configpath = os.path.join(self.defaultpath,'conf') |
---|
29 | self.distro="llx16" |
---|
30 | self.httpd = None |
---|
31 | |
---|
32 | self.tpl_env = Environment(loader=FileSystemLoader('/usr/share/n4d/templates/lliurex-mirror')) |
---|
33 | self.config = ConfigParser.ConfigParser() |
---|
34 | self.update_thread=threading.Thread() |
---|
35 | self.percentage=(0,None) |
---|
36 | |
---|
37 | |
---|
38 | #def init |
---|
39 | |
---|
40 | def startup(self,options): |
---|
41 | self.n4d_vars=objects["VariablesManager"] |
---|
42 | self.variable=objects["VariablesManager"].get_variable("LLIUREXMIRROR") |
---|
43 | |
---|
44 | |
---|
45 | if self.variable==None: |
---|
46 | try: |
---|
47 | self.n4d_vars.add_variable("LLIUREXMIRROR",{"internal":{}},"","Lliurex Mirror info variable","lliurex-mirror-core") |
---|
48 | except Exception as e: |
---|
49 | pass |
---|
50 | |
---|
51 | if type(self.variable)!=type({}): |
---|
52 | self.variable={} |
---|
53 | self.variable["internal"]={} |
---|
54 | |
---|
55 | #def startup |
---|
56 | |
---|
57 | def apt(self): |
---|
58 | # executed after apt operations |
---|
59 | pass |
---|
60 | |
---|
61 | #def apt |
---|
62 | |
---|
63 | # service test and backup functions # |
---|
64 | |
---|
65 | def test(self): |
---|
66 | |
---|
67 | pass |
---|
68 | |
---|
69 | #def test |
---|
70 | |
---|
71 | def backup(self): |
---|
72 | |
---|
73 | pass |
---|
74 | |
---|
75 | #def backup |
---|
76 | |
---|
77 | def restore(self): |
---|
78 | pass |
---|
79 | #def restore |
---|
80 | |
---|
81 | def set_cname(self): |
---|
82 | #Get template |
---|
83 | template = self.tpl_env.get_template("cname") |
---|
84 | list_variables = {} |
---|
85 | |
---|
86 | list_variables = objects['VariablesManager'].get_variable_list(['INTERNAL_DOMAIN','HOSTNAME']) |
---|
87 | for x in list_variables.keys(): |
---|
88 | if list_variables[x] == None: |
---|
89 | return {'status':False,'msg':'Variable ' + x + ' not defined'} |
---|
90 | |
---|
91 | #Encode vars to UTF-8 |
---|
92 | string_template = template.render(list_variables).encode('UTF-8') |
---|
93 | #Open template file |
---|
94 | fd, tmpfilepath = tempfile.mkstemp() |
---|
95 | new_export_file = open(tmpfilepath,'w') |
---|
96 | new_export_file.write(string_template) |
---|
97 | new_export_file.close() |
---|
98 | os.close(fd) |
---|
99 | #Write template values |
---|
100 | n4d_mv(tmpfilepath,'/var/lib/dnsmasq/config/cname-mirror',True,'root','root','0644',False ) |
---|
101 | |
---|
102 | return {'status':True,'msg':'Set mirror cname'} |
---|
103 | #def set_cname |
---|
104 | |
---|
105 | def update(self,distro=None): |
---|
106 | |
---|
107 | if distro==None: |
---|
108 | distro=self.distro |
---|
109 | |
---|
110 | if self.update_thread.is_alive(): |
---|
111 | return {'status':False,'msg':'Lliurex-mirror (n4d instance) is running'} |
---|
112 | |
---|
113 | self.percentage=(0,None) |
---|
114 | self.update_thread=threading.Thread(target=self._update,args=(distro,)) |
---|
115 | self.update_thread.daemon=True |
---|
116 | self.update_thread.start() |
---|
117 | |
---|
118 | return {'status':True,'msg':'running'} |
---|
119 | |
---|
120 | #def update |
---|
121 | |
---|
122 | def _update(self,distro): |
---|
123 | |
---|
124 | # link config debmirror to correct path with distro name |
---|
125 | self.build_debmirror_config(distro) |
---|
126 | os.remove('/etc/debmirror.conf') |
---|
127 | os.symlink(os.path.join(self.debmirrorconfpath,distro),'/etc/debmirror.conf') |
---|
128 | child=pexpect.spawn("/usr/bin/debmirror") |
---|
129 | try: |
---|
130 | objects["ZCenterVariables"].add_pulsating_color("lliurexmirror") |
---|
131 | except: |
---|
132 | pass |
---|
133 | while True: |
---|
134 | try: |
---|
135 | child.expect('\n') |
---|
136 | line =child.before |
---|
137 | print(line) |
---|
138 | line1=line.strip("\n") |
---|
139 | if line1.startswith("[") and line1[5] == "]": |
---|
140 | self.percentage=(int(line1[1:4].strip()),child.exitstatus) |
---|
141 | except pexpect.EOF: |
---|
142 | line1 = child.before |
---|
143 | if line1 != "" and line1.startswith("[") and line1[5] == "]": |
---|
144 | self.percentage=(int(line1[1:4].strip()),child.exitstatus) |
---|
145 | |
---|
146 | child.close() |
---|
147 | self.percentage=(self.percentage[0],child.exitstatus) |
---|
148 | break |
---|
149 | except Exception as e: |
---|
150 | break |
---|
151 | |
---|
152 | self.set_mirror_info(distro) |
---|
153 | |
---|
154 | try: |
---|
155 | objects["ZCenterVariables"].remove_pulsating_color("lliurexmirror") |
---|
156 | except: |
---|
157 | pass |
---|
158 | |
---|
159 | #def _update |
---|
160 | |
---|
161 | def is_alive(self): |
---|
162 | return self.update_thread.is_alive() |
---|
163 | #def is_alive |
---|
164 | |
---|
165 | def set_mirror_info(self,distro=None): |
---|
166 | |
---|
167 | if distro!=None: |
---|
168 | distro=distro |
---|
169 | else: |
---|
170 | distro=self.distro |
---|
171 | |
---|
172 | |
---|
173 | #self.n4d_vars.set_variable("ZEROCENTERINTERNAL",self.internal_variable) |
---|
174 | |
---|
175 | MIRROR_DATE=datetime.date.today().strftime("%d/%m/%Y") |
---|
176 | MIRROR_SIZE=self.get_size("/net/mirror/"+distro) |
---|
177 | |
---|
178 | self.variable["internal"]["last_mirror_date"]=MIRROR_DATE |
---|
179 | self.variable["internal"]["mirror_size"]=str(MIRROR_SIZE) |
---|
180 | |
---|
181 | print self.n4d_vars.set_variable("LLIUREXMIRROR",self.variable) |
---|
182 | |
---|
183 | #set_custom_text(self,app,text): |
---|
184 | txt="Updated on: " + str(MIRROR_DATE) |
---|
185 | txt+=" # Size: %.2fGB"%MIRROR_SIZE |
---|
186 | try: |
---|
187 | objects["ZCenterVariables"].set_custom_text("lliurexmirror",txt) |
---|
188 | abstract=open('/var/log/lliurex/lliurex-mirror.log','w') |
---|
189 | abstract.write(txt+"\n") |
---|
190 | abstract.close() |
---|
191 | except Exception as e: |
---|
192 | pass |
---|
193 | |
---|
194 | #def set_mirror_info(self): |
---|
195 | |
---|
196 | def get_size(self,start_path = '.'): |
---|
197 | |
---|
198 | total_size = 0 |
---|
199 | try: |
---|
200 | for dirpath, dirnames, filenames in os.walk(start_path): |
---|
201 | for f in filenames: |
---|
202 | fp = os.path.join(dirpath, f) |
---|
203 | total_size += os.path.getsize(fp) |
---|
204 | |
---|
205 | total_size/=1024*1024*1024.0 |
---|
206 | return total_size |
---|
207 | except: |
---|
208 | return 0 |
---|
209 | |
---|
210 | #def get_size(start_path = '.'): |
---|
211 | |
---|
212 | def search_field(self,filepath,fieldname): |
---|
213 | try: |
---|
214 | f = open(filepath,'r') |
---|
215 | needle = None |
---|
216 | lines = f.readlines() |
---|
217 | for x in lines: |
---|
218 | if re.match('\s*'+fieldname,x): |
---|
219 | needle = x.strip() |
---|
220 | return needle |
---|
221 | except: |
---|
222 | return None |
---|
223 | # def search_field |
---|
224 | |
---|
225 | def check_mirror(self): |
---|
226 | pass |
---|
227 | #def check_mirror |
---|
228 | |
---|
229 | def get_mirror_architecture(self,distro): |
---|
230 | filepath = os.path.join(self.debmirrorconfpath,distro) |
---|
231 | if not os.path.exists(filepath): |
---|
232 | return {'status':False,'msg':'not exists debmirror.conf to '+ distro } |
---|
233 | archs = self.search_field(filepath,'@arches') |
---|
234 | if archs != None: |
---|
235 | archs = archs.split("=")[1] |
---|
236 | if archs.endswith(";"): |
---|
237 | archs = archs[:-1] |
---|
238 | archs = eval(archs) |
---|
239 | return {'status':True,'msg':archs } |
---|
240 | return {'status':False,'msg':"debmirror.conf hasn't architecture variable" } |
---|
241 | #def get_mirror_architecture |
---|
242 | |
---|
243 | def set_mirror_architecture(self,distro,archs): |
---|
244 | configpath = os.path.join(self.configpath,distro + ".json") |
---|
245 | |
---|
246 | config = json.load(open(configpath,'r')) |
---|
247 | |
---|
248 | config['ARCHITECTURES'] = archs |
---|
249 | |
---|
250 | |
---|
251 | f=open(configpath,"w") |
---|
252 | |
---|
253 | data=unicode(json.dumps(config,indent=4,encoding="utf-8",ensure_ascii=False)).encode("utf-8") |
---|
254 | f.write(data) |
---|
255 | f.close() |
---|
256 | |
---|
257 | self.build_debmirror_config(distro) |
---|
258 | return {'status':True,'msg':'set architecture'} |
---|
259 | |
---|
260 | #def set_mirror_architecture |
---|
261 | |
---|
262 | def get_mirror_orig(self,distro): |
---|
263 | filepath = os.path.join(self.debmirrorconfpath,distro) |
---|
264 | if not os.path.exists(filepath): |
---|
265 | return {'status':False,'msg':'not exists debmirror.conf to '+ distro } |
---|
266 | origfrom = self.search_field(filepath,'\$host') |
---|
267 | if origfrom != None: |
---|
268 | origfrom = origfrom.split("=")[1] |
---|
269 | if origfrom.endswith(";"): |
---|
270 | origfrom = origfrom[:-1] |
---|
271 | origfrom = eval(origfrom) |
---|
272 | return origfrom |
---|
273 | return {'status':True,'msg':origfrom } |
---|
274 | return {'status':False,'msg':"debmirror.conf hasn't orig variable" } |
---|
275 | #def get_mirror_from |
---|
276 | |
---|
277 | def set_mirror_orig(self,distro,url): |
---|
278 | configpath = os.path.join(self.configpath, distro + ".json") |
---|
279 | config = json.load(open(configpath,'r')) |
---|
280 | config['URL'] = url |
---|
281 | |
---|
282 | f=open(configpath,"w") |
---|
283 | data=unicode(json.dumps(config,indent=4,encoding="utf-8",ensure_ascii=False)).encode("utf-8") |
---|
284 | f.write(data) |
---|
285 | f.close() |
---|
286 | |
---|
287 | self.build_debmirror_config(distro) |
---|
288 | return {'status':True,'msg':'set orig'} |
---|
289 | #def set_mirror_architecture |
---|
290 | |
---|
291 | def get_percentage(self): |
---|
292 | return self.percentage |
---|
293 | |
---|
294 | def build_debmirror_config(self,distro): |
---|
295 | template = self.tpl_env.get_template('debmirror.conf') |
---|
296 | configpath = os.path.join(self.configpath,distro + ".json") |
---|
297 | config = json.load(open(configpath,'r')) |
---|
298 | string_template = template.render(config).encode('utf-8') |
---|
299 | f = open(os.path.join(self.debmirrorconfpath,distro),'w') |
---|
300 | f.write(string_template) |
---|
301 | f.close() |
---|
302 | #def build_debmirror_config |
---|
303 | |
---|
304 | def enable_webserver_into_folder(self,path): |
---|
305 | port = 8000 |
---|
306 | self.webserverprocess = Process(target=self._enable_webserver_into_folder,args=(port,path,)) |
---|
307 | self.webserverprocess.start() |
---|
308 | return {'status':True,'msg':port} |
---|
309 | |
---|
310 | def _enable_webserver_into_folder(self,port,path): |
---|
311 | try: |
---|
312 | import os |
---|
313 | iface = '127.0.0.1' |
---|
314 | sock = (iface,port) |
---|
315 | proto = "HTTP/1.0" |
---|
316 | os.chdir(path) |
---|
317 | handler = SimpleHTTPRequestHandler |
---|
318 | handler.protocol_version = proto |
---|
319 | self.httpd = BaseHTTPServer.HTTPServer(sock,handler) |
---|
320 | self.httpd.serve_forever() |
---|
321 | except Exception, e: |
---|
322 | print e |
---|
323 | return None |
---|
324 | |
---|
325 | def stop_webserver(self): |
---|
326 | self.webserverprocess.terminate() |
---|
327 | return {'status':True,'msg':'Server stopped'} |
---|