Пример #1
0
	def setUp(self):
		# add a user
		self.user = User(username='******')
		self.user.save()

		# device classes
		rClass = DeviceClass(name='Router')
		rClass.save()
		sClass = DeviceClass(name='Switch')
		sClass.save()
		rlClass = DeviceClass(name='Routerlab Device')
		rlClass.save()
		lcClass = DeviceClass(name='Labcourse Device')
		lcClass.save()

		# devices
		self.d1 = Device(name='muc-rj1')
		self.d1.save()
		self.d1.deviceClasses.add(rClass)
		self.d1.deviceClasses.add(rlClass)
		self.d1.deviceClasses.add(lcClass)

		self.d2 = Device(name='nyc-sc1')
		self.d2.save()
		self.d2.deviceClasses.add(sClass)
		self.d2.deviceClasses.add(rlClass)
Пример #2
0
    def __forget_device(self, request, **kwargs):
        """
        'forgetting' a device happens if a user unlinks a 'hardware' device from daysyView

        what happens:
         - a new device with a 'virtual' serial-number is created and attached to the user/profile
         - data (files) form the old device are copied to the new one
         - old device and its data (files) are deleted.
        """
        self.method_check(request, allowed=['get', ])
        self.throttle_check(request)
        self.is_authenticated(request)


        user = User.objects.get(**self.remove_api_resource_names(kwargs))

        log.info('forget device for %s' % user.email)

        old_device = user.profile.device

        device = Device()
        device.generate_serial_number(user.pk)
        from django.core.files.base import ContentFile
        # temporary store data
        try:
            data_file = ContentFile(old_device.data_file.read())
        except Exception, e:
            data_file = None
            print e
Пример #3
0
def set_setpoint(request, pk):
  from device.models import Device
  setpoint = request.GET.get('setpoint')
  f = Fermenter.objects.get(pk=pk)
  Device.serial_cmd(f.component.device.device, "setSetpoint,"+str(f.fid)+','+setpoint)
  f.setpoint = Device.serial_cmd(f.component.device.device, "getSetpoint,"+str(f.fid))
  f.save()
  return HttpResponse(f.setpoint)
Пример #4
0
def create_or_update_device(request):
    # define default response
    response = {"error": "", "data": ""}
    # return if GET request
    if request.method == 'GET':
        response['error'] = {'no': 'err0', 'msg': 'sorry no gets'}
        return json_response_from(response)
    # get params from POST
    params = request.POST
    # error checking
    if (params['device_id'] == "" or params['reg_id'] == ""
            or params['phone_no'] == ""):
        response['error'] = {'no': 'err1', 'msg': 'missing mandatory params'}

    # get device
    device = Device.objects.filter(meid=params['device_id'])
    # if device exists, update
    if device.count() == 1:
        device = device[0]
        # email
        #if ('email' in params and device.email != params['email']):
        #  device.email = params['email']
        # reg_id
        if ('reg_id' in params and device.reg_id != params['reg_id']):
            device.reg_id = params['reg_id']
        # update
        if ('update_interval' in params
                and device.update_interval != params['update_interval']):
            device.update_interval = params['update_interval']
        device.save()
    # device does not exist, insert
    else:
        device = Device(
            meid=params['device_id'],
            #    email  = "*****@*****.**", #params['email']
            reg_id=params['reg_id'],
            active="E")
        device.save()

        # create monitor interval in StatusMonitor class
        # statusmonitor = StatusMonitor(
        #                   name = 'monitorInterval',
        #                   value = '10',
        #                   units = 'min')
        # statusmonitor.save()
        deviceprofile = DeviceProfile()
        #deviceprofile.statusmonitor.add(statusmonitor)

        deviceprofile.dev = device
        if params['device_id'].startswith('A0000', 0, 5):
            deviceprofile.phone_no = params['phone_no']
        deviceprofile.save()

        # device
        response['data'] = device
    # render json response
    return json_response_from(response)
Пример #5
0
 def discover(cls, device):
   from fermenter.models import Fermenter
   sn = Device.serial_cmd(device.device, 'getSN')
   type = Device.serial_cmd(device.device, 'getType')
   try:
     c = Component.objects.get(sn=sn)
     c.device = device
     c.save()
   except Component.DoesNotExist:
     c = Component.objects.create(device=device, sn=sn, type=type)
   if type == 'FERMENTER':
     Fermenter.discover(c)
Пример #6
0
def sup_add(request):
    if request.method == 'POST':
        if request.POST['project'] and request.POST[
                'username'] and request.POST['devicename'] and request.POST[
                    'devicetype'] and request.POST['ostype'] and request.POST[
                        'version'] and request.POST[
                            'quantity'] and request.POST['reason']:
            sup = Supplement()
            project = get_object_or_404(Project, name=request.POST['project'])
            user = get_object_or_404(User, username=request.POST['username'])

            device = Device()
            device.code = ''
            device.name = request.POST['devicename']
            device.type = request.POST['devicetype']
            device.ostype = request.POST['ostype']
            device.version = request.POST['version']
            device.status = 'Ordered'

            sup.account = user
            sup.project = project
            sup.device = device
            sup.status = 'Requesting'
            sup.quantity = request.POST['quantity']
            sup.reason = request.POST['reason']
            sup.save()
            return redirect('http://localhost:8000/device/')
        else:
            return render(request, 'supplement/sup_add.html',
                          {'error': 'All fields are required.'})
    else:
        return render(request, 'supplement/sup_add.html')
