コード例 #1
0
    def getProcessName(self):
        # Set Log
        log = SetLog()
        # Exception
        ex = ""
        # Mombre por default
        process = 'SQLDBproc'
        '''
            Version del Sistema Operativo
            2 = Linux
            1 = Windows
        '''
        so = 2
        # extrae la informacion del usuario del archivo de configuracion
        login = Login()
        user = login.returnUserData()

        # Url de la api REST para autenticarse
        url = const.IP_SERVER + '/DBProtector/DBBackUpProcess_GET?IdPlatform=' + str(
            so) + '&User='******'user'] + '&Password='******'password']

        try:
            # Realiza la peticion
            req = urllib2.Request(url)
            response = urllib2.urlopen(req)
        except urllib2.HTTPError, e:
            log.newLog("http_error", "E", e.fp.read())
コード例 #2
0
 def cloudSync(self):
     # Set Log
     log = SetLog()
     # Carga el archivo configuration.json
     file = os.path.join(const.LOCATION, const.CONFIGURATION_FILE)
     # Si el archivo existe...
     if (os.path.exists(file)):
         # lee los parametros de la api
         cloud = self.getCloudSync()
         # abre el archivo lee los parametros
         with open(file, 'r') as f:
             data = json.load(f)
         with open(file, 'w') as f:
             json.dump(
                 {
                     'userPath': data['userPath'],
                     'path': data['path'],
                     'time': cloud['UploadFrecuency'],
                     'time_type': data['time_type'],
                     'IdCustomer': data['IdCustomer'],
                     'user': data['user'],
                     'password': data['password'],
                     'tokenDropbox': data['tokenDropbox'],
                 }, f)
         thread.start_new_thread(self.sync, ())
         #self.sync()
     else:
         log.newLog("load_config_file", "E", "")
コード例 #3
0
	def cloudSync(self):
		# Set Log
		log = SetLog()
		# Carga el archivo configuration.json
		file = os.path.join(const.LOCATION, const.CONFIGURATION_FILE)
		# Si el archivo existe...
		if (os.path.exists(file)):
			# lee los parametros de la api
			cloud = self.getCloudSync()
			# abre el archivo lee los parametros
			with open(file, 'r') as f:
				data = json.load(f)
			with open(file, 'w') as f:
				json.dump({
					'userPath': data['userPath'],
					'path': data['path'],
					'time': cloud['UploadFrecuency'],
					'time_type': data['time_type'],
					'IdCustomer': data['IdCustomer'],
					'user': data['user'],
					'password': data['password'],
					'tokenDropbox': data['tokenDropbox'],
				}, f)
			thread.start_new_thread(self.sync, ())
			#self.sync()
		else:
			log.newLog("load_config_file", "E", "")
コード例 #4
0
 def isRunning(self):
     log = SetLog()
     proceso = 0
     '''
         contador, si encuentra al menos un proceso corriendo con el nombre recibido por la api,
         entonces devuelve true, si no devuelve falso
     '''
     # si el nombre del proceso no es nulo...
     if self.getProcessName():
         # Lista los procesos del sistema
         if psutil.pids():
             for proc in psutil.pids():
                 process = psutil.Process(proc)
                 # busca el proceso de respaldo, dentro de los procesos del sistema
                 if re.search(r"%s" % self.getProcessName(),
                              process.name()):
                     # si el proceso esta en "running" o "waiting" porpone la subida del archivo
                     if process.status() == "running" or process.status(
                     ) == "waiting":
                         proceso + 1
         if proceso > 0:
             return True
         else:
             return False
     else:
         log.newLog("process_incorrect", "E",
                    "BackgroundProcess.getProcessName()")
コード例 #5
0
    def getProcessName(self):
        # Set Log
        log = SetLog()
        # Exception
        ex = ""
        # Mombre por default
        process = 'SQLDBproc'
        '''
            Version del Sistema Operativo
            2 = Linux
            1 = Windows
        '''
        so = 2
        # extrae la informacion del usuario del archivo de configuracion
        login = Login()
        user = login.returnUserData()

        # Url de la api REST para autenticarse
        url = const.IP_SERVER + '/DBProtector/DBBackUpProcess_GET?IdPlatform=' + str(so) + '&User='******'user'] +'&Password='******'password']

        try:
            # Realiza la peticion
            req = urllib2.Request(url)
            response = urllib2.urlopen(req)
        except urllib2.HTTPError, e:
            log.newLog("http_error", "E", e.fp.read())
