added OpenSecurity Initial image downloader
authorOliver Maurhart <oliver.maurhart@ait.ac.at>
Fri, 28 Feb 2014 12:50:56 +0100
changeset 837a9d73ac796a
parent 82 d1c6a193b888
child 84 2e67f3816ea1
added OpenSecurity Initial image downloader
OpenSecurity/bin/download-image.pyw
     1.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
     1.2 +++ b/OpenSecurity/bin/download-image.pyw	Fri Feb 28 12:50:56 2014 +0100
     1.3 @@ -0,0 +1,221 @@
     1.4 +#!/bin/env python
     1.5 +# -*- coding: utf-8 -*-
     1.6 +
     1.7 +# ------------------------------------------------------------
     1.8 +# download-osec-vm-image 
     1.9 +# 
    1.10 +# download the initial OsecVM.ova image
    1.11 +#
    1.12 +# Autor: Oliver Maurhart, <oliver.maurhart@ait.ac.at>
    1.13 +#
    1.14 +# Copyright (C) 2014 AIT Austrian Institute of Technology
    1.15 +# AIT Austrian Institute of Technology GmbH
    1.16 +# Donau-City-Strasse 1 | 1220 Vienna | Austria
    1.17 +# http://www.ait.ac.at
    1.18 +#
    1.19 +# This program is free software; you can redistribute it and/or
    1.20 +# modify it under the terms of the GNU General Public License
    1.21 +# as published by the Free Software Foundation version 2.
    1.22 +# 
    1.23 +# This program is distributed in the hope that it will be useful,
    1.24 +# but WITHOUT ANY WARRANTY; without even the implied warranty of
    1.25 +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    1.26 +# GNU General Public License for more details.
    1.27 +# 
    1.28 +# You should have received a copy of the GNU General Public License
    1.29 +# along with this program; if not, write to the Free Software
    1.30 +# Foundation, Inc., 51 Franklin Street, Fifth Floor, 
    1.31 +# Boston, MA  02110-1301, USA.
    1.32 +# ------------------------------------------------------------
    1.33 +
    1.34 +
    1.35 +# ------------------------------------------------------------
    1.36 +# imports
    1.37 +
    1.38 +import os
    1.39 +import sys
    1.40 +import urllib2
    1.41 +
    1.42 +from PyQt4 import QtCore
    1.43 +from PyQt4 import QtGui
    1.44 +
    1.45 +# local
    1.46 +from environment import Environment
    1.47 +
    1.48 +
    1.49 +# ------------------------------------------------------------
    1.50 +# code
    1.51 +
    1.52 +
    1.53 +class DownloadDialog(QtGui.QDialog):
    1.54 +    
    1.55 +    """Download the initial OsecVM image dialog."""
    1.56 +
    1.57 +    def __init__(self, parent = None, flags = QtCore.Qt.WindowFlags(0)):
    1.58 +        
    1.59 +        # super call and widget init
    1.60 +        super(DownloadDialog, self).__init__(parent, flags)
    1.61 +        self.setWindowTitle('Download initial OpenSecurity VM image')
    1.62 +        self.setup_ui()
    1.63 +
    1.64 +        # setup download thread
    1.65 +        self._downloader = Downloader()
    1.66 +        self._downloader.downloaded.connect(self.downloader_update)
    1.67 +        self._thread = QtCore.QThread()
    1.68 +        self._downloader.moveToThread(self._thread)
    1.69 +        self._downloader.finished.connect(self._thread.quit)
    1.70 +        self._thread.started.connect(self._downloader.work)
    1.71 +        self._thread.finished.connect(self.finished_downloader)
    1.72 +        self._thread.start() 
    1.73 +
    1.74 +
    1.75 +    def clicked_cancel(self):
    1.76 +
    1.77 +        """button cancel clicked"""
    1.78 +
    1.79 +        # tell download thread to stop
    1.80 +        self._downloader.stop = True
    1.81 +
    1.82 +
    1.83 +    def downloader_update(self, current, total):
    1.84 +        
    1.85 +        """New download values present"""
    1.86 +        if self.pbDownload.minimum() != 0:
    1.87 +            self.pbDownload.setMinimum(0)
    1.88 +        if self.pbDownload.maximum() != total:
    1.89 +            self.pbDownload.setMaximum(total)
    1.90 +        self.pbDownload.setValue(current)
    1.91 +
    1.92 +
    1.93 +    def finished_downloader(self):
    1.94 +        
    1.95 +        """Download thread has finished (either success or abort)"""
    1.96 +        if not self._downloader.error is None:
    1.97 +            QtGui.QMessageBox.critical(None, 'OpenSecurity Download VM image error', self._downloader.error)
    1.98 +
    1.99 +        self.accept();
   1.100 +
   1.101 +
   1.102 +    def setup_ui(self):
   1.103 +        
   1.104 +        """Create the widgets."""
   1.105 +        
   1.106 +        lyMain = QtGui.QVBoxLayout(self)
   1.107 +        lyMain.setContentsMargins(8, 8, 8, 8)
   1.108 +
   1.109 +        lbTitle = QtGui.QLabel('Downloading OpenSecurity VM image')
   1.110 +        lyMain.addWidget(lbTitle)
   1.111 +        self.pbDownload = QtGui.QProgressBar()
   1.112 +        self.pbDownload.setTextVisible(True)
   1.113 +        lyMain.addWidget(self.pbDownload)
   1.114 +       
   1.115 +        # buttons
   1.116 +        lyButton = QtGui.QHBoxLayout()
   1.117 +        lyMain.addLayout(lyButton)
   1.118 +        
   1.119 +        lyButton.addStretch(1)
   1.120 +        btnCancel = QtGui.QPushButton('&Cancel', self)
   1.121 +        btnCancel.setMinimumWidth(100)
   1.122 +        lyButton.addWidget(btnCancel)
   1.123 +        
   1.124 +        # connectors
   1.125 +        btnCancel.clicked.connect(self.clicked_cancel)
   1.126 +        
   1.127 +        # reduce to the max
   1.128 +        self.setMinimumWidth(400)
   1.129 +        self.resize(lyMain.minimumSize())
   1.130 +
   1.131 +
   1.132 +class Downloader(QtCore.QObject):
   1.133 +
   1.134 +    """This is the worker thread when downloading"""
   1.135 +
   1.136 +    downloaded = QtCore.pyqtSignal(int, int)
   1.137 +    finished = QtCore.pyqtSignal()
   1.138 +
   1.139 +    def __init__(self):
   1.140 +        
   1.141 +        # super call 
   1.142 +        super(Downloader, self).__init__()
   1.143 +        self.error = None
   1.144 +        self.stop = False
   1.145 +
   1.146 +        # place to store the OsecVM image
   1.147 +        self.vm_path = os.path.join(sys.path[0], '..', 'vm')
   1.148 +        if not os.path.exists(self.vm_path):
   1.149 +            os.mkdir(self.vm_path)
   1.150 + 
   1.151 +       
   1.152 +    def work(self):
   1.153 +
   1.154 +        """Thread method: download until finished or stopped"""
   1.155 +
   1.156 +        url = "http://service.x-net.at/opensecurity/OsecVM_latest.ova"
   1.157 +
   1.158 +        filename_download = os.path.join(self.vm_path, 'OsecVM_latest.ova')
   1.159 +        filename_target = os.path.join(self.vm_path, 'OsecVM.ova')
   1.160 +
   1.161 +        # open URL
   1.162 +        try: 
   1.163 +            resp = urllib2.urlopen(url)
   1.164 +        except urllib2.URLError as e:
   1.165 +            self.error = 'URLError: ' + str(e.reason)
   1.166 +            self.finished.emit()
   1.167 +            return
   1.168 +        except urllib2.HTTPError as e:
   1.169 +            self.error = 'HTTPError: ' + str(e.reason)
   1.170 +            self.finished.emit()
   1.171 +            return
   1.172 +
   1.173 +        # download a CHUNK of data and then update the GUI
   1.174 +        totalSize = int(resp.info().getheader('Content-Length').strip())
   1.175 +        currentSize = 0
   1.176 +        CHUNK_SIZE = 32768
   1.177 +        self.downloaded.emit(currentSize, totalSize)
   1.178 +
   1.179 +        f = open(filename_download, 'w')
   1.180 +        while (not self.stop) and (currentSize < totalSize):
   1.181 +            data = resp.read(CHUNK_SIZE)
   1.182 +            currentSize += len(data)
   1.183 +            f.write(data)
   1.184 +            self.downloaded.emit(currentSize, totalSize)
   1.185 +
   1.186 +        f.flush()
   1.187 +        f.close()
   1.188 +
   1.189 +        # rename the download to OsecVM.ova
   1.190 +        if os.path.exists(filename_target):
   1.191 +            os.remove(filename_target)
   1.192 +        os.rename(filename_download, filename_target)
   1.193 +
   1.194 +        self.finished.emit()
   1.195 +
   1.196 +
   1.197 +def main():
   1.198 +
   1.199 +    """entry point"""
   1.200 +    
   1.201 +    # launch Qt
   1.202 +    global app
   1.203 +    app = QtGui.QApplication(sys.argv)
   1.204 +
   1.205 +    # prebuild the pixmap cache: fetch all jpg, png and jpeg images and load them
   1.206 +    image_path = os.path.join(sys.path[0], '..', 'gfx')
   1.207 +    for file in os.listdir(image_path):
   1.208 +        if file.lower().rpartition('.')[2] in ('jpg', 'png', 'jpeg'):
   1.209 +            QtGui.QPixmapCache.insert(file.lower().rpartition('.')[0], QtGui.QPixmap(os.path.join(image_path, file)))
   1.210 +            
   1.211 +    # we should have now our application icon
   1.212 +    app.setWindowIcon(QtGui.QIcon(QtGui.QPixmapCache.find('opensecurity_icon_64')))
   1.213 +
   1.214 +    w = DownloadDialog()
   1.215 +    w.show()
   1.216 +
   1.217 +    # on with the show
   1.218 +    sys.exit(app.exec_())
   1.219 +   
   1.220 +    
   1.221 +# start
   1.222 +if __name__ == "__main__":
   1.223 +    main()
   1.224 +