Пример #7
0
 def discover(cls, component):
   count = int(Device.serial_cmd(component.device.device,'getFermenters'))
   for fid in range(count):
     try:
       f = cls.objects.get(component=component, fid=fid)
     except Fermenter.DoesNotExist:
       f = cls.objects.create(component=component, fid=fid)
     f.mode = Device.serial_cmd(f.component.device.device,'getMode,'+str(f.fid))
     f.setpoint = Device.serial_cmd(f.component.device.device,'getSetpoint,'+str(f.fid))
     f.save()
     verbose_name="probe_temperature_"+str(f.id)
     try:
       t = Task.objects.get(verbose_name=verbose_name)
     except Task.DoesNotExist:
       cls.probe_temperature(f.id, verbose_name=verbose_name, repeat=60)
Пример #8
0
def upload(request, name):
    logger = logging.getLogger("mylogger")
    # ftp = FTP(host='10.235.65.24',user='******', passwd = 'task!123!')
    # ftp.login()
    # ftp.cwd('/home/task')
    # filename = 'task.csv'
    # localfile = open(filename, 'wb')
    # ftp.retrbinary('RETR ' + filename, localfile.write, 1024)
    # ftp.quit()
    # with open(localfile,encoding = 'cp850') as csv_file:
    try:
        with open(os.path.join(settings.MEDIA_ROOT, name),
                  encoding='cp850') as csv_file:
            next(csv_file)
            csv_reader = csv.reader(csv_file, delimiter=',')
            all_devices = []
            for row in csv_reader:
                str1 = row[1].replace("O/L", "Online")
                str2 = str1.replace("CEASING", "Offline")
                all_devices.append(
                    Device(name=row[0],
                           status=str2,
                           chassis_type=row[2],
                           service_type=row[3],
                           device_type=row[4],
                           toposite_name=row[5],
                           site_name=row[6],
                           ico01=row[7]))
        Device.objects.bulk_create(all_devices)
        return redirect("/all")
    except:
        messages.info(request, 'Wrong file format, please choose a .csv file!')
        return redirect('/')
Пример #9
0
def create_or_update_device(request): 
  # define default response
  response = { "error": "", "data": "" }
  # return if GET request
  if request.method == 'GET':
    response['error'] = {
      'no' : 'err0',
      'msg': 'sorry no gets'
    }
    return json_response_from(response)
  # get params from POST
  params = request.POST
  # error checking
  if (params['device_id'] == "" or params['reg_id'] == ""):
    response['error'] = {
      'no' : 'err1',
      'msg': 'missing mandatory params'
    }
  # get device
  device = Device.objects.filter(id=params['device_id'])
  # if device exists, update
  if device.count() == 1:
    device = device[0]
    # email
    if ('email' in params and device.email != params['email']):
      device.email = params['email']
    # reg_id
    if ('reg_id' in params and device.reg_id != params['reg_id']):
      device.reg_id = params['reg_id']
    # update
    if ('update_interval' in params and device.update_interval != params['update_interval']):
      device.update_interval = params['update_interval']
  # device does not exist, insert
  else:
    device = Device(
        id     = params['device_id'], 
        email  = "*****@*****.**", #params['email'] 
        reg_id = params['reg_id']
    )
  # save device
  device.save()
  
  # device
  response['data'] = device
  # render json response
  return json_response_from(response)
    def test_register_already_existing_device_set_it_to_me(self):
        device = generate_device_info()

        device1 = device.copy()
        device1["user"] = User.objects.last()
        Device(**device1).save()

        self.assertEqual(self.post(device).status_code, status.HTTP_201_CREATED)
        self.assertEqual(Device.objects.get(registration_id=device["registration_id"]).user_id, self.user.id)
Пример #11
0
def get_temperature(request, pk):
  from device.models import Device
  from beer.models import Temperature
  f = Fermenter.objects.get(pk=pk)
  f.temperature = Device.serial_cmd(f.component.device.device, "getTemperature,"+str(f.fid))
  f.datetime = timezone.now()
  f.save()
  if hasattr(f, 'beer'):
    Temperature.objects.create(beer=f.beer, setpoint=f.setpoint, measured=f.temperature, datetime=timezone.now())
  return HttpResponse(f.temperature)
Пример #12
0
def device_monthly(request, pk):
    try:
        device = Device.get(pk)
        items = Monthly.objects.filter(device=device).order_by('-created')[:12]
    except Device.DoesNotExist:
        items = Monthly()
    except Monthly.DoesNotExist:
        items = Monthly()

    return json_write_items(items)
Пример #13
0
def device_activity(request, pk):
    try:
        device = Device.get(pk)
        items = Activity.objects.filter(
            device=device).order_by('-created')[:20]
    except Device.DoesNotExist:
        items = Activity()
    except Activity.DoesNotExist:
        items = Activity()

    return json_write_items(items)
Пример #14
0
def add_device(request):
    if request.method == 'POST':
        if request.POST['code'] and request.POST['name'] and request.POST[
                'type'] and request.POST['ostype'] and request.POST[
                    'version'] and request.POST['status']:
            try:
                device = Device()
                device.code = request.POST['code']
                device.name = request.POST['name']
                device.type = request.POST['type']
                device.ostype = request.POST['ostype']
                device.version = request.POST['version']
                device.status = request.POST['status']
                device.save()
                #return redirect('/device/detail/' + str(device.code))
                return render(request, 'device/add.html', {'device': device})
            except:
                return render(request, 'device/add.html',
                              {'error': 'Something Wrong!'})
        else:
            return render(request, 'device/add.html',
                          {'error': 'All fields are required.'})
    else:
        return render(request, 'device/add.html')
Пример #15
0
def device_activity_chart(request, pk):
    today = date.today()
    try:
        device = Device.get(pk)

        items = Activity.objects.filter(device=device).filter(
            created__contains=today).values_list('created', 'energy_wh',
                                                 'real_power_w')
        chart = [[device.name, 'Energy', 'Power']]
        if len(items) > 0:
            for item in items:
                t = timezone.localtime(item[0]).strftime('%H:%M')
                chart.append((t, item[1], item[2]))
        else:
            raise Device.DoesNotExist
    except Device.DoesNotExist:
        chart = [[device.name, 'Energy', 'Power'], ['', 0, 0]]

    return HttpResponse(json.dumps(chart), content_type="text/json")
