Ejemplo n.º 1
0
     if r<0:
         print "Error getting hosts from database", c
         exit(-1)
     else:
         for host in c:
             host['image_path'] = '/opt/VNF/images/openvim'
             thread = ht.host_thread(name=host['name'], user=host['user'], host=host['ip_name'], db=db_of, db_lock=db_lock,
                     test=host_test_mode, image_path=config_dic['image_path'], version=config_dic['version'],
                     host_id=host['uuid'], develop_mode=host_develop_mode, develop_bridge_iface=host_develop_bridge_iface  )
             thread.start()
             config_dic['host_threads'][ host['uuid'] ] = thread
             
         
     
 #Create thread to listen to web requests
     http_thread = httpserver.httpserver(db_http, 'http', config_dic['http_host'], config_dic['http_port'], False, config_dic)
     http_thread.start()
     
     if 'http_admin_port' in config_dic: 
         db_http = create_database_connection(config_dic)
         http_thread_admin = httpserver.httpserver(db_http, 'http-admin', config_dic['http_host'], config_dic['http_admin_port'], True)
         http_thread_admin.start()
     else:
         http_thread_admin = None
     time.sleep(1)      
     print 'Waiting for http clients'
     print 'openvimd ready'
     print '===================='
     sys.stdout.flush()
     
     #TODO: Interactive console would be nice here instead of join or sleep
Ejemplo n.º 2
0
                    host=host["ip_name"],
                    db=db_of,
                    db_lock=db_lock,
                    test=host_test_mode,
                    image_path=config_dic["image_path"],
                    version=config_dic["version"],
                    host_id=host["uuid"],
                    develop_mode=host_develop_mode,
                    develop_bridge_iface=host_develop_bridge_iface,
                )
                thread.start()
                config_dic["host_threads"][host["uuid"]] = thread

        # Create thread to listen to web requests
        http_thread = httpserver.httpserver(
            db_http, "http", config_dic["http_host"], config_dic["http_port"], False, config_dic
        )
        http_thread.start()

        if "http_admin_port" in config_dic:
            db_http = create_database_connection(config_dic)
            http_thread_admin = httpserver.httpserver(
                db_http, "http-admin", config_dic["http_host"], config_dic["http_admin_port"], True
            )
            http_thread_admin.start()
        else:
            http_thread_admin = None
        time.sleep(1)
        print "Waiting for http clients"
        print "openvimd ready"
        print "===================="
Ejemplo n.º 3
0
        # Initialize DB connection
        mydb = nfvo_db.nfvo_db();
        if mydb.connect(global_config['db_host'], global_config['db_user'], global_config['db_passwd'], global_config['db_name']) == -1:
            print "Error connecting to database", global_config['db_name'], "at", global_config['db_user'], "@", global_config['db_host']
            exit(-1)
        r = mydb.get_db_version()
        if r[0]<0:
            print "Error DATABASE is not a MANO one or it is a '0.0' version. Try to upgrade to version '%s' with './database_utils/migrate_mano_db.sh'" % database_version
            exit(-1)
        elif r[1]!=database_version:
            print "Error DATABASE wrong version '%s'. Try to upgrade/downgrade to version '%s' with './database_utils/migrate_mano_db.sh'" % (r[1], database_version)
            exit(-1)
        
        nfvo.global_config=global_config
        
        httpthread = httpserver.httpserver(mydb, False, global_config['http_host'], global_config['http_port'])
        
        httpthread.start()
        if 'http_admin_port' in global_config: 
            httpthreadadmin = httpserver.httpserver(mydb, True, global_config['http_host'], global_config['http_admin_port'])
            httpthreadadmin.start()
        time.sleep(1)      
        print 'Waiting for http clients'
        print 'openmanod ready'
        print '===================='
        time.sleep(20)
        sys.stdout.flush()

        #TODO: Interactive console must be implemented here instead of join or sleep

        #httpthread.join()
Ejemplo n.º 4
0
                    user=host['user'],
                    host=host['ip_name'],
                    db=db_of,
                    db_lock=db_lock,
                    test=host_test_mode,
                    image_path=config_dic['image_path'],
                    version=config_dic['version'],
                    host_id=host['uuid'],
                    develop_mode=host_develop_mode,
                    develop_bridge_iface=host_develop_bridge_iface)
                thread.start()
                config_dic['host_threads'][host['uuid']] = thread

    #Create thread to listen to web requests
        http_thread = httpserver.httpserver(db_http, 'http',
                                            config_dic['http_host'],
                                            config_dic['http_port'], False,
                                            config_dic)
        http_thread.start()

        if 'http_admin_port' in config_dic:
            db_http = create_database_connection(config_dic)
            http_thread_admin = httpserver.httpserver(
                db_http, 'http-admin', config_dic['http_host'],
                config_dic['http_admin_port'], True)
            http_thread_admin.start()
        else:
            http_thread_admin = None
        time.sleep(1)
        logger.info('Waiting for http clients')
        print 'openvimd ready'
        print '===================='
