forked from tranquilit/WAPT
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcommon.py
7415 lines (6271 loc) · 311 KB
/
common.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/python
# -*- coding: utf-8 -*-
# -----------------------------------------------------------------------
# This file is part of WAPT
# Copyright (C) 2013 Tranquil IT Systems http://www.tranquil.it
# WAPT aims to help Windows systems administrators to deploy
# setup and update applications on users PC.
#
# WAPT 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 3 of the License, or
# (at your option) any later version.
#
# WAPT 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 WAPT. If not, see <http://www.gnu.org/licenses/>.
#
# -----------------------------------------------------------------------
from __future__ import absolute_import
from waptutils import __version__
import os
import re
import logging
import datetime
import time
import sys
import tempfile
import hashlib
import glob
import codecs
import base64
import zlib
import sqlite3
import json
import ujson
import StringIO
import requests
import cPickle
try:
# pylint: disable=no-member
# no error
import requests.packages.urllib3
from requests.packages.urllib3.exceptions import InsecureRequestWarning
requests.packages.urllib3.disable_warnings(InsecureRequestWarning)
except:
pass
import fnmatch
import platform
import socket
import ssl
import copy
import getpass
import psutil
import threading
import traceback
import uuid
import gc
import random
import string
import locale
import shlex
from iniparse import RawConfigParser,INIConfig
from optparse import OptionParser
from collections import namedtuple
from collections import OrderedDict
from collections import defaultdict
from types import ModuleType
import shutil
import urlparse
import zipfile
# Windows stuff
import windnsquery
import win32api
import ntsecuritycon
import win32security
import win32net
import pywintypes
from ntsecuritycon import DOMAIN_GROUP_RID_ADMINS,DOMAIN_GROUP_RID_USERS
import ctypes
from ctypes import wintypes
logger = logging.getLogger()
try:
import requests_kerberos
has_kerberos = True
except:
has_kerberos = False
from _winreg import HKEY_LOCAL_MACHINE,EnumKey,OpenKey,QueryValueEx,\
EnableReflectionKey,DisableReflectionKey,QueryReflectionKey,\
QueryInfoKey,DeleteValue,DeleteKey,\
KEY_READ,KEY_WOW64_32KEY,KEY_WOW64_64KEY,KEY_ALL_ACCESS
# end of windows stuff
from waptutils import BaseObjectClass,ensure_list,ensure_unicode,default_http_headers,get_time_delta
from waptutils import httpdatetime2isodate,datetime2isodate,FileChunks,jsondump,ZipFile,LogOutput,isodate2datetime
from waptutils import import_code,import_setup,force_utf8_no_bom,format_bytes,wget,merge_dict,remove_encoding_declaration,list_intersection
from waptutils import _disable_file_system_redirection
from waptutils import get_requests_client_cert_session
from waptcrypto import SSLCABundle,SSLCertificate,SSLPrivateKey,SSLCRL,SSLVerifyException,SSLCertificateSigningRequest
from waptcrypto import get_peer_cert_chain_from_server,default_pwd_callback,hexdigest_for_data,get_cert_chain_as_pem
from waptcrypto import sha256_for_data,EWaptMissingPrivateKey,EWaptMissingCertificate
from waptcrypto import is_pem_key_encrypted
from waptpackage import EWaptException,EWaptMissingLocalWaptFile,EWaptNotAPackage,EWaptNotSigned
from waptpackage import EWaptBadTargetOS,EWaptNeedsNewerAgent,EWaptDiskSpace
from waptpackage import EWaptUnavailablePackage,EWaptConflictingPackage
from waptpackage import EWaptDownloadError,EWaptMissingPackageHook
from waptpackage import REGEX_PACKAGE_CONDITION,WaptRemoteRepo,PackageEntry,PackageRequest,HostCapabilities,PackageKey
import setuphelpers
import netifaces
class EWaptBadServerAuthentication(EWaptException):
pass
def is_system_user():
return setuphelpers.get_current_user().lower() == 'system'
###########################"
##################
def ipv4_to_int(ipaddr):
(a,b,c,d) = ipaddr.split('.')
return (int(a) << 24) + (int(b) << 16) + (int(c) << 8) + int(d)
def same_net(ip1,ip2,netmask):
"""Given 2 ipv4 address and mask, return True if in same subnet"""
return (ipv4_to_int(ip1) & ipv4_to_int(netmask)) == (ipv4_to_int(ip2) & ipv4_to_int(netmask))
def host_ipv4():
"""return a list of (iface,mac,{addr,broadcast,netmask})"""
ifaces = netifaces.interfaces()
res = []
for i in ifaces:
params = netifaces.ifaddresses(i)
if netifaces.AF_LINK in params and params[netifaces.AF_LINK][0]['addr'] and not params[netifaces.AF_LINK][0]['addr'].startswith('00:00:00'):
iface = {'iface':i,'mac':params[netifaces.AF_LINK][0]['addr']}
if netifaces.AF_INET in params:
iface.update(params[netifaces.AF_INET][0])
res.append( iface )
return res
def tryurl(url,proxies=None,timeout=5.0,auth=None,verify_cert=False,cert=None):
# try to get header for the supplied URL, returns None if no answer within the specified timeout
# else return time to get he answer.
with get_requests_client_cert_session(url=url,cert=cert,verify=verify_cert,proxies=proxies) as session:
try:
logger.debug(u' trying %s' % url)
starttime = time.time()
headers = session.head(url=url,
timeout=timeout,
auth=auth,
allow_redirects=True)
if headers.ok:
logger.debug(u' OK')
return time.time() - starttime
else:
headers.raise_for_status()
except Exception as e:
logger.debug(u' Not available : %s' % ensure_unicode(e))
return None
class EWaptCancelled(Exception):
pass
class WaptBaseDB(BaseObjectClass):
_dbpath = ''
_db_version = None
db = None
curr_db_version = None
def __init__(self,dbpath):
self.transaction_depth = 0
self._db_version = None
self.dbpath = dbpath
self.threadid = None
@property
def dbpath(self):
return self._dbpath
@dbpath.setter
def dbpath(self,value):
if not self._dbpath or (self._dbpath and self._dbpath != value):
self._dbpath = value
self.connect()
def begin(self):
# recreate a connection if not in same thread (reuse of object...)
if self.threadid is not None and self.threadid != threading.current_thread().ident:
logger.warning('Reset of DB connection, reusing wapt db object in a new thread')
self.connect()
elif self.threadid is None:
self.connect()
if self.transaction_depth == 0:
logger.debug(u'DB Start transaction')
self.db.execute('begin')
self.transaction_depth += 1
def commit(self):
if self.transaction_depth > 0:
self.transaction_depth -= 1
else:
logger.critical('Unexpected commit of an already committed transaction...')
if logger.level == logging.DEBUG:
raise Exception('Unexpected commit of an already committed transaction...')
if self.transaction_depth == 0:
logger.debug(u'DB commit')
try:
self.db.execute('commit')
except:
self.db.execute('rollback')
raise
def rollback(self):
if self.transaction_depth > 0:
self.transaction_depth -= 1
if self.transaction_depth == 0:
logger.debug(u'DB rollback')
self.db.execute('rollback')
def connect(self):
if not self.dbpath:
return
logger.debug('Thread %s is connecting to wapt db' % threading.current_thread().ident)
self.threadid = threading.current_thread().ident
if not self.dbpath == ':memory:' and not os.path.isfile(self.dbpath):
dirname = os.path.dirname(self.dbpath)
if os.path.isdir (dirname)==False:
os.makedirs(dirname)
os.path.dirname(self.dbpath)
self.db=sqlite3.connect(self.dbpath,detect_types=sqlite3.PARSE_DECLTYPES | sqlite3.PARSE_COLNAMES)
self.db.isolation_level = None
self.transaction_depth = 0
self.initdb()
elif self.dbpath == ':memory:':
self.db=sqlite3.connect(self.dbpath,detect_types=sqlite3.PARSE_DECLTYPES | sqlite3.PARSE_COLNAMES)
self.db.isolation_level = None
self.transaction_depth = 0
self.initdb()
else:
self.db=sqlite3.connect(self.dbpath,detect_types=sqlite3.PARSE_DECLTYPES | sqlite3.PARSE_COLNAMES)
self.db.isolation_level = None
self.transaction_depth = 0
if self.curr_db_version != self.db_version:
self.upgradedb()
def __enter__(self):
self.start_timestamp = time.time()
self.begin()
#logger.debug(u'DB enter %i' % self.transaction_depth)
return self
def __exit__(self, type, value, tb):
if time.time()-self.start_timestamp>1.0:
logger.debug('Transaction took too much time : %s' % (time.time()-self.start_timestamp,))
if not value:
#logger.debug(u'DB exit %i' % self.transaction_depth)
self.commit()
else:
self.rollback()
logger.debug(u'Error at DB exit %s, rollbacking\n%s' % (value,ensure_unicode(traceback.format_tb(tb))))
@property
def db_version(self):
if not self._db_version:
val = self.db.execute('select value from wapt_params where name="db_version"').fetchone()
if val:
self._db_version = val[0]
else:
raise Exception('Unknown DB Version')
return self._db_version
@db_version.setter
def db_version(self,value):
with self:
self.db.execute('insert or replace into wapt_params(name,value,create_date) values (?,?,?)',('db_version',value,datetime2isodate()))
self._db_version = value
@db_version.deleter
def db_version(self):
with self:
self.db.execute("delete from wapt_params where name = 'db_version'")
self._db_version = None
def initdb(self):
pass
def set_package_attribute(self,install_id,key,value):
"""Store permanently a (key/value) pair in database for a given package, replace existing one"""
with self:
self.db.execute('insert or replace into wapt_package_attributes(install_id,key,value,create_date) values (?,?,?,?)',(install_id,key,value,datetime2isodate()))
def set_param(self,name,value,ptype=None):
"""Store permanently a (name/value) pair in database, replace existing one"""
with self:
if not value is None:
if ptype is None:
if isinstance(value,(str,unicode)):
ptype = 'str'
# bool before int !
elif isinstance(value,bool):
ptype = 'bool'
elif isinstance(value,int):
ptype = 'int'
elif isinstance(value,float):
ptype = 'float'
elif isinstance(value,datetime.datetime):
ptype = 'datetime'
else:
ptype = 'json'
if ptype in ('int','float'):
value = str(value)
elif ptype in ('json','bool'):
value = jsondump(value)
elif ptype == 'datetime':
value = datetime2isodate(value)
self.db.execute('insert or replace into wapt_params(name,value,create_date,ptype) values (?,?,?,?)',(name,value,datetime2isodate(),ptype))
def get_param(self,name,default=None,ptype=None):
"""Retrieve the value associated with name from database"""
q = self.db.execute('select value,ptype from wapt_params where name=? order by create_date desc limit 1',(name,)).fetchone()
if q:
(value,sptype) = q
if ptype is None:
ptype = sptype
if not value is None:
if ptype == 'int':
value = long(value)
elif ptype == 'float':
value = float(value)
elif ptype in ('json','bool'):
value = ujson.loads(value)
elif ptype == 'datetime':
value = isodate2datetime(value)
return value
else:
return default
def delete_param(self,name):
with self:
row = self.db.execute('select value from wapt_params where name=? limit 1',(name,)).fetchone()
if row:
self.db.execute('delete from wapt_params where name=?',(name,))
def query(self,query, args=(), one=False,as_dict=True):
"""
execute la requete query sur la db et renvoie un tableau de dictionnaires
"""
cur = self.db.execute(query, args)
if as_dict:
rv = [dict((cur.description[idx][0], value)
for idx, value in enumerate(row)) for row in cur.fetchall()]
else:
rv = cur.fetchall()
return (rv[0] if rv else None) if one else rv
def upgradedb(self,force=False):
"""Update local database structure to current version if rules are described in db_upgrades
Args:
force (bool): force upgrade even if structure version is greater than requested.
Returns:
tuple: (old_structure_version,new_structure_version)
"""
with self:
try:
backupfn = ''
# use cached value to avoid infinite loop
old_structure_version = self._db_version
if old_structure_version >= self.curr_db_version and not force:
logger.warning(u'upgrade db aborted : current structure version %s is newer or equal to requested structure version %s' % (old_structure_version,self.curr_db_version))
return (old_structure_version,old_structure_version)
logger.info(u'Upgrade database schema')
if self.dbpath != ':memory:':
# we will backup old data in a file so that we can rollback
backupfn = tempfile.mktemp('.sqlite')
logger.debug(u' copy old data to %s' % backupfn)
shutil.copy(self.dbpath,backupfn)
else:
backupfn = None
# we will backup old data in dictionaries to convert them to new structure
logger.debug(u' backup data in memory')
old_datas = {}
tables = [ c[0] for c in self.db.execute('SELECT name FROM sqlite_master WHERE type = "table" and name like "wapt_%"').fetchall()]
for tablename in tables:
old_datas[tablename] = self.query('select * from %s' % tablename)
logger.debug(u' %s table : %i records' % (tablename,len(old_datas[tablename])))
logger.debug(u' drop tables')
for tablename in tables:
self.db.execute('drop table if exists %s' % tablename)
# create new empty structure
logger.debug(u' recreates new tables ')
new_structure_version = self.initdb()
del(self.db_version)
# append old data in new tables
logger.debug(u' fill with old data')
for tablename in tables:
if old_datas[tablename]:
logger.debug(u' process table %s' % tablename)
allnewcolumns = [ c[0] for c in self.db.execute('select * from %s limit 0' % tablename).description]
# take only old columns which match a new column in new structure
oldcolumns = [ k for k in old_datas[tablename][0] if k in allnewcolumns ]
insquery = "insert into %s (%s) values (%s)" % (tablename,",".join(oldcolumns),",".join("?" * len(oldcolumns)))
for rec in old_datas[tablename]:
logger.debug(u' %s' %[ rec[oldcolumns[i]] for i in range(0,len(oldcolumns))])
self.db.execute(insquery,[ rec[oldcolumns[i]] for i in range(0,len(oldcolumns))] )
# be sure to put back new version in table as db upgrade has put the old value in table
self.db_version = new_structure_version
return (old_structure_version,new_structure_version)
except Exception as e:
if backupfn:
logger.critical(u"UpgradeDB ERROR : %s, copy back backup database %s" % (e,backupfn))
shutil.copy(backupfn,self.dbpath)
raise
class WaptSessionDB(WaptBaseDB):
curr_db_version = '20181004'
def __init__(self,username=''):
super(WaptSessionDB,self).__init__(None)
if not username:
username = setuphelpers.get_current_user()
self.username = username
self.dbpath = os.path.join(setuphelpers.application_data(),'wapt','waptsession.sqlite')
def initdb(self):
"""Initialize current sqlite db with empty table and return structure version"""
assert(isinstance(self.db,sqlite3.Connection))
logger.debug(u'Initialize Wapt session database')
self.db.execute("""
create table if not exists wapt_sessionsetup (
id INTEGER PRIMARY KEY AUTOINCREMENT,
username varchar(255),
package_uuid varchar(255),
package varchar(255),
version varchar(255),
architecture varchar(255),
install_date varchar(255),
install_status varchar(255),
install_output TEXT,
process_id integer
)"""
)
self.db.execute("""
create index if not exists idx_sessionsetup_username on wapt_sessionsetup(username,package);""")
self.db.execute("""
create index if not exists idx_sessionsetup_package on wapt_sessionsetup(package);""")
self.db.execute("""
create index if not exists idx_sessionsetup_package_uuid on wapt_sessionsetup(package_uuid);""")
self.db.execute("""
create table if not exists wapt_params (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name varchar(64),
value text,
ptype varchar(10),
create_date varchar(255)
) """)
self.db.execute("""
create unique index if not exists idx_params_name on wapt_params(name);
""")
self.db_version = self.curr_db_version
return self.curr_db_version
def add_start_install(self,package_entry):
"""Register the start of installation in local db
Returns:
int : rowid of the inserted record
"""
with self:
cur = self.db.execute("""delete from wapt_sessionsetup where package=?""" ,(package_entry.package,))
cur = self.db.execute("""\
insert into wapt_sessionsetup (
username,
package_uuid,
package,
version,
architecture,
install_date,
install_status,
install_output,
process_id
) values (?,?,?,?,?,?,?,?,?)
""",(
self.username,
package_entry.package_uuid,
package_entry.package,
package_entry.version,
package_entry.architecture,
datetime2isodate(),
'INIT',
'',
os.getpid()
))
return cur.lastrowid
def update_install_status(self,rowid,set_status=None,append_output=None):
"""Update status of package installation on localdb"""
with self:
if set_status in ('OK','WARNING','ERROR'):
pid = None
else:
pid = os.getpid()
cur = self.db.execute("""\
update wapt_sessionsetup
set install_status=coalesce(?,install_status),install_output = coalesce(install_output,'') || ?,process_id=?
where rowid = ?
""",(
set_status,
ensure_unicode(append_output) if append_output is not None else '',
pid,
rowid,
)
)
return cur.lastrowid
def update_install_status_pid(self,pid,set_status='ERROR'):
"""Update status of package installation on localdb"""
with self:
cur = self.db.execute("""\
update wapt_sessionsetup
set install_status=coalesce(?,install_status) where process_id = ?
""",(
set_status,
pid,
)
)
return cur.lastrowid
def remove_install_status(self,package):
"""Remove status of package installation from localdb
>>> wapt = Wapt()
>>> wapt.forget_packages('tis-7zip')
???
"""
with self:
cur = self.db.execute("""delete from wapt_sessionsetup where package=?""" ,(package,))
return cur.rowcount
def remove_obsolete_install_status(self,installed_packages):
"""Remove local user status of packages no more installed"""
with self:
cur = self.db.execute("""delete from wapt_sessionsetup where package not in (%s)"""%\
','.join('?' for i in installed_packages), installed_packages)
return cur.rowcount
def is_installed(self,package,version):
p = self.query('select * from wapt_sessionsetup where package=? and version=? and install_status="OK"',(package,version))
if p:
return p[0]
else:
return None
class WaptDB(WaptBaseDB):
"""Class to manage SQLite database with local installation status"""
curr_db_version = '20190111'
def initdb(self):
"""Initialize current sqlite db with empty table and return structure version"""
assert(isinstance(self.db,sqlite3.Connection))
logger.debug(u'Initialize Wapt database')
self.db.execute("""
create table if not exists wapt_package (
id INTEGER PRIMARY KEY AUTOINCREMENT,
package_uuid varchar(255),
package varchar(255),
version varchar(255),
architecture varchar(255),
section varchar(255),
priority varchar(255),
maintainer varchar(255),
description varchar(255),
filename varchar(255),
size integer,
md5sum varchar(255),
depends varchar(800),
conflicts varchar(800),
sources varchar(255),
repo_url varchar(255),
repo varchar(255),
signer varchar(255),
signer_fingerprint varchar(255),
signature varchar(255),
signature_date varchar(255),
signed_attributes varchar(800),
min_wapt_version varchar(255),
maturity varchar(255),
locale varchar(255),
installed_size integer,
target_os varchar(255),
max_os_version varchar(255),
min_os_version varchar(255),
impacted_process varchar(255),
audit_schedule varchar(255),
editor varchar(255),
keywords varchar(255),
licence varchar(255),
homepage varchar(255)
)"""
)
self.db.execute("""
create index if not exists idx_package_name on wapt_package(package);""")
self.db.execute("""
create index if not exists idx_package_uuid on wapt_package(package_uuid);""")
self.db.execute("""
create table if not exists wapt_localstatus (
id INTEGER PRIMARY KEY AUTOINCREMENT,
package_uuid varchar(255),
package varchar(255),
version varchar(255),
version_pinning varchar(255),
explicit_by varchar(255),
architecture varchar(255),
section varchar(255),
priority varchar(255),
maturity varchar(255),
locale varchar(255),
install_date varchar(255),
install_status varchar(255),
install_output TEXT,
install_params VARCHAR(800),
uninstall_key varchar(255),
setuppy TEXT,
process_id integer,
depends varchar(800),
conflicts varchar(800),
last_audit_on varchar(255),
last_audit_status varchar(255),
last_audit_output TEXT,
next_audit_on varchar(255),
impacted_process varchar(255),
audit_schedule varchar(255),
persistent_dir varchar(255)
)
""")
self.db.execute("""
create index if not exists idx_localstatus_name on wapt_localstatus(package);
""")
self.db.execute("""
create index if not exists idx_localstatus_status on wapt_localstatus(install_status);
""")
self.db.execute("""
create index if not exists idx_localstatus_next_audit_on on wapt_localstatus(next_audit_on);
""")
self.db.execute("""
create index if not exists idx_localstatus_package_uuid on wapt_localstatus(package_uuid);
""")
self.db.execute("""
create table if not exists wapt_params (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name varchar(64),
value text,
ptype varchar(10),
create_date varchar(255)
) """)
self.db.execute("""
create unique index if not exists idx_params_name on wapt_params(name);
""")
self.db.execute("""CREATE TRIGGER IF NOT EXISTS inc_rev_ins_status
AFTER INSERT ON wapt_params
WHEN NEW.name not in ('status_revision','last_update_server_hashes')
BEGIN
update wapt_params set value=cast(value as integer)+1
where name='status_revision';
END
""")
self.db.execute("""CREATE TRIGGER IF NOT EXISTS inc_rev_upd_status
AFTER UPDATE ON wapt_params
WHEN NEW.name <> 'status_revision'
BEGIN
update wapt_params set value=cast(value as integer)+1
where name='status_revision';
END
""")
self.db.execute("""CREATE TRIGGER IF NOT EXISTS inc_rev_del_status
AFTER DELETE ON wapt_params
WHEN OLD.name <> 'status_revision'
BEGIN
update wapt_params set value=cast(value as integer)+1
where name='status_revision';
END
""")
# action : install, remove, check, session_setup, update, upgrade
# state : draft, planned, postponed, running, done, error, canceled
self.db.execute("""
CREATE TABLE if not exists wapt_task (
id integer NOT NULL PRIMARY KEY AUTOINCREMENT,
action varchar(16),
state varchar(16),
current_step varchar(255),
process_id integer,
start_date varchar(255),
finish_date varchar(255),
package_name varchar(255),
username varchar(255),
package_version_min varchar(255),
package_version_max varchar(255),
rundate_min varchar(255),
rundate_max varchar(255),
rundate_nexttry varchar(255),
runduration_max integer,
created_date varchar(255),
run_params VARCHAR(800),
run_output TEXT
);
""")
self.db.execute("""
create index if not exists idx_task_state on wapt_task(state);
""")
self.db.execute("""
create index if not exists idx_task_package_name on wapt_task(package_name);
""")
self.db.execute("""
create table if not exists wapt_sessionsetup (
id INTEGER PRIMARY KEY AUTOINCREMENT,
username varchar(255),
package varchar(255),
version varchar(255),
architecture varchar(255),
maturity varchar(255),
locale varchar(255),
install_date varchar(255),
install_status varchar(255),
install_output TEXT
)"""
)
self.db.execute("""
create index idx_sessionsetup_username on wapt_sessionsetup(username,package);""")
self.db_version = self.curr_db_version
return self.curr_db_version
def add_package_entry(self,package_entry,locale_code=None):
with self:
# for backward compatibility with packages signed without package_uuid attribute
if not package_entry.package_uuid:
package_entry.package_uuid = package_entry.make_fallback_uuid()
cur = self.db.execute("""delete from wapt_package where package=? and version=? and architecture=? and maturity=? and locale=?""" ,
(package_entry.package,package_entry.version,package_entry.architecture,package_entry.maturity,package_entry.locale))
cur = self.db.execute("""\
insert into wapt_package (
package_uuid,
package,
version,
section,
priority,
architecture,
maintainer,
description,
filename,
size,
md5sum,
depends,
conflicts,
sources,
repo_url,
repo,
signer,
signer_fingerprint,
maturity,
locale,
signature,
signature_date,
signed_attributes,
min_wapt_version,
installed_size,
max_os_version,
min_os_version,
target_os,
impacted_process,
audit_schedule,
editor,
keywords,
licence,
homepage
) values (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)
""",(
package_entry.package_uuid,
package_entry.package,
package_entry.version,
package_entry.section,
package_entry.priority,
package_entry.architecture,
package_entry.maintainer,
package_entry.get_localized_description(locale_code),
package_entry.filename,
package_entry.size,
package_entry.md5sum,
package_entry.depends,
package_entry.conflicts,
package_entry.sources,
package_entry.repo_url,
package_entry.repo,
package_entry.signer,
package_entry.signer_fingerprint,
package_entry.maturity,
package_entry.locale,
package_entry.signature,
package_entry.signature_date,
package_entry.signed_attributes,
package_entry.min_wapt_version,
package_entry.installed_size,
package_entry.max_os_version,
package_entry.min_os_version,
package_entry.target_os,
package_entry.impacted_process,
package_entry.audit_schedule,
package_entry.editor,
package_entry.keywords,
package_entry.licence,
package_entry.homepage,
)
)
return cur.lastrowid
def add_start_install(self,package_entry,params_dict={},explicit_by=None):
"""Register the start of installation in local db
Args:
params_dict (dict) : dictionary of parameters provided on command line with --param or by the server
explicit_by (str) : username of initiator of the install.
if not None, install is not a dependencie but an explicit manual install
setuppy (str) : python source code used for install, uninstall or session_setup
code used for uninstall or session_setup must use only wapt self library as
package content is no longer available at this step.
Returns:
int : rowid of the inserted install status row
"""
with self:
if package_entry.package_uuid:
# keep old entry for reference until install is completed.
cur = self.db.execute("""update wapt_localstatus set install_status='UPGRADING' where package=? and package_uuid <> ?""" ,(package_entry.package,package_entry.package_uuid))
cur = self.db.execute("""delete from wapt_localstatus where package_uuid=?""" ,(package_entry.package_uuid,))
else:
cur = self.db.execute("""delete from wapt_localstatus where package_uuid=?""" ,(package_entry.package,))
cur = self.db.execute("""\
insert into wapt_localstatus (
package_uuid,
package,
version,
section,
priority,
architecture,
install_date,
install_status,
install_output,
install_params,
explicit_by,
process_id,
maturity,
locale,
depends,
conflicts,
impacted_process,
audit_schedule
) values (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)
""",(
package_entry.package_uuid,
package_entry.package,
package_entry.version,
package_entry.section,
package_entry.priority,
package_entry.architecture,
datetime2isodate(),
'INIT',
'',
jsondump(params_dict),
explicit_by,
os.getpid(),
package_entry.maturity,
package_entry.locale,
package_entry.depends,
package_entry.conflicts,
package_entry.impacted_process,
package_entry.audit_schedule,
))
return cur.lastrowid
def update_install_status(self,rowid,set_status=None,append_output=None,uninstall_key=None,persistent_dir=None):
"""Update status of package installation on localdb"""
with self:
if set_status in ('OK','WARNING','ERROR'):
pid = None
else:
pid = os.getpid()
cur = self.db.execute("""\
update wapt_localstatus
set install_status=coalesce(?,install_status),
install_output = coalesce(install_output,'') || ?,
uninstall_key=coalesce(?,uninstall_key),
process_id=?,
persistent_dir = coalesce(?,persistent_dir)
where rowid = ?
""",(
set_status,
ensure_unicode(append_output) if append_output is not None else u'',
uninstall_key,
pid,
persistent_dir,
rowid,
)
)
# removed repviously installed package entry
install_rec = self.query('select package_uuid,package from wapt_localstatus where rowid = ?',(rowid,),one=True)
if install_rec and set_status in ('OK','WARNING','ERROR'):
cur = self.db.execute("""delete from wapt_localstatus where package=? and rowid <> ?""" ,(install_rec['package'],rowid))
return cur.lastrowid
def update_audit_status(self,rowid,set_status=None,set_output=None,append_output=None,set_last_audit_on=None,set_next_audit_on=None):
"""Update status of package installation on localdb"""
with self:
if set_status in ('OK','WARNING','ERROR'):
pid = None
else:
pid = os.getpid()
# retrieve last status
#cur = self.db.execute("""select last_audit_status,last_audit_on,next_audit_on from wapt_localstatus where rowid = ?""",(rowid,))
#(last_audit_status,last_audit_on,next_audit_on) = cur.fetchone()
#if last_audit_on is None:
# last_audit_on = datetime2isodate()
#
#if set_status is None:
# set_status = last_audit_status
#if set_status is None:
# set_status = 'RUNNING'
cur = self.db.execute("""\
update wapt_localstatus set
last_audit_status=coalesce(?,last_audit_status,'RUNNING'),
last_audit_on=coalesce(?,last_audit_on),
last_audit_output = coalesce(?,last_audit_output,'') || ?,
process_id=?,next_audit_on=coalesce(?,next_audit_on)
where rowid = ?
""",(
set_status,
set_last_audit_on,
set_output,
append_output if append_output is not None else '',
pid,
set_next_audit_on,