Пример #16
0
def edit(request, pk):
  from device.models import Device
  f = Fermenter.objects.get(pk=pk)
  if request.method == "POST":
    form = FermenterForm(request.POST)
    if "save" in request.POST and form.is_valid():
      if not f.name == request.POST.get("name"):
        f.name = request.POST.get("name")
      if not f.setpoint == Decimal(request.POST.get("setpoint")):
        Device.serial_cmd(f.component.device.device,"setSetpoint,"+str(f.fid)+","+request.POST.get("setpoint"))
        f.setpoint = Device.serial_cmd(f.component.device.device,"getSetpoint,"+str(f.fid))
      if not f.mode == request.POST.get("mode"):
        Device.serial_cmd(f.component.device.device,"setMode,"+str(f.fid)+","+request.POST.get("mode"))
        f.mode = Device.serial_cmd(f.component.device.device,"getMode,"+str(f.fid))
      f.save()
    return redirect('fermenter:detail', pk=f.id)
  else:
    form = FermenterForm(instance=f)
    return render(request, 'fermenter/form.html', {'form': form, 'fermenter': f})
Пример #17
0
def apiDevice( request ):
	
	# Return list of all devices
	if( request.method == "GET" ):
		try:
			device_data = Device.objects.all()
			
		except Device.DoesNotExist:
			return Response( status = status.HTTP_404_NOT_FOUND )
		
	
		serializer = DeviceSerializer( device_data, many=True )
		return Response( serializer.data )
		
	
	# Create new device
	elif ( request.method == "POST" ):
		try:
			# Extract attributes
			payload = request.POST
		
			uid = payload["uid"]
			name = payload["name"]
			
			# Create new Device
			device_new = Device( uid = uid, name = name )
			
			Device.full_clean( device_new )
			
			device_new.save()
			
		
		except PermissionDenied as e:
			return Response( status = status.HTTP_401_UNAUTHORIZED )
		
		
	 

		return Response( status = status.HTTP_201_CREATED )
Пример #18
0
	def setUp(self):
		# device classes
		rClass = DeviceClass(name='Router')
		rClass.save()
		sClass = DeviceClass(name='Switch')
		sClass.save()
		rlClass = DeviceClass(name='Routerlab Device')
		rlClass.save()
		lcClass = DeviceClass(name='Labcourse Device')
		lcClass.save()
		lgClass = DeviceClass(name='LoadGen')
		lgClass.save()
		domUClass = DeviceClass(name='VirtualLoadGen')
		domUClass.save()

		# power device classes
		pdClass = DeviceClass(name='PowerDevice')
		pdClass.save()
		pdIlomClass = DeviceClass(name='ILOM')
		pdIlomClass.save()
		pdXenDom0Class = DeviceClass(name='XenDom0')
		pdXenDom0Class.save()
		pdPowerSwitchClass = DeviceClass(name='GUDE Power Switch')
		pdPowerSwitchClass.save()
		pdPowerBarClass = DeviceClass(name='Infratec Power Bar')
		pdPowerBarClass.save()


		# devices
		self.router = Device(name='muc-rj1')
		self.router.save()
		self.router.deviceClasses.add(rClass)
		self.router.deviceClasses.add(rlClass)
		self.router.deviceClasses.add(lcClass)

		self.switch = Device(name='nyc-sc1')
		self.switch.save()
		self.switch.deviceClasses.add(sClass)
		self.switch.deviceClasses.add(rlClass)

		self.domU = Device(name='Loadgen42')
		self.domU.save()
		self.domU.deviceClasses.add(lcClass)
		self.domU.deviceClasses.add(rlClass)
		self.domU.deviceClasses.add(domUClass)

		self.loadgen35 = Device(name='loadgen35')
		self.loadgen35.save()
		self.loadgen35.deviceClasses.add(lcClass)
		self.loadgen35.deviceClasses.add(rlClass)
		self.loadgen35.deviceClasses.add(lgClass)

		# power devices
		self.dom0 = Device(name='LoadgenXenDom0')
		self.dom0.save()
		self.dom0.deviceClasses.add(rlClass)
		self.dom0.deviceClasses.add(pdXenDom0Class)
		self.dom0.deviceClasses.add(pdClass)

		self.ilom = Device(name='loadgen35-sp')
		self.ilom.save()
		self.ilom.deviceClasses.add(rlClass)
		self.ilom.deviceClasses.add(pdIlomClass)
		self.ilom.deviceClasses.add(pdClass)

		self.power_switch = Device(name='PowerSwitch')
		self.power_switch.save()
		self.power_switch.deviceClasses.add(rlClass)
		self.power_switch.deviceClasses.add(pdPowerSwitchClass)
		self.power_switch.deviceClasses.add(pdClass)

		self.power_bar = Device(name='PowerBar 3')
		self.power_bar.save()
		self.power_bar.deviceClasses.add(rlClass)
		self.power_bar.deviceClasses.add(pdClass)
		self.power_bar.deviceClasses.add(pdPowerBarClass)

		# link devices to power devices
		self.pp_xen = PowerPort(device=self.dom0,socketId=1)
		self.pp_xen.save()
		self.domU.power = self.pp_xen

		self.pp_ilom = PowerPort(device=self.ilom,socketId=1)
		self.pp_ilom.save()
		self.loadgen35.power = self.pp_ilom

		self.pp_power_switch_1 = PowerPort(device=self.power_switch,socketId=1)
		self.pp_power_switch_1.save()
		self.switch.power = self.pp_power_switch_1

		self.pp_power_switch_2 = PowerPort(device=self.power_switch,socketId=2)
		self.pp_power_switch_2.save()
