proinfodataAgent.py 9.32 KB
Newer Older
1
# Copyright (C) 2009-2012 Centro de Computacao Cientifica e Software Livre
Adriano da Luz's avatar
Adriano da Luz committed
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
# Departamento de Informatica - Universidade Federal do Parana - C3SL/UFPR
#
# This file is part of windows-coleta
#
# windows-coleta 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 2
# of the License, or (at your option) any later version.
#
# This program 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 this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
# USA.

#coding: utf-8
import os
import sys
import _winreg
import shutil
import subprocess
import urllib
from time import localtime, strftime
from xml.etree.ElementTree import tostring
import collect
import glob

# ==========================================
#       Constants
# ==========================================
# TODO: Check compatibility with 64bit Windows (Program Files(x86) folder)
PROINFODATAPATH = os.environ["ProgramFiles"] + "\\ProInfoData"
URL = ""
# Log lifetime in days
LOGLIFETIME = 30

# ==========================================
#       Classes definitions
# ==========================================
# Class log: log manipulation
class Log():
    # Verify if today's log exist. If exists, the log is opened. Otherwise,
    # a new one is created
    def __init__(self):
        date = strftime("%Y%m%d", localtime())
        logpath = PROINFODATAPATH + "\log"
        logfilename = date + ".log"
        if (os.path.exists(logpath + "\\" + logfilename)):
            self.logfile = file(logpath + "\\" + logfilename,"a")
        else:
            self.logfile = file(logpath + "\\" + logfilename,"w")
57
        self.write("START: Proinfodata Agent Windows.")
Adriano da Luz's avatar
Adriano da Luz committed
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

    def write(self, str):
        self.logfile.write(strftime("%I:%M:%S", localtime()) + ": ")
        self.logfile.write(str + "\n")

    def close(self):
        self.logfile.close()

    def flush(self):
        self.logfile.flush()

class clientError():
    def __init__(self, retCode, error):
        self.code = retCode
        self.errorMsg = error

# ==========================================
#       Functions definitions
# ==========================================
# Get the proinfodata version
def getVersion():
    return collect.getRegistryValue("HKEY_LOCAL_MACHINE", "SOFTWARE\\ProInfoData", "Version")

# Write INEP in conf\inep file
def writeInepConf(inep):
    inepConfFile = file(PROINFODATAPATH + "\\conf\\inep", "w")
    inepConfFile.write(inep)
    inepConfFile.close()

# Write Version in conf\version file
def writeVersionConf(version):
    versionConfFile = file(PROINFODATAPATH + "\\conf\\version", "w")
    versionConfFile.write(version)
    versionConfFile.close()

# Call client.exe returning the returncode and the output
def callClient(args):
    clientPath = "\"" + PROINFODATAPATH + "\\bin\\client.exe" + "\""
    proc = subprocess.Popen(clientPath + args, stdout=subprocess.PIPE,
    stderr=subprocess.PIPE, shell=True)
    out = proc.communicate()

    return (proc.returncode, out)

# Check for updates
def verifyUpdate():
    args = " --update --url=" + URL

    (phost, pport, puser, ppass) = getProxyInfo()

    if phost != "":
            args += " --phost=" + phost
            if pport != "":
                args += " --pport=" + pport
            if puser != "" or ppass != "":
                    args += " --puid=" + puser + " --ppasswd=" + ppass

    (returnCode, output) = callClient(args)
    if returnCode == 0:
        return 0

    if returnCode == 4:
        updatelink = output[0].split("\n")[0]
        return updatelink
    else:
        raise clientError(returnCode, output)

# Save the old collect-data file
def backupCollectData():
    if os.path.exists(PROINFODATAPATH + "\\data\\collect-data.xml"):
        date = strftime("%Y%m%d-%I%M%S", localtime())
        shutil.copy(PROINFODATAPATH + "\\data\\collect-data.xml",\
        PROINFODATAPATH + "\\data\\collect-data" + date + ".xml")
    return 0

# Delete old log files
def deleteOldLogs():
    logPath = PROINFODATAPATH + "\\log"
    today = strftime("%Y%m%d", localtime())
    ageLimit = int(today) - LOGLIFETIME
    for infile in glob.glob(os.path.join(logPath, '*.log')):
        try:
            fileDate = int(infile.split("\\")[-1].split(".")[0].strip())
        except:
            continue

        if fileDate <= ageLimit:
            os.remove(infile)

# Get proxy information from Windows registry
def getProxyInfo():
    phost = collect.getRegistryValue("HKEY_LOCAL_MACHINE", "SOFTWARE\\ProInfoData", "ProxyHost")
    pport = collect.getRegistryValue("HKEY_LOCAL_MACHINE", "SOFTWARE\\ProInfoData", "ProxyPort")
    puser = collect.getRegistryValue("HKEY_LOCAL_MACHINE", "SOFTWARE\\ProInfoData", "ProxyUser")
    ppass = collect.getRegistryValue("HKEY_LOCAL_MACHINE", "SOFTWARE\\ProInfoData", "ProxyPass")

    return (phost, pport, puser, ppass)

