OpenSecurity/bin/download-image.pyw
author Oliver Maurhart <oliver.maurhart@ait.ac.at>
Wed, 29 Oct 2014 15:18:22 +0100
changeset 240 d7ef04254e9c
parent 86 a169498c5314
permissions -rwxr-xr-x
lizenz fixed in all files
     1 #!/bin/env python
     2 # -*- coding: utf-8 -*-
     3 
     4 # ------------------------------------------------------------
     5 # download-osec-vm-image 
     6 # 
     7 # download the initial OsecVM.ova image
     8 #
     9 # Copyright 2013-2014 X-Net and AIT Austrian Institute of Technology
    10 # 
    11 # 
    12 #     X-Net Services GmbH
    13 #     Elisabethstrasse 1
    14 #     4020 Linz
    15 #     AUSTRIA
    16 #     https://www.x-net.at
    17 # 
    18 #     AIT Austrian Institute of Technology
    19 #     Donau City Strasse 1
    20 #     1220 Wien
    21 #     AUSTRIA
    22 #     http://www.ait.ac.at
    23 # 
    24 # 
    25 # Licensed under the Apache License, Version 2.0 (the "License");
    26 # you may not use this file except in compliance with the License.
    27 # You may obtain a copy of the License at
    28 # 
    29 #    http://www.apache.org/licenses/LICENSE-2.0
    30 # 
    31 # Unless required by applicable law or agreed to in writing, software
    32 # distributed under the License is distributed on an "AS IS" BASIS,
    33 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    34 # See the License for the specific language governing permissions and
    35 # limitations under the License.
    36 # ------------------------------------------------------------
    37 
    38 
    39 # ------------------------------------------------------------
    40 # imports
    41 
    42 import errno
    43 import os
    44 import sys
    45 import urllib2
    46 
    47 from PyQt4 import QtCore
    48 from PyQt4 import QtGui
    49 
    50 # local
    51 from environment import Environment
    52 
    53 
    54 # ------------------------------------------------------------
    55 # global vars
    56 
    57 
    58 vm_path = os.path.normpath(os.path.join(sys.path[0], '..', 'vm'))
    59 
    60 
    61 # ------------------------------------------------------------
    62 # code
    63 
    64 
    65 class DownloadDialog(QtGui.QDialog):
    66     
    67     """Download the initial OsecVM image dialog."""
    68 
    69     def __init__(self, parent = None, flags = QtCore.Qt.WindowFlags(0)):
    70         
    71         # super call and widget init
    72         super(DownloadDialog, self).__init__(parent, flags)
    73         self.setWindowTitle('Download initial OpenSecurity VM image')
    74         self.setup_ui()
    75 
    76         # setup download thread
    77         self._downloader = Downloader()
    78         self._downloader.downloaded.connect(self.downloader_update)
    79         self._thread = QtCore.QThread()
    80         self._downloader.moveToThread(self._thread)
    81         self._downloader.finished.connect(self._thread.quit)
    82         self._thread.started.connect(self._downloader.work)
    83         self._thread.finished.connect(self.finished_downloader)
    84         self._thread.start() 
    85 
    86 
    87     def clicked_cancel(self):
    88 
    89         """button cancel clicked"""
    90 
    91         # tell download thread to stop
    92         self._downloader.stop = True
    93 
    94 
    95     def downloader_update(self, current, total):
    96         
    97         """New download values present"""
    98         if self.pbDownload.minimum() != 0:
    99             self.pbDownload.setMinimum(0)
   100         if self.pbDownload.maximum() != total:
   101             self.pbDownload.setMaximum(total)
   102         self.pbDownload.setValue(current)
   103 
   104 
   105     def finished_downloader(self):
   106         
   107         """Download thread has finished (either success or abort)"""
   108         if not self._downloader.error is None:
   109             QtGui.QMessageBox.critical(None, 'OpenSecurity Download VM image error', self._downloader.error)
   110 
   111         self.accept();
   112 
   113 
   114     def setup_ui(self):
   115         
   116         """Create the widgets."""
   117         
   118         lyMain = QtGui.QVBoxLayout(self)
   119         lyMain.setContentsMargins(8, 8, 8, 8)
   120 
   121         lbTitle = QtGui.QLabel('Downloading OpenSecurity VM image')
   122         lyMain.addWidget(lbTitle)
   123         self.pbDownload = QtGui.QProgressBar()
   124         self.pbDownload.setTextVisible(True)
   125         lyMain.addWidget(self.pbDownload)
   126        
   127         # buttons
   128         lyButton = QtGui.QHBoxLayout()
   129         lyMain.addLayout(lyButton)
   130         
   131         lyButton.addStretch(1)
   132         btnCancel = QtGui.QPushButton('&Cancel', self)
   133         btnCancel.setMinimumWidth(100)
   134         lyButton.addWidget(btnCancel)
   135         
   136         # connectors
   137         btnCancel.clicked.connect(self.clicked_cancel)
   138         
   139         # reduce to the max
   140         self.setMinimumWidth(400)
   141         self.resize(lyMain.minimumSize())
   142 
   143 
   144 class Downloader(QtCore.QObject):
   145 
   146     """This is the worker thread when downloading"""
   147 
   148     downloaded = QtCore.pyqtSignal(int, int)
   149     finished = QtCore.pyqtSignal()
   150 
   151     def __init__(self):
   152         
   153         # super call 
   154         super(Downloader, self).__init__()
   155         self.error = None
   156         self.stop = False
   157 
   158         # place to store the OsecVM image
   159         if not os.path.exists(vm_path):
   160             os.mkdir(vm_path)
   161  
   162        
   163     def work(self):
   164 
   165         """Thread method: download until finished or stopped"""
   166 
   167         url = "http://service.x-net.at/opensecurity/OsecVM_latest.ova"
   168 
   169         filename_download = os.path.join(vm_path, 'OsecVM_latest.ova')
   170         filename_target = os.path.join(vm_path, 'OsecVM.ova')
   171 
   172         # open URL
   173         try: 
   174             resp = urllib2.urlopen(url)
   175         except urllib2.URLError as e:
   176             self.error = 'URLError: ' + str(e.reason)
   177             self.finished.emit()
   178             return
   179         except urllib2.HTTPError as e:
   180             self.error = 'HTTPError: ' + str(e.reason)
   181             self.finished.emit()
   182             return
   183 
   184         # download a CHUNK of data and then update the GUI
   185         totalSize = int(resp.info().getheader('Content-Length').strip())
   186         currentSize = 0
   187         CHUNK_SIZE = 32768
   188         self.downloaded.emit(currentSize, totalSize)
   189 
   190         f = open(filename_download, 'w')
   191         while (not self.stop) and (currentSize < totalSize):
   192             data = resp.read(CHUNK_SIZE)
   193             currentSize += len(data)
   194             f.write(data)
   195             self.downloaded.emit(currentSize, totalSize)
   196 
   197         f.flush()
   198         f.close()
   199 
   200         # rename the download to OsecVM.ova
   201         if os.path.exists(filename_target):
   202             os.remove(filename_target)
   203         os.rename(filename_download, filename_target)
   204 
   205         self.finished.emit()
   206 
   207 
   208 def main():
   209 
   210     """entry point"""
   211     
   212     # launch Qt
   213     global app
   214     app = QtGui.QApplication(sys.argv)
   215 
   216     # prebuild the pixmap cache: fetch all jpg, png and jpeg images and load them
   217     image_path = os.path.join(sys.path[0], '..', 'gfx')
   218     for file in os.listdir(image_path):
   219         if file.lower().rpartition('.')[2] in ('jpg', 'png', 'jpeg'):
   220             QtGui.QPixmapCache.insert(file.lower().rpartition('.')[0], QtGui.QPixmap(os.path.join(image_path, file)))
   221             
   222     # we should have now our application icon
   223     app.setWindowIcon(QtGui.QIcon(QtGui.QPixmapCache.find('opensecurity_icon_64')))
   224 
   225     # check essential permissions
   226     try:
   227         f = open(os.path.join(vm_path, '.x'), 'w')
   228         f.write('test')
   229         f.flush()
   230         f.close()
   231         os.remove(os.path.join(vm_path, '.x'))
   232     except IOError as e:
   233         if e.errno == errno.EACCES:
   234             QtGui.QMessageBox.critical(None, 'OpenSecurity Download VM image error', 'No write access to "' + str(vm_path) + '"\nIs this run as Administrator?')
   235             sys.exit(1)
   236         else:
   237             QtGui.QMessageBox.critical(None, 'OpenSecurity Download VM image error', 'Error occured.\nErrno: ' + str(e.errno))
   238             sys.exit(1)
   239 
   240     # open download dialog
   241     w = DownloadDialog()
   242     w.show()
   243 
   244     # on with the show
   245     sys.exit(app.exec_())
   246    
   247     
   248 # start
   249 if __name__ == "__main__":
   250     main()
   251