Пример #19
0
def confirm_participant_register(request):
  # params checking
  if (request.POST['ub_id'] == '' and request.POST['email'] == '' \
         and request.POST['first_name'] =='' and request.POST['last_name'] ==''):
    participantregister = ParticipantRegister(
                         lib_number = request.POST['lib_number'],
                         meid       = request.POST['meid']
                         )
    print request.POST['lib_number']+" -- "+request.POST['meid']
    participantregister.save()
    return render_to_response(
    	'participant_register_form.html',
      {
      'success': True,
      },
      context_instance=RequestContext(request)
      )
  else:
    password = User.objects.make_random_password(length=10, allowed_chars='abcdefghjkmnpqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ23456789')
    user = User.objects.create_user(request.POST['ub_id'], request.POST['email'], password)
    user.is_active = False
    user.first_name = request.POST['first_name']
    user.last_name = request.POST['last_name']
    user.save() 
	
    # Build the activation key for their account                                                                                                                    
    salt = hashlib.md5(str(random.random())).hexdigest()[:5]
    activation_key = hashlib.md5(salt+user.username).hexdigest()
    key_expires = datetime.today() + timedelta(2)
    userprofile = UserProfile(
                user = user,
                user_type = "P",
                activation_key=activation_key, 
                key_expires=key_expires
                )
    # Create and save their profile                                                                                                                                 
    userprofile.save()

    device = Device(
           meid = request.POST['meid'],
           hash_meid = hashlib.sha1(request.POST['meid']).hexdigest(),
           active = "E"
           )
    device_id = device.save()
    device.save()
  
    # create monitor interval in StatusMonitor class
    statusmonitor = StatusMonitor(
                  name = 'monitorInterval',
                  value = '10',
                  units = 'min')
    statusmonitor.save()
  
    # Create and save device profile
    deviceprofile = DeviceProfile()
    deviceprofile.dev = device
    deviceprofile.user = user
    deviceprofile.phone_no = request.POST['phone_number']
    deviceprofile.status = "W"
    #deviceprofile.purpose = ""
    if request.POST['meid'].startswith('A0000', 0, 5):
       deviceprofile.service_type = "4"
    else:
       deviceprofile.service_type = "3"
    deviceprofile.save()
    deviceprofile.statusmonitor.add(statusmonitor)
    deviceprofile.save()
    return render_to_response(
    	'participant_register_form.html',
      {
      'success': True,
      },
      context_instance=RequestContext(request)
      )
Пример #20
0
def create_device(user):
    info = dict(user=user, registration_id="{}-{}".format(user, uuid.uuid4()))
    device = Device(**info)
    device.save()
    return device