コード例 #6
0
	def rebootCron(self):
		# Set Log
		log = SetLog()
		# Este comando se utiliza para extraer el usuario que ejecutara el cron
		linux_user = "******"
		# lee el resultado del comando anterior
		p = os.popen(linux_user, "r")
		linux_user_value = p.readline()

		# crea el cron
		tab = CronTab(user=linux_user_value)
		# elimina cualquier cron previo con el comentario SCANDA_sync
		tab.remove_all(comment='SCANDA_init')
		# crea una nueva tarea en el cron, agrega el comentario SCANDA_sync, para poder ser identificado despues
		cron_job = tab.new("/usr/bin/dbprotector_scanda", comment="SCANDA_init")

		# configura el cron para que la aplicacion se inicie cada reinicio del sistema
		cron_job.every_reboot()

		# escribe y guarda el cron
		try:
			tab.write()
			# print tab.render()
			return True
		except:
			log.newLog("cron_error", "E", "")
			return False
コード例 #7
0
    def writePreferences(self, path, time, time_type, userPath):
        log = SetLog()
        # Carga el archivo configuration.json
        file = os.path.join(const.LOCATION, const.CONFIGURATION_FILE)
        # Si el archivo existe...
        if (os.path.exists(file)):
            # abre el archivo y guarda la variable 'path' del archivo json
            with open(file, 'r') as f:
                data = json.load(f)
            # escribe la nueva variable time en el archivo json junto con la variable value
            with open(file, 'w') as f:
                json.dump({
                    'userPath': userPath,
                    'path': path,
                    'time': time,
                    'time_type': time_type,
                    'IdCustomer': data['IdCustomer'],
                    'user': data['user'],
                    'password': data['password'],
                    'tokenDropbox': data['tokenDropbox'],
                }, f)

            # Guarda los cambios en el archivo de configuracion y genera el cron
            c = Cron()
            thread.start_new_tahread(c.sync, ())
            #c.sync()
            return True
        else:
            log.newLog("load_config_file", "E", "")
            return False
コード例 #8
0
    def rebootCron(self):
        # Set Log
        log = SetLog()
        # Este comando se utiliza para extraer el usuario que ejecutara el cron
        linux_user = "******"
        # lee el resultado del comando anterior
        p = os.popen(linux_user, "r")
        linux_user_value = p.readline()

        # crea el cron
        tab = CronTab(user=linux_user_value)
        # elimina cualquier cron previo con el comentario SCANDA_sync
        tab.remove_all(comment='SCANDA_init')
        # crea una nueva tarea en el cron, agrega el comentario SCANDA_sync, para poder ser identificado despues
        cron_job = tab.new("/usr/bin/dbprotector_scanda",
                           comment="SCANDA_init")

        # configura el cron para que la aplicacion se inicie cada reinicio del sistema
        cron_job.every_reboot()

        # escribe y guarda el cron
        try:
            tab.write()
            # print tab.render()
            return True
        except:
            log.newLog("cron_error", "E", "")
            return False
コード例 #9
0
    def updateSpace(self, user, spaceFile):
        log = SetLog()
        space = int(user["spaceUsed"]) + int(spaceFile)
        url = const.IP_SERVER + '/DBProtector/CustomerStorage_SET?UsedStorage=' + str(space) + '&User='******'user'] + '&Password='******'password']

        try:
            # Realiza la peticion
            req = urllib2.Request(url)
            response = urllib2.urlopen(req)
        except urllib2.HTTPError, e:
            log.newLog("http_error", "E", e.fp.read())
コード例 #10
0
    def setDownloadstatus(self, fileDownload, path, status):
        # logs
        log = SetLog()

        # Carga el status de la subida a nivel local
        file = os.path.join(const.LOCATION, const.STATUS_FILE)
        # Si el archivo existe...
        if (os.path.exists(file)):
            # guarda los datos anteriores
            with open(file, 'r') as f:
                data = json.load(f)
            # abre el archivo y escribe los datos
            with open(file, 'w') as f:
                json.dump(
                    {
                        'download': {
                            'file': fileDownload,
                            'path': path,
                            'status': status
                        },
                        'upload': data['upload']
                    }, f)

            if status == 2 or status == 0:
                print "sincronizado"

            else:
                from time import gmtime, strftime
                url = ""
                # extrae la info del user
                l = Login()
                user = l.returnUserData()
                # extrae la fecha actual formateada
                date = strftime("%Y%m%d%H%M%S", gmtime())

                # valida el status de la subida
                # 1 para carga iniciada
                if status == 1:
                    # i el chunk es de 5mb, entonces es el primero en subirse
                    url = const.IP_SERVER + '/DBProtector/FileTransaction_SET?User='******'user'] + '&Password='******'password'] + '&StartDate=' + date + '&ActualChunk=' + str(0) + '&TotalChunk=' + \
                          str(0) + '&Status=EnProgreso&FileName=' + fileDownload + '&TransactionType=5'
                elif status == 0:
                    # Url de la api REST para la subida de archivos
                    url = const.IP_SERVER + '/DBProtector/FileTransaction_DELETE?User='******'user'] + '&Password='******'password'] + '&FileName=' + fileDownload + '&TransactionType=5'
                try:
                    # Realiza la peticion
                    req = urllib2.Request(url)
                    response = urllib2.urlopen(req)
                except urllib2.HTTPError, e:
                    log.newLog("http_error", "E", e.fp.read())
