def check_services(self):
        """
        Checks the status of required services

        :returns: status of the services
        :rtype: bool
        """

        logging = LogHandler(System().get_watcher_log_dir())

        # Checking the API
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        result = sock.connect_ex((self.system.get_grid_ip(), self.system.get_api_port()))

        if result == 0:
            api_status = True
            logging.logger("Status of API: ACTIVE", 4, module)
        else:
            api_status = False
            logging.logger("Status of API: INACTIVE", 4, module)

        # Checking the LOCAL_NET
        if ServiceManager().get_service_status("pimotics-local-net"):
            local_net_status = True
            logging.logger("Status of LOCAL_NET: ACTIVE", 4, module)
        else:
            local_net_status = False
            logging.logger("Status of LOCAL_NET: INACTIVE", 4, module)

        # Output result
        if api_status and local_net_status:
            return True
        else:
            return False
Example #2
0
    def __init__(self, description, name=None):
        self.module = __name__
        self.logger = LogHandler(System().get_core_log_dir())

        # properties of Class User
        self._name = name
        self.description = description
Example #3
0
    def __init__(self, user_id, distributed_on, valid_until, api_token=None):
        self.module = __name__
        self.logger = LogHandler(System().get_core_log_dir())

        # properties of Class ApiToken
        self._user_id = user_id  # foreign key to user object
        self._api_token = api_token
        self.distributed_on = distributed_on
        self.valid_until = valid_until
Example #4
0
    def __init__(self, pin_number, pin_type, bus_address, identifier=None):
        self.module = __name__
        self.logger = LogHandler(System().get_core_log_dir())

        # properties of Class User
        self._id = identifier
        self.pin_number = pin_number
        self.pin_type = pin_type
        self.bus_address = bus_address
Example #5
0
    def __init__(self, pin_id, name, type, room_name, identifier=None):
        self.module = __name__
        self.logger = LogHandler(System().get_core_log_dir())

        # properties of Class Sensor
        self._id = identifier
        self._pi_pin = pin_id
        self._room_name = room_name
        self.name = name
        self.type = type
Example #6
0
    def __init__(self):
        """
        constructor for MySQLDB
        """

        self.module = __name__
        self.settings = System().get_config_file()
        self.logger = LogHandler(System().get_model_log_dir())

        # init db
        self.db = MySQLdb.connect(host="localhost",
                                  user=self.settings['pimotics']['cluster']['config']['mysql']['user'],
                                  passwd=self.settings['pimotics']['cluster']['config']['mysql']['password'],
                                  db=self.settings['pimotics']['cluster']['config']['mysql']['database'])
Example #7
0
    def __init__(self, username, password, name, surname, email, user_access, admin_access, identifier=None,
                 joined_on=datetime.datetime.now()):
        self.module = __name__
        self.logger = LogHandler(System().get_core_log_dir())

        # properties of Class User
        self._id = identifier
        self.username = username
        self.password = password
        self.name = name
        self.surname = surname
        self.email = email
        self.joined_on = joined_on
        self.user_access = user_access
        self.admin_access = admin_access