Пример #21
0
class ReservationTest(TestCase):
	def setUp(self):
		# add a user
		self.user = User(username='******')
		self.user.save()

		# device classes
		rClass = DeviceClass(name='Router')
		rClass.save()
		sClass = DeviceClass(name='Switch')
		sClass.save()
		rlClass = DeviceClass(name='Routerlab Device')
		rlClass.save()
		lcClass = DeviceClass(name='Labcourse Device')
		lcClass.save()

		# devices
		self.d1 = Device(name='muc-rj1')
		self.d1.save()
		self.d1.deviceClasses.add(rClass)
		self.d1.deviceClasses.add(rlClass)
		self.d1.deviceClasses.add(lcClass)

		self.d2 = Device(name='nyc-sc1')
		self.d2.save()
		self.d2.deviceClasses.add(sClass)
		self.d2.deviceClasses.add(rlClass)

	@unittest.skip("feature not yet implemented")
	def test_no_reservation_creation_in_the_past(self):
		""" Reservations must begin at or after the current system now """
		r = Reservation(user=self.user)
		r.startTime = datetime.datetime(2011, 10, 12, 10, 0, 0).replace(tzinfo=utc)
		r.endTime   = datetime.datetime(2011, 10, 12, 14, 0, 0).replace(tzinfo=utc)
		r.save()
		r.devices.add(self.d1)
		r.save()

		self.assertRaises(ValidationError, r.save)

	def test_simple_reservation_creation(self):
		r = Reservation(user=self.user)
		r.startTime = datetime.datetime(2016, 10, 12, 10, 0, 0).replace(tzinfo=utc)
		r.endTime   = datetime.datetime(2016, 10, 12, 14, 0, 0).replace(tzinfo=utc)
		r.save()
		r.devices.add(self.d1)
		r.save()

		self.assertEqual(Reservation.objects.get(id=1).devices.all()[0], self.d1)

	def test_start_end_time_inverstion_raises_exception(self):
		""" Reservation with begin after end must raise ValidationError """
		r = Reservation(user=self.user)
		r.startTime   = datetime.datetime(2016, 10, 12, 14, 0, 0).replace(tzinfo=utc)
		r.endTime = datetime.datetime(2016, 10, 12, 10, 0, 0).replace(tzinfo=utc)

		self.assertRaises(ValidationError, r.save)

	def test_single_device_conflicting_reservations(self):
		r = Reservation(user=self.user)
		r.startTime = datetime.datetime(2016, 10, 12, 10, 0, 0).replace(tzinfo=utc)
		r.endTime   = datetime.datetime(2016, 10, 12, 14, 0, 0).replace(tzinfo=utc)
		r.save()
		r.devices.add(self.d1)
		r.save()

		# this reservation has a device whose existing reservation conflicts
		r = Reservation(user=self.user)
		r.startTime = datetime.datetime(2016, 10, 12,  9, 0, 0).replace(tzinfo=utc)
		r.endTime   = datetime.datetime(2016, 10, 12, 11, 0, 0).replace(tzinfo=utc)
		r.save()
		r.devices.add(self.d1)
		self.assertRaises(ValidationError, r.save)

	def test_multi_device_conflicting_reservations(self):
		r = Reservation(user=self.user)
		r.startTime = datetime.datetime(2016, 10, 12, 10, 0, 0).replace(tzinfo=utc)
		r.endTime   = datetime.datetime(2016, 10, 12, 14, 0, 0).replace(tzinfo=utc)
		r.save()
		r.devices.add(self.d1)
		r.devices.add(self.d2)
		r.save()

		# this reservation has a device whose existing reservation conflicts
		r = Reservation(user=self.user)
		r.startTime = datetime.datetime(2016, 10, 12,  9, 0, 0).replace(tzinfo=utc)
		r.endTime   = datetime.datetime(2016, 10, 12, 11, 0, 0).replace(tzinfo=utc)
		r.save()
		r.devices.add(self.d2)
		self.assertRaises(ValidationError, r.save)

	def test_bordering_reservations(self):
		""" Reservations may begin at the time dependent reservations end """
		r = Reservation(user=self.user)
		r.startTime = datetime.datetime(2016, 10, 12, 10, 0, 0).replace(tzinfo=utc)
		r.endTime   = datetime.datetime(2016, 10, 12, 14, 0, 0).replace(tzinfo=utc)
		r.save()
		r.devices.add(self.d1)
		r.save()

		# test bordering reservation
		r = Reservation(user=self.user)
		r.startTime = datetime.datetime(2016, 10, 12, 14, 0, 0).replace(tzinfo=utc)
		r.endTime   = datetime.datetime(2016, 10, 12, 15, 0, 0).replace(tzinfo=utc)
		r.save()
		r.devices.add(self.d1)
		self.assertEqual(Reservation.objects.get(id=1).devices.all()[0], self.d1)


	# Only active and future reservations may have device additions
	@unittest.skip("feature not yet implemented")
	def test_active_reservation_device_addition(self):
		""" A new reservation should be created inclding the new devices
		(if possible), old reservation terminated now and new reservation starting
		now
		"""
		pass

	@unittest.skip("feature not yet implemented")
	def test_future_reservation_device_addition_(self):
		pass

	@unittest.skip("feature not yet implemented")
	def test_ended_reservation_device_addition_raises_exception(self):
		pass


	# Only active and future reservations may be time-extended i.e. end-time set to system now
	@unittest.skip("feature not yet implemented")
	def test_active_reservation_extension(self):
		pass

	@unittest.skip("feature not yet implemented")
	def test_future_reservation_extension_raises_exception(self):
		pass

	@unittest.skip("feature not yet implemented")
	def test_ended_reservation_extension_raises_exception(self):
		pass


	# Only active reservations may be terminated i.e. end-time set to system now
	def test_active_reservation_termination(self):
		""" Active reservations should not be running after termination """
		r = Reservation(user=self.user)
		now = datetime.datetime.utcnow().replace(tzinfo=utc)
		r.startTime = now + datetime.timedelta(days=-1)
		r.endTime   = now + datetime.timedelta(days=10)
		r.save(full_clean=False)

		r.terminate(full_clean=False)
		
		self.assertFalse(r.is_running())

	def test_future_reservation_termination_raises_exception(self):
		""" Future reservations may not be terminated """
		r = Reservation(user=self.user)
		now = datetime.datetime.utcnow().replace(tzinfo=utc)
		r.startTime = now + datetime.timedelta(days=10)
		r.endTime   = now + datetime.timedelta(days=12)
		r.save()

		self.assertRaises(ValidationError, r.terminate)

	def test_ended_reservation_termination_raises_exception(self):
		""" Ended reservations may not be terminated """
		r = Reservation(user=self.user)
		now = datetime.datetime.utcnow().replace(tzinfo=utc)
		r.startTime = now + datetime.timedelta(days=-14)
		r.endTime   = now + datetime.timedelta(days=-7)
		r.save(full_clean=False)

		self.assertRaises(ValidationError, r.terminate)

	# Reservations may only be deleted i.e. removed from the database or flagged as deleted and thus never considered by any logic if they have not yet begun
	@unittest.skip("feature not yet implemented")
	def test_active_reservation_deletion_raises_exception(self):
		pass

	@unittest.skip("feature not yet implemented")
	def test_future_active_reservation_deletion(self):
		pass

	@unittest.skip("feature not yet implemented")
	def test_ended_reservation_deletion_raises_exception(self):
		pass
Пример #22
0
        # create the user as active
        # separate flag in profile model to track email confirmation
        user = create_user(data['email'], data['password'], is_active=True)

        # hook up with registration
        registration_profile = RegistrationProfile.objects.create_profile(user)
        registration_signals.user_registered.send(sender=self.__class__, user=user, request=request)
        send_activation_email(registration_profile)

        # create device for user
        if serial_number:
            # device, created = Device.objects.get_or_create(profiles__in=[user.pk, ], serial_number=serial_number)
            device, created = Device.objects.get_or_create(serial_number=serial_number, status=2)
        else:
            # no serial provided, so create a 'app' device and generate a serial for it
            device = Device()
            device.generate_serial_number(user.pk)
            device.status = 2
            device.save()

        # finally create the user profile
        profile, created = UserProfile.objects.get_or_create(user=user, device=device)

        log.info('registraion success: %s - serial number: %s' % (email, device.serial_number))

        bundle = self.build_bundle(obj=user, request=request)
        bundle = self.full_dehydrate(bundle)

        # provide api key
        bundle.data['api_key'] = bundle.obj.api_key.key