コード例 #11
0
 def returnUserData(self):
     log = SetLog()
     # Datos del usuario
     l = Login()
     user = l.returnUserData()  # Url de la api REST para autenticarse
     url = const.IP_SERVER + '/DBProtector/Account_GET?User='******'user'] + '&Password='******'password']
     try:
         # Realiza la peticion
         req = urllib2.Request(url)
         response = urllib2.urlopen(req)
     except urllib2.HTTPError, e:
         log.newLog("http_error", "E", e.fp.read())
コード例 #12
0
    def setDownloadstatus(self, fileDownload, path, status):
        # logs
        log = SetLog()

        # Carga el status de la subida a nivel local
        file = os.path.join(const.LOCATION, const.STATUS_FILE)
        # Si el archivo existe...
        if (os.path.exists(file)):
            # guarda los datos anteriores
            with open(file, 'r') as f:
                data = json.load(f)
            # abre el archivo y escribe los datos
            with open(file, 'w') as f:
                json.dump({
                    'download': {
                        'file': fileDownload,
                        'path': path,
                        'status': status
                    },
                    'upload': data['upload']
                }, f)

            if status == 2 or status == 0:
                print "sincronizado"

            else:
                from time import gmtime, strftime
                url = ""
                # extrae la info del user
                l = Login()
                user = l.returnUserData()
                # extrae la fecha actual formateada
                date = strftime("%Y%m%d%H%M%S", gmtime())

                # valida el status de la subida
                # 1 para carga iniciada
                if status == 1:
                    # i el chunk es de 5mb, entonces es el primero en subirse
                    url = const.IP_SERVER + '/DBProtector/FileTransaction_SET?User='******'user'] + '&Password='******'password'] + '&StartDate=' + date + '&ActualChunk=' + str(0) + '&TotalChunk=' + \
                          str(0) + '&Status=EnProgreso&FileName=' + fileDownload + '&TransactionType=5'
                elif status == 0:
                    # Url de la api REST para la subida de archivos
                    url = const.IP_SERVER + '/DBProtector/FileTransaction_DELETE?User='******'user'] + '&Password='******'password'] + '&FileName=' + fileDownload + '&TransactionType=5'
                try:
                    # Realiza la peticion
                    req = urllib2.Request(url)
                    response = urllib2.urlopen(req)
                except urllib2.HTTPError, e:
                    log.newLog("http_error", "E", e.fp.read())
コード例 #13
0
    def downloadFile(self, file, path):
        from dropbox.client import DropboxClient
        log = SetLog()
        status = Status()
        # Usado para comprimir el archivo
        zip = Compress()
        # Extrae el nombre, la extension del archivo
        dir, name = os.path.split(file)
        # Archivo local donde se almacenara
        localFile = os.path.join(path, name)
        cliente = DropboxClient(self.TOKEN)
        thread.start_new_thread(status.setDownloadstatus, (name, path, 1,))
        with self.stopwatch('download'):
            try:
                out = open(localFile, 'wb')
                with self.stopwatch("download"):
                    with cliente.get_file(file) as f:
                        out.write(f.read())
            except dropbox.exceptions.HttpError as err:
                log.newLog("error_download", "T", file)
                return False
        out.close()

        if os.path.exists(localFile):
            thread.start_new_thread(status.setDownloadstatus, (name, path, 2,))
            zip.uncompress(localFile)
            log.newLog("success_download", "T", file)
            thread.start_new_thread(status.setDownloadstatus, (name, path, 0,))
            return True
        else:
            log.newLog("error_download", "T", file)
            return False
コード例 #14
0
    def getDownloadStatus(self):
        # logs
        log = SetLog()

        file = os.path.join(const.LOCATION, const.STATUS_FILE)
        # Si el archivo existe...
        if (os.path.exists(file)):
            # abre el archivo y lee los datos
            with open(file, 'r') as f:
                data = json.load(f)
            download = data['download']
        else:
            log.newLog("error_file_status", "E", "")
        return download