Example #8
0
class User(object):
    """
    User class
    """

    def __init__(self, username, password, name, surname, email, user_access, admin_access, identifier=None,
                 joined_on=datetime.datetime.now()):
        self.module = __name__
        self.logger = LogHandler(System().get_core_log_dir())

        # properties of Class User
        self._id = identifier
        self.username = username
        self.password = password
        self.name = name
        self.surname = surname
        self.email = email
        self.joined_on = joined_on
        self.user_access = user_access
        self.admin_access = admin_access

    @property
    def id(self):
        """
        Creates a READ ONLY 'id' property

        :returns: id
        :rtype: int
        """

        return self._id

    def save(self):
        """
        Save/update the object to the persistent backend. It will also invalidate certain caches.

        :raises PiMoticUserNotFoundExceptionsException
        """

        db = MySQLDB()

        if self.id:
            if self._exists():
                db.execute_query("UPDATE `User` SET `password`='{0}',"
                                "`name`='{1}',`surname`='{2}',`e-mail`='{3}',"
                                "`user_access`={4}, `admin_access`={5} WHERE `id`={6};"
                                 .format(self.password, self.name, self.surname,
                                        self.email, self.user_access, self.admin_access, self.id)
                                 )
                db.commit()
            else:
                raise UserNotFoundException("Object User with name '{0}' not found in persistent database".format(self.name),
                                        self.module)
        else:
            self.logger.logger("Inserting new User into DB", 4, self.module)
            db.execute_query("INSERT INTO `User` (`username`, `password`, `name`, `surname`, `e-mail`, `joined_on`"
                            ", `user_access`, `admin_access`) VALUES ('{0}', '{1}', '{2}', '{3}', '{4}', now(), "
                            "{5}, {6});".format(self.username, self.password, self.name, self.surname, self.email,
                                                self.user_access, self.admin_access))
            db.commit()

    def serialize(self):
        """
        Returns the object in a dict/json style

        :returns: a serialized object
        :rtype: dict
        """

        return {
            "id": self.id,
            "username": self.username,
            "password": self.password,
            "name": self.name,
            "surname": self.surname,
            "e-mail": self.email,
            "joined_on": self.joined_on,
            "user_access": self.user_access,
            "admin_access": self.admin_access
        }

    def delete(self):
        """
        Deletes the object from the persistent backend. It will also invalidate certain caches.

        :raises UserNotFoundException
        """

        db = MySQLDB()

        if self._exists():
            mysql_check = self._select()

            if mysql_check:
                db.execute_query("DELETE FROM `User` WHERE `id`={0};".format(self.id))
                db.commit()
            else:
                raise UserNotFoundException("Object User with name '{0}' not found in the persistent backend"
                                        .format(self.name), self.module)
        else:
            raise UserNotFoundException("Object User with name '{0}' is a new object, "
                                    "and can't be deleted from the persistent database"
                                    .format(self.name), self.module)

    def _select(self):
        """
        Selects the object from the persistent backend.

        :returns: mysql database result
        :rtype: tuple
        """

        db = MySQLDB()
        mysql_check = db.execute_query("SELECT * FROM `User` WHERE `id`={0};".format(self.id)).fetchall()
        return mysql_check

    def _exists(self):
        """
        Checks if the object exists in the persistent backend

        :returns: if the local objects exists in the backend
        :rtype: bool
        """

        mysql_exists = self._select()

        if len(mysql_exists) == 1:
            return True
        else:
            return False

    def discard(self):
        """
        Discard the local object/changes and get object from persistent backend.
        It will also invalidate certain caches.
        """

        # get object
        if self._exists():
            mysql_user = self._select()

            # reset attributes
            self._id = mysql_user[0][0]
            self.username = mysql_user[0][1]
            self.password = mysql_user[0][2]
            self.name = mysql_user[0][3]
            self.surname = mysql_user[0][4]
            self.email = mysql_user[0][5]
            self.joined_on = mysql_user[0][6]
            self.user_access = mysql_user[0][7]
            self.admin_access = mysql_user[0][8]
        else:
            raise UserNotFoundException("Object User with name '{0}' not found in the persistent backend"
                                        .format(self.name), self.module)