Пример #23
0
class PowerTest(TestCase):
	def setUp(self):
		# device classes
		rClass = DeviceClass(name='Router')
		rClass.save()
		sClass = DeviceClass(name='Switch')
		sClass.save()
		rlClass = DeviceClass(name='Routerlab Device')
		rlClass.save()
		lcClass = DeviceClass(name='Labcourse Device')
		lcClass.save()
		lgClass = DeviceClass(name='LoadGen')
		lgClass.save()
		domUClass = DeviceClass(name='VirtualLoadGen')
		domUClass.save()

		# power device classes
		pdClass = DeviceClass(name='PowerDevice')
		pdClass.save()
		pdIlomClass = DeviceClass(name='ILOM')
		pdIlomClass.save()
		pdXenDom0Class = DeviceClass(name='XenDom0')
		pdXenDom0Class.save()
		pdPowerSwitchClass = DeviceClass(name='GUDE Power Switch')
		pdPowerSwitchClass.save()
		pdPowerBarClass = DeviceClass(name='Infratec Power Bar')
		pdPowerBarClass.save()


		# devices
		self.router = Device(name='muc-rj1')
		self.router.save()
		self.router.deviceClasses.add(rClass)
		self.router.deviceClasses.add(rlClass)
		self.router.deviceClasses.add(lcClass)

		self.switch = Device(name='nyc-sc1')
		self.switch.save()
		self.switch.deviceClasses.add(sClass)
		self.switch.deviceClasses.add(rlClass)

		self.domU = Device(name='Loadgen42')
		self.domU.save()
		self.domU.deviceClasses.add(lcClass)
		self.domU.deviceClasses.add(rlClass)
		self.domU.deviceClasses.add(domUClass)

		self.loadgen35 = Device(name='loadgen35')
		self.loadgen35.save()
		self.loadgen35.deviceClasses.add(lcClass)
		self.loadgen35.deviceClasses.add(rlClass)
		self.loadgen35.deviceClasses.add(lgClass)

		# power devices
		self.dom0 = Device(name='LoadgenXenDom0')
		self.dom0.save()
		self.dom0.deviceClasses.add(rlClass)
		self.dom0.deviceClasses.add(pdXenDom0Class)
		self.dom0.deviceClasses.add(pdClass)

		self.ilom = Device(name='loadgen35-sp')
		self.ilom.save()
		self.ilom.deviceClasses.add(rlClass)
		self.ilom.deviceClasses.add(pdIlomClass)
		self.ilom.deviceClasses.add(pdClass)

		self.power_switch = Device(name='PowerSwitch')
		self.power_switch.save()
		self.power_switch.deviceClasses.add(rlClass)
		self.power_switch.deviceClasses.add(pdPowerSwitchClass)
		self.power_switch.deviceClasses.add(pdClass)

		self.power_bar = Device(name='PowerBar 3')
		self.power_bar.save()
		self.power_bar.deviceClasses.add(rlClass)
		self.power_bar.deviceClasses.add(pdClass)
		self.power_bar.deviceClasses.add(pdPowerBarClass)

		# link devices to power devices
		self.pp_xen = PowerPort(device=self.dom0,socketId=1)
		self.pp_xen.save()
		self.domU.power = self.pp_xen

		self.pp_ilom = PowerPort(device=self.ilom,socketId=1)
		self.pp_ilom.save()
		self.loadgen35.power = self.pp_ilom

		self.pp_power_switch_1 = PowerPort(device=self.power_switch,socketId=1)
		self.pp_power_switch_1.save()
		self.switch.power = self.pp_power_switch_1

		self.pp_power_switch_2 = PowerPort(device=self.power_switch,socketId=2)
		self.pp_power_switch_2.save()

	def test_device_power_methods(self):
		with self.assertRaises(UnboundLocalError):
			self.router.on()

		with self.assertRaises(UnboundLocalError):
			self.router.off()

		with self.assertRaises(UnboundLocalError):
			self.router.powercycle()

		with self.assertRaises(UnboundLocalError):
			self.router.isrunning()

		self.router.power = self.pp_power_switch_2
		self.assertTrue(self.router.on())
		self.assertTrue(self.router.off())
		self.assertTrue(self.router.powercycle())
		self.assertTrue(self.router.isrunning())

		self.assertTrue(self.switch.on())
		self.assertTrue(self.switch.off())
		self.assertTrue(self.switch.powercycle())
		self.assertTrue(self.switch.isrunning())

		self.assertTrue(self.domU.on())
		self.assertTrue(self.domU.off())
		self.assertTrue(self.domU.powercycle())
		self.assertTrue(self.domU.isrunning())

		self.assertTrue(self.loadgen35.on())
		self.assertTrue(self.loadgen35.off())
		self.assertTrue(self.loadgen35.powercycle())
		self.assertTrue(self.loadgen35.isrunning())

	def test_power_device_methods(self):
		self.assertTrue(self.dom0.on())
		self.assertTrue(self.dom0.off())
		self.assertTrue(self.dom0.powercycle())
		self.assertTrue(self.dom0.isrunning())

		self.assertTrue(self.ilom.on())
		self.assertTrue(self.ilom.off())
		self.assertTrue(self.ilom.powercycle())
		self.assertTrue(self.ilom.isrunning())

		self.assertTrue(self.power_switch.on())
		self.assertTrue(self.power_switch.off())
		self.assertTrue(self.power_switch.powercycle())
		self.assertTrue(self.power_switch.isrunning())

		self.assertTrue(self.power_bar.on())
		self.assertTrue(self.power_bar.off())
		self.assertTrue(self.power_bar.powercycle())
		self.assertTrue(self.power_bar.isrunning())

	def test_initialize_ssh_client(self):
		self.testclient = powercontroller.initialize_ssh_client()
		self.assertEqual(isinstance(self.testclient, ssh.SSHClient),True)
		# Policy tests
		self.assertEqual(isinstance(self.testclient._policy, ssh.AutoAddPolicy),True)

		self.testclient = powercontroller.initialize_ssh_client(policy='add')
		self.assertEqual(isinstance(self.testclient._policy, ssh.AutoAddPolicy),True)

		self.testclient = powercontroller.initialize_ssh_client(policy='deny')
		self.assertEqual(isinstance(self.testclient._policy, ssh.RejectPolicy),True)

		self.testclient = powercontroller.initialize_ssh_client(policy='')
		self.assertEqual(isinstance(self.testclient._policy, ssh.WarningPolicy),True)

		# HostKey test
		self.testclient = powercontroller.initialize_ssh_client()
		# System Host Keys
		self.assertEqual(isinstance(self.testclient._system_host_keys,ssh.HostKeys),True)
		self.assertNotEqual(self.testclient._system_host_keys.__len__(), 0)

		# FIXME: Add tests for custom host_key files

	def test_interaction_ILOMSNMP(self):
		self.snmp_ilom = powercontroller.ILOMSNMP(unicode('loadgen35-sp'))

		# Test if configuration file exists and was parsed correctly
		self.assertIsNotNone(powercontroller.CONFIGFILE)
		self.assertDictContainsSubset(dict(on=1,off=2,cycle=3),self.snmp_ilom.ILOM_SNMP_POWER_STATES)
		self.assertEqual('1.3.6.1.4.1.42.2.175.102.11.1.1.1.2.4.47.83.89.83',self.snmp_ilom.ILOM_SNMP_POWER)

		# Test that power functions exist, throw no exception and return false
		self.assertFalse(self.snmp_ilom.PowerOn())
		self.assertFalse(self.snmp_ilom.PowerOff())
		self.assertFalse(self.snmp_ilom.PowerCycle())
		self.assertFalse(self.snmp_ilom.PowerIsRunning())