コード例 #15
0
    def getDownloadStatus(self):
        # logs
        log = SetLog()

        file = os.path.join(const.LOCATION, const.STATUS_FILE)
        # Si el archivo existe...
        if (os.path.exists(file)):
            # abre el archivo y lee los datos
            with open(file, 'r') as f:
                data = json.load(f)
            download = data['download']
        else:
            log.newLog("error_file_status", "E", "")
        return download
コード例 #16
0
    def getData(self):
        extensiones = []
        log = SetLog()
        l = Login()
        user = l.returnUserData()
        p = Preferences()
        spaceData = p.returnUserData()
        url = const.IP_SERVER + '/DBProtector/Extensions_GET?User='******'user'] + '&Password='******'password']

        try:
            # Realiza la peticion
            req = urllib2.Request(url)
            response = urllib2.urlopen(req)
        except urllib2.HTTPError, e:
            log.newLog("http_error", "E", e.fp.read())
コード例 #17
0
 def getLocalFilesList(self, ruta, filtro):
     files = []
     log = SetLog()
     try:
         # lista de archivos completa
         ar = [file for file in os.listdir(ruta) if os.path.isfile(os.path.join(ruta, file))]
         # valida los archivos por extension permitida
         ar = [file for file in ar if self.filtradoPorExtension(file, filtro)]
         ar = [file for file in ar if self.checkNameSintax(file)]
         for archivo in ar:
             files.append(archivo)
     except:
         log.newLog("error_path", "E", "")
         files = None
     return files
コード例 #18
0
 def uncompress(self, file):
     log = SetLog()
     if os.path.exists(file):
         path, name = os.path.split(file)
         with zipfile.ZipFile(file, "r") as f:
             for name in f.namelist():
                 f.extract(name, path, self.createPassword())
         # elimina el .zip despues de haber sido extraido
         if os.remove(file):
             return True
         else:
             log.newLog("error_remove_file", "E", "Compress.uncompress()")
             return True
     else:
         return False
コード例 #19
0
 def readConf(self):
     # Set Log
     log = SetLog()
     # Carga el archivo configuration.json
     file = os.path.join(const.LOCATION, const.CONFIGURATION_FILE)
     # Si el archivo existe...
     if (os.path.exists(file)):
         # abre el archivo lee los parametros
         with open(file, 'r') as f:
             data = json.load(f)
             self.time = data['time']
             self.time = str(self.time)
             self.time_type = data['time_type']
     else:
         log.newLog("load_config_file", "E", "")
     # Comando que ejecutara el cron, es el archivo que realizara los respaldos
     self.cron = "/usr/bin/dbprotector_sync"
コード例 #20
0
	def readConf(self):
		# Set Log
		log = SetLog()
		# Carga el archivo configuration.json
		file = os.path.join(const.LOCATION, const.CONFIGURATION_FILE)
		# Si el archivo existe...
		if ( os.path.exists(file) ):
			# abre el archivo lee los parametros
			with open(file, 'r') as f:
				data = json.load(f)
				self.time = data['time']
				self.time = str(self.time)
				self.time_type = data['time_type']
		else :
			log.newLog("load_config_file", "E", "")
		# Comando que ejecutara el cron, es el archivo que realizara los respaldos
		self.cron = "/usr/bin/dbprotector_sync"
コード例 #21
0
    def prepareExternalPath(self, args):
        p = Preferences()
        log = SetLog()
        path = p.returnExternalPath()
        try:
            while len(os.listdir(path)) >= args['FileHistoricalNumber']:
                # lista de archivos completa
                files = (os.path.join(path, file) for file in os.listdir(path))
                files = ((os.stat(path), path) for path in files)
                # fecha de modificacion
                files = ((stat[ST_CTIME], path)
                           for stat, path in files if S_ISREG(stat[ST_MODE]))
                # ordena de mas viejo al mas nuevo
                files = sorted(files)
                os.remove(files[0][1])

        except:
            log.newLog("error_path", "E", "")
コード例 #22
0
    def getUploadStatus(self):
        # logs
        log = SetLog()

        file = os.path.join(const.LOCATION, const.STATUS_FILE)
        # Si el archivo existe...
        if (os.path.exists(file)):
            # abre el archivo y lee los datos
            with open(file, 'r') as f:
                data = json.load(f)
            upload = data['upload']
            if upload['status'] != 0:
                if upload['chunk'] == 0 or upload['total'] == 0:
                    upload['chunk'] = 0
                    upload['total'] = 0
                else:
                    upload['chunk'] = self.returnPercent(int(upload['total']), int(upload['chunk']))
                    upload['total'] = (int(upload['total']) / 1024) / 1024
        else:
            log.newLog("error_file_status", "E", "")
        return upload