Ejemplo n.º 5
0
	print 'pid ',pid,'finished'
	
	

def synchronous():
	for i in range(1,10):
		fetch(i)

def asynchronous():
	threads = []
	for i in range(1,10):
		threads.append(general_common.gevent.spawn(fetch, i))
	general_common.gevent.joinall(threads)

print('Synchronous:')
#synchronous()

print('Asynchronous:')
asynchronous()



'''

if __name__ == '__main__':
    logger_init('../conf/logger.conf', ['root', 'example01'])
    resource.resource_singleton()
    rollback_task.start_warn_rollback()
    mysvr = httpserver.httpserver()
    mysvr.start_server()
Ejemplo n.º 6
0
#!/usr/bin/python
# -*- coding: UTF-8 -*-

import httpserver

httpserver.httpserver("127.0.0.1",8008,"haroroda")
Ejemplo n.º 7
0
                'db_name'], "at", global_config['db_user'], "@", global_config[
                    'db_host']
            exit(-1)
        r = mydb.get_db_version()
        if r[0] < 0:
            print "Error DATABASE is not a MANO one or it is a '0.0' version. Try to upgrade to version '%s' with './database_utils/migrate_mano_db.sh'" % database_version
            exit(-1)
        elif r[1] != database_version:
            print "Error DATABASE wrong version '%s'. Try to upgrade/downgrade to version '%s' with './database_utils/migrate_mano_db.sh'" % (
                r[1], database_version)
            exit(-1)

        nfvo.global_config = global_config

        httpthread = httpserver.httpserver(mydb, False,
                                           global_config['http_host'],
                                           global_config['http_port'])

        httpthread.start()
        if 'http_admin_port' in global_config:
            httpthreadadmin = httpserver.httpserver(
                mydb, True, global_config['http_host'],
                global_config['http_admin_port'])
            httpthreadadmin.start()
        time.sleep(1)
        print 'Waiting for http clients'
        print 'openmanod ready'
        print '===================='
        time.sleep(20)
        sys.stdout.flush()
Ejemplo n.º 8
0
UPLOAD_FOLDER = DOWNLOAD_FOLDER

#creates clean directory to store torrents
try:
	shutil.rmtree(DOWNLOAD_FOLDER)
except OSError:
	pass
os.mkdir(DOWNLOAD_FOLDER)

# These distributions have easy static links for their latest torrent downloads

# Download Raspian from a static link
scraper_object.downloadfile('http://downloads.raspberrypi.org/raspbian_latest.torrent',DOWNLOAD_FOLDER)
scraper_object.downloadfile('http://downloads.raspberrypi.org/raspbian_lite_latest.torrent',DOWNLOAD_FOLDER)
#Download Debian from the "current" folder
scraper_object.scrape('http://cdimage.debian.org/debian-cd/current/amd64/bt-cd/','netinst','true',DOWNLOAD_FOLDER)
#download Arch from the "latest" folder
scraper_object.scrape('http://mirror.rackspace.com/archlinux/iso/latest/','torrent','true',DOWNLOAD_FOLDER)

# These distributions require us to scrape their website to find their latest torrent downloads

# Download Ubuntu
scraper_object.scrape('http://www.ubuntu.com/download/alternative-downloads',"download-torrent",'false',DOWNLOAD_FOLDER)

######################################
# Start simple http server           #
######################################

httpserver_object = httpserver.httpserver(DOWNLOAD_FOLDER)

Ejemplo n.º 9
0
	def detect(self):	

		self.log("Start detection thread")
		### open cam ###
		cap = vc.VideoCapture(self._videoInput, self).capture
		if cap == None:
			self.log("Can't open camera!")
			self.active = False
			return
		
		cap.setFPS(self._fps)
		cap.setVideoSize(self._videoSize)
		cap.setBin(self._bin)
		cap.setGain(self._gain)
		
		
		### init ###
		frame, ts = cap.getFrame()
		
		if not frame:
			self.log("Error reading first frame")
			self.active = False
			return
		frameSize = cv.GetSize(frame)
		
		darkframe = None
		if self._darkframe:
			try:
				darkframe = cv.LoadImage(self._darkframe)
				if frameSize != cv.GetSize(darkframe):
					darkframe = None
					self.log("Darkframe has wrong size")
			except:
				self.log("Darkframe not found")
				
		mask = None
		'''
		if self._mask:
			try:
				tmp = cv.LoadImage(self._mask)
				mask = cv.CreateImage( frameSize, cv.IPL_DEPTH_8U, 1)
				cv.CvtColor( tmp, mask, cv.CV_RGB2GRAY )
				if frameSize != cv.GetSize(mask):
					raise Exception();
			except:
				self.log("Mask not found or wrong size")
		'''
		small, smallSize = self.workingThumb(frame, frameSize)
		runAvg = cv.CreateImage( smallSize, cv.IPL_DEPTH_32F, small.channels)
		runAvgDisplay = cv.CreateImage(smallSize, small.depth, small.channels)
		differenceImg = cv.CreateImage(smallSize, small.depth, small.channels)
		grayImg = cv.CreateImage(smallSize, cv.IPL_DEPTH_8U, 1)
		historyBuffer = imagestack.Imagestack(self._prevFrames)
		capbuf = None
		videoGap = self._maxVideoGap
		postFrames = 0
		frameCount = 1
		detect = False
		newVideo = True
		
		### testwindow
		if self._showWindow:
			self.log("Show window")
			cv.NamedWindow("Thread " + str(self._thread), 1)
			
		### server
		if self._runServer:
			self.log("Start Server on port %d" % self._serverPort)
			self._server = httpserver.httpserver(self._serverPort)

		### capture loop ###
		while self._run:
			frame, ts = cap.getFrame()
			if ts == None:
				ts = time.time()
				
			### create small image for detection
			small, smallSize = self.workingThumb(frame, frameSize)
			
			videoGap += 1

			if small:
				frameCount += 1

				if 1/float(frameCount) < self._avgLevel and not detect:
					self.log("start detection")
					detect = True
				
				### substract darkframe
				if darkframe:
					cv.Sub( frame, darkframe, frame )
	
				if self._deNoiseLevel > 0:
					cv.Smooth( small, small, cv.CV_MEDIAN, self._deNoiseLevel)
				cv.RunningAvg( small, runAvg, self._avgLevel, mask )
				cv.ConvertScale( runAvg, runAvgDisplay, 1.0, 0.0 )
				cv.AbsDiff( small, runAvgDisplay, differenceImg )
				
				if differenceImg.depth == grayImg.depth:
					grayImg = differenceImg
				else:
					cv.CvtColor( differenceImg, grayImg, cv.CV_RGB2GRAY )
				cv.Threshold( grayImg, grayImg, self._detectThresh, 255, cv.CV_THRESH_BINARY )
				contour = cv.FindContours( grayImg, cv.CreateMemStorage(0), cv.CV_RETR_EXTERNAL, cv.CV_CHAIN_APPROX_SIMPLE)	
				

				## draw bounding rect
				while contour:
					bounding_rect = cv.BoundingRect( list(contour) )
					area = bounding_rect[2]*bounding_rect[3]
					if area > self._minRectArea and area < self._maxRectArea and detect:
						videoGap = 0
						#print(str(area))
						self.log("motion detected...")
						if self._drawRect:
							self.drawBoundingRect(frame, bounding_rect, smallSize = smallSize)

					contour = contour.h_next()
		
				## add text notations
				ms = "%04d" % int( (ts-int(ts)) * 10000 )
				t = time.strftime("%Y-%m-%d %H:%M:%S." + ms + " UTC", time.gmtime(ts))
				frame = self.addText(frame, self._texttl, t)

				
				## save / show frame
				if videoGap < self._maxVideoGap:
					if newVideo:
						self.log("Found motion, start capturing")
						capbuf = []
						newVideo = False						
						directory = os.path.join(self._videoDir,
											"%d/%02d/%s" % (time.gmtime(ts).tm_year, time.gmtime(ts).tm_mon, t))

						if not self.isWriteable(directory):
							self._log(directory + "is not writeable!")
							self._run = False
							continue

						capbuf.extend(historyBuffer.getImages())

					capbuf.append({'img' : frame, 'time' : t})
				else:
					if postFrames < self._postFrames and not newVideo:
						capbuf.append({'img' : frame, 'time' : t})
						postFrames += 1
					elif not newVideo:
						self.log("Stop capturing")
						### write images to hdd in new thread ###
						thread.start_new(self.saveVideo, (directory, capbuf))
						capbuf = None
						postFrames = 0
						newVideo = True


				######## Add Frame to history buffer ########
				historyBuffer.add(cv.CloneImage( frame ), t)


				######## Window ########
				if self._showWindow:
					cv.ShowImage("Thread " + str(self._thread), frame)
					cv.ShowImage("Thread %d avg" % self._thread, runAvgDisplay)
					cv.ShowImage("Thread %d diff" % self._thread, differenceImg)
					cv.WaitKey(1)
				
				######## Update Server ########
				if self._server:
					self._server.updateImage(cv.CloneImage( frame ))
				
				self.log("Proc: " + str(time.time() - ts))

			else:
				self.log("no more frames (" + str(frameCount) +" frames)")
				break

		self.log("Close camera")
		cap.close()
		
		if self._server:
			self.log("Close server")
			self._server.shutdown()
		
		self.log("end detection thread " + str(self._thread))
		self.active = False