Example #9
0
class MySQLDB:
    """
    initiates MySQLDB server connection
    """

    def __init__(self):
        """
        constructor for MySQLDB
        """

        self.module = __name__
        self.settings = System().get_config_file()
        self.logger = LogHandler(System().get_model_log_dir())

        # init db
        self.db = MySQLdb.connect(host="localhost",
                                  user=self.settings['pimotics']['cluster']['config']['mysql']['user'],
                                  passwd=self.settings['pimotics']['cluster']['config']['mysql']['password'],
                                  db=self.settings['pimotics']['cluster']['config']['mysql']['database'])

    def execute_query(self, mysql_query):
        """
        Execute a database query

        :param mysql_query: a mysql database query
        :type mysql_query: str

        :returns: result from a mysql database
        :rtype: tuple

        :raises PiMoticsException
        """

        self.logger.logger("Executing DB query", 4, self.module)
        try:
            # init cursor
            cur = self.db.cursor()

            # execute query
            cur.execute(mysql_query)

            return cur

        except MySQLdb.Error as e:
            raise MySqlException("A MySQL unexpected Error occurred: {0}".format(e[1]), self.module)

    def commit(self):
        """
        Perform a mysql database commit
        """

        # commit if insert
        self.db.commit()

    def __del__(self):
        """
        Close the database connection when garbage collector is passing
        """

        self.logger.logger("Closing DB connection", 4, self.module)
        self.db.close()
Example #10
0
class Sensor(object):
    """
    Sensor class
    """

    def __init__(self, pin_id, name, type, room_name, identifier=None):
        self.module = __name__
        self.logger = LogHandler(System().get_core_log_dir())

        # properties of Class Sensor
        self._id = identifier
        self._pi_pin = pin_id
        self._room_name = room_name
        self.name = name
        self.type = type

    @property
    def id(self):
        """
        Creates a READ ONLY 'id' property

        :returns: identifier of PiPin
        :rtype: int
        """

        return self._id

    @property
    def pi_pin(self):  # @TODO: link to class
        """
        Foreign key to PiPin object through pin_id.

        :returns: PiPin object
        :rtype: PiPin
        """

        return self._id

    def save(self): # @TODO: save
        """
        Save/update the object to the persistent backend. It will also invalidate certain caches.
        """

        db = MySQLDB()

        if self._exists():
            db.execute_query("UPDATE `PI_pin` SET `pin_number`='{0}', WHERE `id`={1};"
                             .format(self.pin_number, self.id)
                             )
            db.commit()
        else:
            self.logger.logger("Inserting new PiPin into DB", 4, self.module)
            db.execute_query("INSERT INTO `PI_pin`(`pin_number`) VALUES ('{0}');"
                             .format(self.pin_number))
            db.commit()

    def serialize(self): # @TODO: serialize
        """
        Returns the object in a dict/json style

        :returns: a serialized object
        :rtype: dict
        """

        return {
            "id": self.id,
            "pin_number": self.pin_number
        }

    def delete(self): # @TODO: delete
        """
        Deletes the object from the persistent backend. It will also invalidate certain caches.

        :raises SensorNotFoundException
        """

        db = MySQLDB()

        if self._exists():
            mysql_check = self._select()

            if mysql_check:
                db.execute_query("DELETE FROM `PI_pin` WHERE `id`='{0}';".format(self.id))
                db.commit()
            else:
                raise SensorNotFoundException("Object PiPin with id '{0}' not found in the persistent database"
                                              .format(self.id), self.module)
        else:
            raise SensorNotFoundException("Object PiPin with id '{0}' is a new object, "
                                          "and can't be deleted from the persistent database"
                                          .format(self.id), self.module)

    def _select(self): # @TODO: _select
        """
        Selects the object from the persistent backend.

        :returns: mysql database result
        :rtype: tuple
        """

        db = MySQLDB()
        mysql_check = db.execute_query("SELECT * FROM `PI_pin` WHERE `id`='{0}';".format(self.id)).fetchall()
        return mysql_check

    def _exists(self): # @TODO: _exists
        """
        Checks if the object exists in the persistent backend

        :returns: if the local objects exists in the backend
        :rtype: bool
        """

        mysql_exists = self._select()

        if len(mysql_exists) == 1:
            return True
        else:
            return False

    def discard(self): # @TODO: discard
        """
        Discard the local object/changes and get object from persistent backend.
        It will also invalidate certain caches.
        """

        # get object
        if self._exists():
            mysql_user = self._select()

            # reset attributes
            self._id = mysql_user[0][0]
            self.pin_number = mysql_user[0][1]
        else:
            raise SensorNotFoundException("Object PiPin with id '{0}' not found in the persistent database"
                                          .format(self.id), self.module)
