Esempio n. 1
0
class Device(models.Model):
    name = models.CharField(max_length=30)
    device_class = models.ForeignKey(DeviceClass)
    server_name = models.CharField(max_length=30, blank=True)
    argument = models.CharField(max_length=30, blank=True)
    depends_on = models.ManyToManyField('Device',
                                        related_name='depends',
                                        symmetrical=False,
                                        blank=True)
    location = models.ForeignKey(Location)
    hidden = models.BooleanField(default=False)
    power_state = models.ForeignKey(State)

    def __unicode__(self):
        return self.name

    def __init__(self, *args, **kwargs):
        super(Device, self).__init__(*args, **kwargs)
        if not hasattr(self, 'device_class'):
            return
        c = self.device_class
        if c.device_type.value in [
                control_pb2.APC, control_pb2.PC_WIN, control_pb2.PC_LINUX,
                control_pb2.UFO, control_pb2.IPPOWER, control_pb2.IPMI
        ]:
            server = 'localhost'
        else:
            server = self.server_name
        self.service = RpcService(control_pb2.ControlService_Stub, 10021,
                                  server)
        d_pb = control_pb2.Device()
        d_pb.type = c.device_type.value
        d_pb.server = self.server_name
        d_pb.port = str(self.argument)
        self.pb = control_pb2.Device()
        self.pb.CopyFrom(d_pb)

    def send_get(self, feature_type):
        request = control_pb2.GetRequest()
        request.device.CopyFrom(self.pb)
        request.type = feature_type
        response = self.service.Get(request, timeout=10000)
        if not response.result:
            log.error('Invalide answer: ' + response.error)
        return response

    def send_set(self, feature_type, value):
        request = control_pb2.SetRequest()
        request.device.CopyFrom(self.pb)
        request.type = feature_type
        request.value = value
        response = self.service.Set(request, timeout=1000)
        if not response.result:
            log.error('Invalide answer: ' + response.error)
        return response

    def get_pwr(self):
        for d in self.depends_on.all():
            response = d.get_pwr()
            if response.value != control_pb2.POWER_ON:
                return response
        return self.send_get(control_pb2.FEAT_PWR)

    def send_pwr(self, value):
        # no protection for recursive dependencies.
        if value == control_pb2.POWER_ON:
            # power other device first
            for d in self.depends_on.all():
                d.send_pwr(value)
        response = self.send_set(control_pb2.FEAT_PWR, value)
        if response.result:
            self.power_state = State.objects.get(value=value)
            self.save()
            if value == control_pb2.POWER_OFF:
                for d in self.depends_on.all():
                    d.send_pwr(value)