コード例 #23
0
 def returnExternalPath(self):
     log = SetLog()
     # Carga el archivo configuration.json
     file = os.path.join(const.LOCATION, const.CONFIGURATION_FILE)
     # Si el archivo existe...
     if (os.path.exists(file)):
         # abre el archivo y guarda la variable 'path' del archivo json
         with open(file, 'r') as f:
             data = json.load(f)
         if not data['userPath']:
             newPath = os.path.join(data['path'], "respaldados")
             if not os.path.exists(newPath):
                 os.makedirs(newPath)
             return newPath
         else:
             if not os.path.exists(data['userPath']):
                 os.makedirs(data['userPath'])
             return data['userPath']
     else:
         log.newLog("load_config_file", "E", "")
         return ''
コード例 #24
0
 def sync(self):
     log = SetLog()
     if self.checkUpload():
         status = Status()
         background = BackgroundProcess()
         # Usado para comprimir el archivo
         zip = Compress()
         # Extrae la info del usuario
         user = self.getData()
         # Lista de archivos validos para ser subidos
         files = self.getLocalFilesList(user["path"], user["ext"])
         if not files:
             thread.start_new_thread(status.setUploadStatus, ("file.bak", 1, 1, 0,))
         else:
             # si hay mas respaldos de los permitidos los elimina
             self.historicalCloud()
             for file in files:
                 if 1:
                 #if not background.isRunning():
                     name, ext = file.split(".")
                     file = os.path.join(user["path"], file)
                     # Comprime el archivo
                     # actualiza el estado de la aplicacion a cifrando
                     thread.start_new_thread(status.setUploadStatus, (name + ".zip", 1, 1, 3,))
                     if zip.compress(file):
                         # Datos del archivo subido
                         data = self.uploadFile(name + "." + ext + ".zip")
                         # que se hace con el archivo?
                         self.actionAfterUpload(name + "." + ext)
                         # Elimina el archivo, si no se elimino
                         if os.path.isfile(file):
                             os.remove(file)
                         # actualiza el estado de la aplicacion a sincronizado
                         thread.start_new_thread(status.setUploadStatus, (file, 1, 1, 2,))
                     else:
                         if os.path.isfile(file):
                             os.remove(file)
                         log.newLog("error_compress", "T", "")
                 else:
                     log.newLog("background_exists", "T", "")
         '''
             Una vez que se han terminado las subidas, se sincroniza con la api
             para actualizar la frecuencia de respaldo y generar un nuevo cron
         '''
         c = Cron()
         thread.start_new_thread(c.cloudSync, ())
         #c.cloudSync()
     else:
         print "Existe otra subida en proceso"
         log.newLog("error_upload_exist", "T", "")
コード例 #25
0
	def removeCrons(self):
		log = SetLog()
		# Este comando se utiliza para extraer el usuario que ejecutara el cron
		linux_user = "******"
		# lee el resultado del comando anterior
		p = os.popen(linux_user, "r")
		linux_user_value = p.readline()

		tab = CronTab(user=linux_user_value)
		# elimina cualquier cron previo con el comentario SCANDA_sync
		tab.remove_all(comment='SCANDA_init')
		# elimina cualquier cron previo con el comentario SCANDA_sync
		tab.remove_all(comment='SCANDA_sync')

		# escribe y guarda el cron
		try:
			tab.write()
			# print tab.render()
			return True
		except:
			log.newLog("cron_error", "E", "")
			return False
コード例 #26
0
    def getUploadStatus(self):
        # logs
        log = SetLog()

        file = os.path.join(const.LOCATION, const.STATUS_FILE)
        # Si el archivo existe...
        if (os.path.exists(file)):
            # abre el archivo y lee los datos
            with open(file, 'r') as f:
                data = json.load(f)
            upload = data['upload']
            if upload['status'] != 0:
                if upload['chunk'] == 0 or upload['total'] == 0:
                    upload['chunk'] = 0
                    upload['total'] = 0
                else:
                    upload['chunk'] = self.returnPercent(
                        int(upload['total']), int(upload['chunk']))
                    upload['total'] = (int(upload['total']) / 1024) / 1024
        else:
            log.newLog("error_file_status", "E", "")
        return upload