# Send the collect-data.xml
def sendData():
    args = " --inventory --url=" + URL + " --inep=" + inep

    (phost, pport, puser, ppass) = getProxyInfo()

    if phost != "":
            args += " --phost=" + phost
            if pport != "":
                args += " --pport=" + pport
            if puser != "" or ppass != "":
                    args += " --puid=" + puser + " --ppasswd=" + ppass

    (returnCode, output) = callClient(args)
    if returnCode != 0:
        raise clientError(returnCode, output)
    return 0

# Create collect-data.xml file
def writeCollectData(collectData):
    collectDataFile = file(PROINFODATAPATH + "\\data\\collect-data.xml", "w")
    collectDataFile.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n")
    collectDataFile.write(tostring(collectData))
    collectDataFile.close()

# Download the update package
def downloadUpdate(link):
    urllib.urlretrieve(link, PROINFODATAPATH + "\\update\\updatePackage.exe")

# Call the update package
def callUpdater():
    updaterPath = "\"" + PROINFODATAPATH + "\\update\\updatePackage.exe" + "\""
    args = "/S"
    proc = subprocess.Popen(updaterPath + args)
190 191
    # Wait to be killed
    out = proc.communicate()
Adriano da Luz's avatar
Adriano da Luz committed
192 193 194 195 196 197 198 199 200 201 202

# ==========================================
#       Main program
# ==========================================
# Open the logfile
log = Log()

# Delete old log files
try:
    deleteOldLogs()
except:
203
    log.write("WARNING: Failed to delete old log files.")
Adriano da Luz's avatar
Adriano da Luz committed
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

# Get Version from Windows Registry
try:
    version = getVersion()
except:
    log.write("ERROR(1): Failed to check Version in Windows registry.")
    log.close()
    sys.exit(1)

# Get INEP from Windows Registry

try:
    inep = collect.getINEP()
except:
    log.write("ERROR(2): Failed to check INEP in Windows registry.")
    log.close()
    sys.exit(2)

# Write inep and version conf files
try:
    writeVersionConf(version)
    writeInepConf(inep)
except:
    log.write("ERROR(3): Cannot write inep or version conf files.")
    log.close()
    sys.exit(3)

# Check if PROINFODATAPATH\bin\client.exe exists
if not (os.path.exists(PROINFODATAPATH + "\\bin\\client.exe")):
    log.write("ERROR(4): client.exe not found.")
    log.close()
    sys.exit(4)

# Check for updates
try:
    updatelink = verifyUpdate()
except clientError, e:
    log.write("ERROR(5): Failed to check for updates. Client returned " + str(e.code) + ".")
    log.write("Client message: " + str(e.errorMsg))
    log.close()
    sys.exit(5)

# If update is needed
if(updatelink):
    log.write("UPDATE: New update package available.")

    # Get remote version
    # The update link is in the format: "http://url/proinfodata-windows_x.x.x.exe
    # where x.x.x is the remote version
    newVersion = updatelink.split("_")[-1].replace(".exe", "")
    log.write("UPDATE: Updating from " + version + " to " + newVersion.strip() + ".")
    try:
        downloadUpdate(updatelink)
    except:
        log.write("ERROR(6): Failed to dowload update package.")
        log.close()
        sys.exit(6)

    # The update package will be an NSIS installer. This installer will kill
    # this process to overwrite the files. After that, the installer will call
    # this process again (now updated)
    try:
        log.write("UPDATE: Stopping for update process.")
        log.flush()
        callUpdater()
    except:
        log.write("ERROR(7): Failed to call the updater.")
        log.close()
        sys.exit(7)
else:
    log.write("UPDATE: No updates are available.")

# Collect data
try:
    collectData = collect.collect()
except:
    log.write("ERROR(8): Failed to collect data.")
    log.close()
    sys.exit(8)

# Write the collect-data.xml file
try:
    writeCollectData(collectData)
except:
    log.write("ERROR(9): Failed to write collect-data.xml.")
    log.close()
    sys.exit(9)

# Send data
try:
    sendData()
except clientError, e:
    log.write("ERROR(10): Failed to send data. Client returned " + str(e.code) + ".")
    log.write("Client message: " + str(e.errorMsg))
    log.close()
    sys.exit(10)
except:
301
    log.write("ERROR(11): Failed to get the proxy information from Windows registry.")
Adriano da Luz's avatar
Adriano da Luz committed
302 303 304 305 306 307 308
    log.close()
    sys.exit(11)

# If everything ran ok, exit with success status
log.write("EXIT(0): Success.")
log.close()
sys.exit(0)