Example #11
0
class ApiToken(object):
    """
    ApiToken class
    """

    def __init__(self, user_id, distributed_on, valid_until, api_token=None):
        self.module = __name__
        self.logger = LogHandler(System().get_core_log_dir())

        # properties of Class ApiToken
        self._user_id = user_id  # foreign key to user object
        self._api_token = api_token
        self.distributed_on = distributed_on
        self.valid_until = valid_until

    @property
    def api_token(self):
        """
        Creates a READ ONLY 'api_token' property

        :returns: api_token
        :rtype: str
        """

        return self._api_token

    @property
    def user(self):
        """
        Foreign key to user object through user_id.

        :returns: a User object that is connected to this ApiToken
        :rtype: User
        """

        return UserList().get_by_id(self._user_id)

    def save(self):
        """
        Save/update the object to the persistent backend. It will also invalidate certain caches.

        :raises ApiTokenNotFoundException
        """

        db = MySQLDB()

        if self.api_token:
            if self._exists():
                db.execute_query("UPDATE `API_Token` SET "
                                 "`user_id`={0},`distributed_on`='{1}',`valid_until`='{2}' WHERE `api_token`='{3}';"
                                 .format(self.user_id, self.distributed_on, self.valid_until, self.api_token)
                                 )
                db.commit()
            else:
                raise ApiTokenNotFoundException("Object ApiToken with api_token '{0}' "
                                                "not found in the persistent backend".format(self.api_token),
                                                self.module)
        else:
            self.logger.logger("Inserting new ApiToken into DB", 4, self.module)
            db.execute_query("INSERT INTO `API_Token` (`user_id`, `api_token`, `distributed_on`, `valid_until`) VALUES "
                             "({0}, '{1}', '{2}', '{3}';"
                             .format(self.user_id, self._api_token, self.distributed_on, self.valid_until)
                             )
            db.commit()

    def serialize(self):
        """
        Returns the object in a dict/json style

        :returns: a serialized object
        :rtype: dict
        """

        return {
            "user": self.user.serialize(),
            "api_token": self.api_token,
            "distributed_on": self.distributed_on,
            "valid_until": self.valid_until
        }

    def delete(self):
        """
        Deletes the object from the persistent backend. It will also invalidate certain caches.

        :raises ApiTokenNotFoundException
        """

        db = MySQLDB()

        if self._exists():
            mysql_check = self._select()

            if mysql_check:
                db.execute_query("DELETE FROM `API_Token` WHERE `api_token`='{0}';".format(self.api_token))
                db.commit()
            else:
                raise ApiTokenNotFoundException(
                        "Object ApiToken with api_token '{0}' not found in the persistent database"
                        .format(self.api_token), self.module)
        else:
            raise ApiTokenNotFoundException(
                    "Object ApiToken with api_token '{0}' is a new object, "
                    "and can't be deleted from the persistent database"
                    .format(self.api_token), self.module)

    def _select(self):
        """
        Selects the object from the persistent backend.

        :returns: mysql database result
        :rtype: tuple
        """

        db = MySQLDB()
        mysql_check = db.execute_query("SELECT * FROM `API_Token` WHERE `api_token`='{0}';".format(self.api_token))\
            .fetchall()
        return mysql_check

    def _exists(self):
        """
        Checks if the object exists in the persistent backend

        :returns: if the local objects exists in the backend
        :rtype: bool
        """

        mysql_exists = self._select()

        if len(mysql_exists) == 1:
            return True
        else:
            return False

    def discard(self):
        """
        Discard the local object/changes and get object from persistent backend. It will also invalidate certain caches.
        """

        # get object
        if self._exists():
            mysql_user = self._select()

            # reset attributes
            self.user_id = mysql_user[0][0]
            self._api_token = mysql_user[0][1]
            self.distributed_on = mysql_user[0][2]
            self.valid_until = mysql_user[0][3]
        else:
            raise ApiTokenNotFoundException("Object ApiToken with api_token '{0}' not found in the persistent database"
                                            .format(self.api_token), self.module)
        # Output result
        if api_status and local_net_status:
            return True
        else:
            return False