コード例 #27
0
	def sync(self):
		# Set Log
		log = SetLog()
		self.readConf()
		# Este comando se utiliza para extraer el usuario que ejecutara el cron
		linux_user = "******"
		# lee el resultado del comando anterior
		p = os.popen(linux_user, "r")
		linux_user_value = p.readline()

		# crea el cron
		tab = CronTab(user=linux_user_value)
		# elimina cualquier cron previo con el comentario SCANDA_sync
		tab.remove_all(comment='SCANDA_sync')
		# crea una nueva tarea en el cron, agrega el comentario SCANDA_sync, para poder ser identificado despues
		cron_job = tab.new(self.cron, comment="SCANDA_sync")

		# datos de la frecuencia de respaldo
		dias = 0
		# pasa las horas a horas y dias
		if self.time > 23:
			while self.time > 23:
				dias += 1
				self.time -= 24

		# Agrega las frecuencias de respaldo
		if dias > 0:
			cron_job.day.every(dias)
		if self.time > 0:
			cron_job.hour.every(self.time)

		# escribe y guarda el cron
		try:
			tab.write()
			#print tab.render()
			return True
		except:
			log.newLog("cron_error", "E", "")
			return False
コード例 #28
0
    def sync(self):
        # Set Log
        log = SetLog()
        self.readConf()
        # Este comando se utiliza para extraer el usuario que ejecutara el cron
        linux_user = "******"
        # lee el resultado del comando anterior
        p = os.popen(linux_user, "r")
        linux_user_value = p.readline()

        # crea el cron
        tab = CronTab(user=linux_user_value)
        # elimina cualquier cron previo con el comentario SCANDA_sync
        tab.remove_all(comment='SCANDA_sync')
        # crea una nueva tarea en el cron, agrega el comentario SCANDA_sync, para poder ser identificado despues
        cron_job = tab.new(self.cron, comment="SCANDA_sync")

        # datos de la frecuencia de respaldo
        dias = 0
        # pasa las horas a horas y dias
        if self.time > 23:
            while self.time > 23:
                dias += 1
                self.time -= 24

        # Agrega las frecuencias de respaldo
        if dias > 0:
            cron_job.day.every(dias)
        if self.time > 0:
            cron_job.hour.every(self.time)

        # escribe y guarda el cron
        try:
            tab.write()
            #print tab.render()
            return True
        except:
            log.newLog("cron_error", "E", "")
            return False
コード例 #29
0
    def removeCrons(self):
        log = SetLog()
        # Este comando se utiliza para extraer el usuario que ejecutara el cron
        linux_user = "******"
        # lee el resultado del comando anterior
        p = os.popen(linux_user, "r")
        linux_user_value = p.readline()

        tab = CronTab(user=linux_user_value)
        # elimina cualquier cron previo con el comentario SCANDA_sync
        tab.remove_all(comment='SCANDA_init')
        # elimina cualquier cron previo con el comentario SCANDA_sync
        tab.remove_all(comment='SCANDA_sync')

        # escribe y guarda el cron
        try:
            tab.write()
            # print tab.render()
            return True
        except:
            log.newLog("cron_error", "E", "")
            return False
コード例 #30
0
 def isRunning(self):
     log = SetLog()
     proceso = 0
     '''
         contador, si encuentra al menos un proceso corriendo con el nombre recibido por la api,
         entonces devuelve true, si no devuelve falso
     '''
     # si el nombre del proceso no es nulo...
     if self.getProcessName():
         # Lista los procesos del sistema
         if psutil.pids():
             for proc in psutil.pids():
                 process = psutil.Process(proc)
                 # busca el proceso de respaldo, dentro de los procesos del sistema
                 if re.search(r"%s" % self.getProcessName(), process.name()):
                     # si el proceso esta en "running" o "waiting" porpone la subida del archivo
                     if process.status() == "running" or process.status() == "waiting":
                         proceso+1
         if proceso > 0:
             return True
         else:
             return False
     else:
         log.newLog("process_incorrect", "E", "BackgroundProcess.getProcessName()")