Пример #24
0
def add(request,action):
	message = {}
	if request.method == "POST":
		try:
			if action == "device":
				name = request.POST.get('name')
				devtype_id = request.POST.get('equ_class_id')
				code = request.POST.get('code')
				serial = request.POST.get('serial')
				addtime = request.POST.get('addtime')
				place = request.POST.get('place')
				manager = request.POST.get('manager')

				if devtype_id == None:
					raise ValidationError("请选择分类")
				device = Device()
				device.dev_type = DevType.objects.get(pk=devtype_id)
				device.code = code
				device.serial = serial
				device.addtime = addtime
				device.place = place
				device.manager = manager

				device.clean()
				device.save()
				message={'type':'success','content':'添加设备成功'}
			
			elif action == "devtype":
				devcataid = request.POST.get('mode')
				name = request.POST.get('pattern')
				unit = request.POST.get('unit')
				price = request.POST.get('price')

				devtype = DevType()
				devtype.dev_cata = DevCata.objects.get(pk=devcataid)
				devtype.name = name
				devtype.unit = unit
				devtype.price = price
				devtype.clean()
				devtype.save()
				message={'type':'success','content':'添加设备型号成功'}

			elif action == "devcata":
				name = request.POST.get('name')
				devcata = DevCata()
				devcata.name = name
				devcata.clean()
				devcata.save()
				message={'type':'success','content':'添加设备分类成功'}
		
		except ValidationError as e:
			message = {'type':'error','content':'; '.join(e.messages)}

		message["exist"] = True
		request.session["message"] = message
		return redirect("device:add",action)

	cataList = DevCata.objects.all()
	typeList = DevType.objects.all()
	if action == "device":
		form = DeviceForm()
		template = 'device/adddevice.html'
	elif action == "devtype":
		form = DevTypeForm()
		template = 'device/adddevtype.html'
	elif action == "devcata":
		form = DevCataForm()
		template = 'device/adddevcata.html'

	if 'message' in request.session:
		message = request.session['message']
		message['exist'] = True
		del request.session['message']

	return render_to_response(template,{'form':form,'action':action,'cataList':cataList,'typeList':typeList,'message':message,'section':'add'},context_instance=RequestContext(request))
Пример #25
0
 def on_message(client, userdata, msg):
     Device = MqttClientConfig.Device
     print(msg.topic)
     print(msg.payload)
     topic = msg.topic
     if topic.startswith(cfg_pre):
         sn = topic.replace(cfg_pre, '')
         dev_msg = json.loads(msg.payload)
         try:
             if not sn == dev_msg['sn']:
                 print('found error msg topic %s payload %s' %
                       (msg.topic, msg.topic))
             else:
                 res = Device.objects.filter(id=sn)
                 if res.count() == 0:
                     print('dev_msg not exist')
                     device = Device()
                     device.id = sn
                     device.name = dev_msg['name']
                     device.config = json.dumps(dev_msg['config'])
                     device.version = dev_msg['version']
                     device.save()
                     print('dev_msg saved')
                 else:
                     device = res[0]
                     local_ver = dev_msg['version'].split('.')
                     cloud_ver = device.version.split('.')
                     if int(local_ver[0]) > int(cloud_ver[0]) or \
                             (int(local_ver[0]) == int(cloud_ver[0]) and int(local_ver[1]) >= int(cloud_ver[1])):
                         device.config = json.dumps(dev_msg['config'])
                         device.confirm = True
                         device.version = dev_msg['version']
                         device.save()
                         print('dev_msg updated')
                     else:
                         device.confirm = False
                         device.save()
         except Exception as e:
             print(e)
     elif topic.startswith(data_pre):
         sn = topic.replace(data_pre, '')
         dev_msg = json.loads(msg.payload)
         if not sn == dev_msg['sn']:
             print('found error msg topic %s payload %s' %
                   (msg.topic, msg.topic))
         else:
             print('handle data')
     else:
         print('found unknown msg topic %s payload %s' %
               (msg.topic, msg.topic))