if __name__ == "__main__":
    """
    Executes the watcher, checks the services and controls the PiMotics core watcher
    """

    service_mode = sys.argv[1]
    watcher = Watcher()
    module = "main-watcher"
    logging = LogHandler(System().get_webapps_log_dir())
    logging.logger("Started watcher ...", 3, module)

    if service_mode == "check":
        amount_tries = 0
        max_tries = 10

        logging.logger("Checking services ...", 3, module)
        while True:
            if not watcher.check_services():
                if max_tries > amount_tries:
                    logging.logger("One of the PiMotics services is down! Checking again in a few...", 2, module)
                    max_tries += 1
                    time.sleep(5)
                else:
                    logging.logger("Some PiMotics services are down! Max tries have been exceeded, shutting down ...",
Example #13
0
class Room(object):
    """
    Room class
    """

    def __init__(self, description, name=None):
        self.module = __name__
        self.logger = LogHandler(System().get_core_log_dir())

        # properties of Class User
        self._name = name
        self.description = description

    @property
    def name(self):
        """
        Creates a READ ONLY 'name' property

        :returns: name
        :rtype: str
        """

        return self._name

    def save(self):
        """
        Save/update the object to the persistent backend. It will also invalidate certain caches.
        """

        db = MySQLDB()

        if self._exists():
            db.execute_query("UPDATE `Room` SET `description`='{0}', WHERE `name`={1};"
                             .format(self.description, self.name)
                             )
            db.commit()
        else:
            self.logger.logger("Inserting new Room into DB", 4, self.module)
            db.execute_query("INSERT INTO `Room`(`name`, `description`) VALUES ('{0}', '{1}');"
                             .format(self.name, self.description))
            db.commit()

    def serialize(self):
        """
        Returns the object in a dict/json style

        :returns: a serialized object
        :rtype: dict
        """

        return {
            "name": self.name,
            "description": self.description
        }

    def delete(self):
        """
        Deletes the object from the persistent backend. It will also invalidate certain caches.

        :raises RoomNotFoundException
        """

        db = MySQLDB()

        if self._exists():
            mysql_check = self._select()

            if mysql_check:
                db.execute_query("DELETE FROM `Room` WHERE `name`='{0}';".format(self.name))
                db.commit()
            else:
                raise RoomNotFoundException("Object Room with name '{0}' not found in the persistent database"
                                            .format(self.name), self.module)
        else:
            raise RoomNotFoundException("Object Room with name '{0}' is a new object, "
                                        "and can't be deleted from the persistent database"
                                        .format(self.name), self.module)

    def _select(self):
        """
        Selects the object from the persistent backend.

        :returns: mysql database result
        :rtype: tuple
        """

        db = MySQLDB()
        mysql_check = db.execute_query("SELECT * FROM `Room` WHERE `name`='{0}';".format(self.name)).fetchall()
        return mysql_check

    def _exists(self):
        """
        Checks if the object exists in the persistent backend

        :returns: if the local objects exists in the backend
        :rtype: bool
        """

        mysql_exists = self._select()

        if len(mysql_exists) == 1:
            return True
        else:
            return False

    def discard(self):
        """
        Discard the local object/changes and get object from persistent backend.
        It will also invalidate certain caches.

        :raises RoomNotFoundException
        """

        # get object
        if self._exists():
            mysql_user = self._select()

            # reset attributes
            self._name = mysql_user[0][0]
            self.description = mysql_user[0][1]
        else:
            raise RoomNotFoundException("Object Room with name '{0}' not found in the persistent database"
                                        .format(self.name), self.module)