コード例 #31
0
    def setUploadStatus(self, fileUploaded, chunk, total, status):
        # logs
        log = SetLog()

        # Carga el status de la subida a nivel local
        file = os.path.join(const.LOCATION, const.STATUS_FILE)
        # Si el archivo existe...
        if (os.path.exists(file)):
            #guarda los datos anteriores
            with open(file, 'r') as f:
                data = json.load(f)
            # abre el archivo y escribe los datos
            with open(file, 'w') as f:
                json.dump(
                    {
                        'upload': {
                            'file': fileUploaded,
                            'chunk': chunk,
                            'total': total,
                            'status': status
                        },
                        'download': data['download']
                    }, f)

        else:
            log.newLog("error_file_status", "E", "")
        '''
            0 = Subida terminada
            1 = Iniciando subida
            2 = Subiendo
            3 = Comprimiendo
            Si es diferente de 3 envia un log a la API
        '''
        if status == 3 or status == 0:
            print "sincronizado"

        else:
            from time import gmtime, strftime
            url = ""
            # extrae la infor del user
            l = Login()
            user = l.returnUserData()
            # extrae la fecha actual formateada
            date = strftime("%Y%m%d%H%M%S", gmtime())

            # valida el status de la subida
            # 1 para carga iniciada
            if status == 1:
                #i el chunk es de 5mb, entonces es el primero en subirse
                if chunk <= const.CHUNK_SIZE:  # tamano del chunk de 5MB
                    # Url de la api REST para la subida de archivos
                    url = const.IP_SERVER + '/DBProtector/FileTransaction_SET?User='******'user'] + '&Password='******'password'] + '&StartDate=' + date + '&ActualChunk=' + str(chunk) + '&TotalChunk=' + \
                          str(total) + '&Status=EnProgreso&FileName=' + fileUploaded + '&TransactionType=1'
                # si el es diferente de 5 mb, se esta actualizando
                else:
                    # Url de la api REST para la subida de archivos
                    url = const.IP_SERVER + '/DBProtector/FileTransaction_UPDATE?User='******'user'] + '&Password='******'password'] + '&ActualChunk='+str(chunk)+'&Status=EnProgreso&FileName=' + fileUploaded + '&TransactionType=1'
            elif status == 2:
                # Url de la api REST para la subida de archivos
                url = const.IP_SERVER + '/DBProtector/FileTransaction_DELETE?User='******'user'] + '&Password='******'password'] + '&FileName=' + fileUploaded + '&TransactionType=1'

            try:
                # Realiza la peticion
                req = urllib2.Request(url)
                response = urllib2.urlopen(req)
            except urllib2.HTTPError, e:
                log.newLog("http_error", "E", e.fp.read())
コード例 #32
0
    def setUploadStatus(self, fileUploaded, chunk, total, status):
        # logs
        log = SetLog()

        # Carga el status de la subida a nivel local
        file = os.path.join(const.LOCATION, const.STATUS_FILE)
        # Si el archivo existe...
        if (os.path.exists(file)):
            #guarda los datos anteriores
            with open(file, 'r') as f:
                data = json.load(f)
            # abre el archivo y escribe los datos
            with open(file, 'w') as f:
                json.dump({
                    'upload': {
                        'file': fileUploaded,
                        'chunk': chunk,
                        'total': total,
                        'status': status
                    },
                    'download': data['download']
                }, f)

        else:
            log.newLog("error_file_status", "E", "")

        '''
            0 = Subida terminada
            1 = Iniciando subida
            2 = Subiendo
            3 = Comprimiendo
            Si es diferente de 3 envia un log a la API
        '''
        if status == 3 or status == 0:
            print "sincronizado"

        else:
            from time import gmtime, strftime
            url = ""
            # extrae la infor del user
            l = Login()
            user = l.returnUserData()
            # extrae la fecha actual formateada
            date = strftime("%Y%m%d%H%M%S", gmtime())

            # valida el status de la subida
            # 1 para carga iniciada
            if status == 1:
                #i el chunk es de 5mb, entonces es el primero en subirse
                if chunk <= const.CHUNK_SIZE: # tamano del chunk de 5MB
                    # Url de la api REST para la subida de archivos
                    url = const.IP_SERVER + '/DBProtector/FileTransaction_SET?User='******'user'] + '&Password='******'password'] + '&StartDate=' + date + '&ActualChunk=' + str(chunk) + '&TotalChunk=' + \
                          str(total) + '&Status=EnProgreso&FileName=' + fileUploaded + '&TransactionType=1'
                # si el es diferente de 5 mb, se esta actualizando
                else:
                    # Url de la api REST para la subida de archivos
                    url = const.IP_SERVER + '/DBProtector/FileTransaction_UPDATE?User='******'user'] + '&Password='******'password'] + '&ActualChunk='+str(chunk)+'&Status=EnProgreso&FileName=' + fileUploaded + '&TransactionType=1'
            elif status == 2:
                # Url de la api REST para la subida de archivos
                url = const.IP_SERVER + '/DBProtector/FileTransaction_DELETE?User='******'user'] + '&Password='******'password'] + '&FileName=' + fileUploaded + '&TransactionType=1'

            try:
                # Realiza la peticion
                req = urllib2.Request(url)
                response = urllib2.urlopen(req)
            except urllib2.HTTPError, e:
                log.newLog("http_error", "E", e.fp.read())