Пример #26
0
def create_or_update_device(request): 
  # define default response
  response = { "error": "", "data": "" }
  # return if GET request
  if request.method == 'GET':
    response['error'] = {
      'no' : 'err0',
      'msg': 'sorry no gets'
    }
    return json_response_from(response)
  # get params from POST
  params = request.POST
  # error checking
  if (params['device_id'] == "" or params['reg_id'] == "" or params['phone_no'] == ""):
    response['error'] = {
      'no' : 'err1',
      'msg': 'missing mandatory params'
    }
  
  # get device
  device = Device.objects.filter(meid=params['device_id'])
  # if device exists, update
  if device.count() == 1:
    device = device[0]
    # email
    #if ('email' in params and device.email != params['email']):
    #  device.email = params['email']
    # reg_id
    if ('reg_id' in params and device.reg_id != params['reg_id']):
      device.reg_id = params['reg_id']
    # update
    if ('update_interval' in params and device.update_interval != params['update_interval']):
      device.update_interval = params['update_interval']
    device.save()
  # device does not exist, insert
  else:
    device = Device(
        meid     = params['device_id'], 
    #    email  = "*****@*****.**", #params['email'] 
        reg_id = params['reg_id'],
        active = "E"
    )
    device.save()

    # create monitor interval in StatusMonitor class
    # statusmonitor = StatusMonitor(
    #                   name = 'monitorInterval',
    #                   value = '10',
    #                   units = 'min')
    # statusmonitor.save()
    deviceprofile = DeviceProfile()    
    #deviceprofile.statusmonitor.add(statusmonitor)

    deviceprofile.dev = device
    if params['device_id'].startswith('A0000', 0, 5):
      deviceprofile.phone_no = params['phone_no']
    deviceprofile.save()
    
    # device
    response['data'] = device
  # render json response
  return json_response_from(response)
Пример #27
0
class ReservationTest(TestCase):
	def setUp(self):
		# add a user
		self.user = User(username='******')
		self.user.save()

		# device classes
		rClass = DeviceClass(name='Router')
		rClass.save()
		sClass = DeviceClass(name='Switch')
		sClass.save()
		rlClass = DeviceClass(name='Routerlab Device')
		rlClass.save()
		lcClass = DeviceClass(name='Labcourse Device')
		lcClass.save()

		# devices
		self.d1 = Device(name='muc-rj1')
		self.d1.save()
		self.d1.deviceClasses.add(rClass)
		self.d1.deviceClasses.add(rlClass)
		self.d1.deviceClasses.add(lcClass)

		self.d2 = Device(name='nyc-sc1')
		self.d2.save()
		self.d2.deviceClasses.add(sClass)
		self.d2.deviceClasses.add(rlClass)

	def test_device_reservability(self):
		# add a basic reservation
		r = Reservation(user=self.user)
		r.startTime = datetime.datetime(2112, 10, 12, 10, 0, 0).replace(tzinfo=utc)
		r.endTime   = datetime.datetime(2112, 10, 12, 14, 0, 0).replace(tzinfo=utc)
		r.save()
		r.devices.add(self.d1)
		r.save()

		# device can be reserved if not blocked
		self.assertEqual(True, self.d1.isReservable(
					datetime.datetime(2112, 10, 12,  8, 0, 0).replace(tzinfo=utc),
					datetime.datetime(2112, 10, 12,  9, 0, 0).replace(tzinfo=utc)
		))

		self.assertEqual(True, self.d1.isReservable(
					datetime.datetime(2112, 10, 12,  8,  0,  0).replace(tzinfo=utc),
					datetime.datetime(2112, 10, 12,  9, 59, 59).replace(tzinfo=utc)
		))

		self.assertEqual(False, self.d1.isReservable(
					datetime.datetime(2112, 10, 12,  8, 0, 0).replace(tzinfo=utc),
					datetime.datetime(2112, 10, 12, 10, 0, 0).replace(tzinfo=utc)
		))

		self.assertEqual(False, self.d1.isReservable(
					datetime.datetime(2112, 10, 11,  8, 0, 0).replace(tzinfo=utc),
					datetime.datetime(2112, 10, 16, 10, 0, 0).replace(tzinfo=utc)
		))

		self.assertEqual(True, self.d1.isReservable(
					datetime.datetime(2112, 10, 18,  8, 0, 0).replace(tzinfo=utc),
					datetime.datetime(2112, 10, 20, 10, 0, 0).replace(tzinfo=utc)
		))

	def test_adding_devices_to_reservation(self):
		# add a basic reservation
		r = Reservation(user=self.user)
		r.startTime = datetime.datetime(2112, 10, 12, 10, 0, 0).replace(tzinfo=utc)
		r.endTime   = datetime.datetime(2112, 10, 12, 14, 0, 0).replace(tzinfo=utc)
		r.save()
		r.devices.add(self.d1)
		r.save()

		newRes = r.addDevices(datetime.datetime(2112, 10, 12, 12, 0, 0).replace(tzinfo=utc), [self.d2])

		self.assertEqual(newRes.endTime, datetime.datetime(2112, 10, 12, 14, 0, 0).replace(tzinfo=utc))
		self.assertEqual(newRes.startTime, datetime.datetime(2112, 10, 12, 12, 0, 0).replace(tzinfo=utc))
		self.assertEqual(Reservation.objects.get(id=1).endTime, datetime.datetime(2112, 10, 12, 11, 59, 59).replace(tzinfo=utc))
		self.assertEqual(self.d1 in newRes.devices.all(), True)
		self.assertEqual(self.d2 in newRes.devices.all(), True)