コード例 #33
0
    def uploadFile(self, file):
        log = SetLog()
        status = Status()
        # Extrae los datos del usuario
        user = self.getData()
        # Si es un archivo / existe
        fullFile = os.path.join(user['path'], file)
        if os.path.isfile(fullFile):
            # Tamano en bytes
            size_bytes = os.path.getsize(fullFile)
            # Tamano en MB
            size = float(float(int(size_bytes) / 1024) / 1024)
            # Si el tamano del archivo es menor que el tamano disponible
            if size < user['freeSpace']:
                # Extrae el nombre, la extension y la fecha de modificacion del archivo
                name, ext = os.path.splitext(file)
                ext = ext.replace(".", "")
                mtime = os.path.getmtime(fullFile)
                # si la extension del archivo es valida...
                if ext in user['ext']:
                    # abre una sesion
                    dbx = dropbox.Dropbox(self.TOKEN)
                    # Ruta donde se almacenara
                    dest = self.pathToUpload(user['IdCustomer']) + name + "." + ext
                    # Abre el archivo
                    with open(fullFile, 'rb') as f:
                        # Si el archivo es mas grande que CHUNK_SIZE
                        if os.path.getsize(fullFile) <= const.CHUNK_SIZE:
                            data = f.read()
                            # Inicia la subida
                            with self.stopwatch('upload %d MB' % len(data)):
                                try:
                                    res = dbx.files_upload(data, dest)
                                    # "borrando archivo: "
                                    os.remove(fullFile)
                                    # Notifica a la API
                                    log.newLog("success_upload", "T", file)
                                    # Muestra al usuario, que se subio el archivo
                                    #status.setUploadStatus(file, str(f.tell()), str(size_bytes), 2)
                                    thread.start_new_thread(status.setUploadStatus, (file, str(f.tell()), str(size_bytes), 2,))
                                    # Actualiza el espacio disponible del usuario
                                    self.updateSpace(user, size)
                                    return res
                                except dropbox.exceptions.ApiError as err:
                                    # eliminar archivo
                                    os.remove(fullFile)
                                    log.newLog("error_upload", "T", "")
                                    # los logs de dropbox son demasiado grandes para ser enviados como log
                                    #print err
                                    return None
                            #return res
                        # Subida de archivos Grandes
                        else:
                            with self.stopwatch('upload %d MB' % size):
                                try:
                                    # Sube el archivo por bloques, maximo 150 mb
                                    upload_session_start_result = dbx.files_upload_session_start(f.read(const.CHUNK_SIZE))
                                    cursor = dropbox.files.UploadSessionCursor(session_id=upload_session_start_result.session_id,
                                                                               offset=f.tell())
                                    commit = dropbox.files.CommitInfo(path=dest)

                                    while f.tell() < size_bytes:
                                        # tamano subido y id de la sesion de subida
                                        if ((size_bytes - f.tell()) <= const.CHUNK_SIZE):
                                            # Muestra al usuario que se esta subiendo
                                            #status.setUploadStatus(file, f.tell(), size_bytes, 2)
                                            thread.start_new_thread(status.setUploadStatus,
                                                                    (file, str(f.tell()), str(size_bytes), 2,))
                                            res = dbx.files_upload_session_finish(f.read(const.CHUNK_SIZE), cursor, commit)
                                            self.updateSpace(user, size)
                                            # "borrando archivo: "
                                            os.remove(fullFile)
                                            # Notifica a la API
                                            log.newLog("success_upload", "T", "")
                                        else:
                                            # Muestra al usuario que se esta subiendo
                                            #status.setUploadStatus(file, f.tell(), size_bytes, 1)
                                            thread.start_new_thread(status.setUploadStatus,
                                                                    (file, str(f.tell()), str(size_bytes), 1,))
                                            dbx.files_upload_session_append(f.read(const.CHUNK_SIZE), cursor.session_id, cursor.offset)
                                            cursor.offset = f.tell()
                                except dropbox.exceptions.ApiError as err:
                                    # "borrando archivo: "
                                    os.remove(fullFile)
                                    log.newLog("error_upload", "T", "")
                                    return None
                else:
                    # extension invalida
                    log.newLog("error_ext", "T", ext)
                    return None
            else:
                log.newLog("error_size", "T", "")
                # Espacio insuficiente
                return None
        else:
            # Archivo invalido
            log.newLog("error_404", "T", file)
            return None