Esempio n. 1
0
def setup_db_department():
    """Create the database for Department table testing.

    Args:
        None

    Returns:
        None

    """
    # Initialize key variables
    idx_department = 1

    # Create a dict of all the expected values
    expected = {
        'enabled': 1,
        'name': general.hashstring(general.randomstring()),
        'idx_department': idx_department,
        'code': general.hashstring(general.randomstring()),
    }

    # Drop the database and create tables
    initialize_db()

    # Insert data into database
    data = Department(code=general.encode(expected['code']),
                      name=general.encode(expected['name']))
    database = db.Database()
    database.add_all([data], 1048)

    # Return
    return expected
Esempio n. 2
0
    def post(self, save=True, data=None):
        """Post data to central server.

        Args:
            save: When True, save data to cache directory if postinf fails
            data: Data to post. If None, then uses self.data

        Returns:
            success: "True: if successful

        """
        # Initialize key variables
        success = False
        response = False
        timestamp = self.data['timestamp']
        id_agent = self.data['id_agent']

        # Create data to post
        if data is None:
            data = self.data

        # Post data save to cache if this fails
        try:
            result = requests.post(self.url, json=data)
            response = True
        except:
            if save is True:
                # Create a unique very long filename to reduce risk of
                devicehash = general.hashstring(self.data['devicename'], sha=1)
                filename = ('%s/%s_%s_%s.json') % (self.cache_dir, timestamp,
                                                   id_agent, devicehash)

                # Save data
                with open(filename, 'w') as f_handle:
                    json.dump(data, f_handle)

        # Define success
        if response is True:
            if result.status_code == 200:
                success = True

        # Log message
        if success is True:
            log_message = ('Agent "%s" successfully contacted server %s'
                           '') % (self.name(), self.url)
            log.log2info(1027, log_message)
        else:
            log_message = ('Agent "%s" failed to contact server %s'
                           '') % (self.name(), self.url)
            log.log2warning(1028, log_message)

        # Return
        return success
Esempio n. 3
0
    def _id_agent(self, devicename):
        """Generate an id_agent for a device.

        Args:
            devicename: Name of device

        Returns:
            id_agent: ID agent to use

        """
        # Get ID agent to use
        id_agent = general.hashstring('{}_SIM_CARD_ID'.format(devicename))
        return id_agent
Esempio n. 4
0
def setup_db_device():
    """Create the database for Device table testing.

    Args:
        None

    Returns:
        None

    """
    # Initialize key variables
    idx_device = 1

    # Create a dict of all the expected values
    expected = {
        'devicename': general.hashstring(general.randomstring()),
        'description': general.hashstring(general.randomstring()),
        'ip_address': general.hashstring('100.100.100.100'),
        'idx_device': idx_device,
        'exists': True,
        'enabled': 1
    }

    # Drop the database and create tables
    initialize_db()

    # Insert data into database
    data = Device(description=general.encode(expected['description']),
                  devicename=general.encode(expected['devicename']),
                  ip_address=general.encode(expected['ip_address']),
                  enabled=expected['enabled'])
    database = db.Database()
    database.add_all([data], 1019)

    # Return
    return expected
Esempio n. 5
0
def setup_db_agent():
    """Create the database for Agent table testing.

    Args:
        None

    Returns:
        None

    """
    # Initialize key variables
    idx_agent = 1

    # Get an agent ID
    id_agent = general.hashstring('_MDL_TEST_')

    # Create a dict of all the expected values
    expected = {
        'id_agent': id_agent,
        'name': general.hashstring(general.randomstring()),
        'idx_agent': idx_agent,
        'enabled': 1
    }

    # Drop the database and create tables
    initialize_db()

    # Insert data into database
    data = Agent(id_agent=general.encode(expected['id_agent']),
                 name=general.encode(expected['name']),
                 enabled=expected['enabled'])
    database = db.Database()
    database.add_all([data], 1045)

    # Return
    return (id_agent, expected)
Esempio n. 6
0
def generate_id_agent():
    """SAMPLE - Generate an id_agent.

    Args:
        None

    Returns:
        id_agent: the UID

    """
    #########################################################################
    #########################################################################
    # NOTE: In production you'd need to generate the id_agent value from
    # a random string
    #########################################################################
    #########################################################################
    id_agent = general.hashstring('_MDL_TEST_')

    # Return
    return id_agent
Esempio n. 7
0
    def __init__(self, config, devicename, id_agent, timestamp=None):
        """Method initializing the class.

        Args:
            config: ConfigAgent configuration object
            agent_name: Name of agent
            devicename: Devicename that the agent applies to
            id_agent: ID of the agent running on the device
            timestamp: The timestamp that should be used

        Returns:
            None

        """
        # Initialize key variables
        self.data = defaultdict(lambda: defaultdict(dict))
        agent_name = config.agent_name()

        # Add timestamp
        if timestamp is None:
            self.data['timestamp'] = general.normalized_timestamp()
        else:
            self.data['timestamp'] = int(timestamp)
        self.data['id_agent'] = id_agent
        self.data['agent'] = agent_name
        self.data['devicename'] = devicename

        # Create an object for API interaction
        self._api = ReferenceSampleAPI(config)

        # Create the cache directory
        self.cache_dir = config.agent_cache_directory()
        if os.path.exists(self.cache_dir) is False:
            os.mkdir(self.cache_dir)

        # All cache files created by this agent will end with this suffix.
        devicehash = general.hashstring(self.data['devicename'], sha=1)
        self.cache_suffix = ('%s_%s.json') % (id_agent, devicehash)
Esempio n. 8
0
    def test_hashstring(self):
        """Create a UTF encoded SHA hash string."""
        # Initialize key variables
        test_string = 'banana'
        test_string_encoded = bytes(test_string.encode())
        hasher = hashlib.sha256()
        hasher.update(test_string_encoded)
        expected = hasher.hexdigest()
        result = general.hashstring(test_string)
        self.assertEqual(result, expected)

        hasher = hashlib.sha512()
        hasher.update(test_string_encoded)
        expected = hasher.hexdigest()
        result = general.hashstring(test_string, sha=512)
        self.assertEqual(result, expected)
        result = general.hashstring(test_string, sha=512, utf8=True)
        self.assertEqual(result, expected.encode())

        hasher = hashlib.sha256()
        hasher.update(test_string_encoded)
        expected = hasher.hexdigest()
        result = general.hashstring(test_string, sha=256)
        self.assertEqual(result, expected)
        result = general.hashstring(test_string, sha=256, utf8=True)
        self.assertEqual(result, expected.encode())

        hasher = hashlib.sha224()
        hasher.update(test_string_encoded)
        expected = hasher.hexdigest()
        result = general.hashstring(test_string, sha=224)
        self.assertEqual(result, expected)
        result = general.hashstring(test_string, sha=224, utf8=True)
        self.assertEqual(result, expected.encode())

        hasher = hashlib.sha384()
        hasher.update(test_string_encoded)
        expected = hasher.hexdigest()
        result = general.hashstring(test_string, sha=384)
        self.assertEqual(result, expected)
        result = general.hashstring(test_string, sha=384, utf8=True)
        self.assertEqual(result, expected.encode())

        hasher = hashlib.sha1()
        hasher.update(test_string_encoded)
        expected = hasher.hexdigest()
        result = general.hashstring(test_string, sha=1)
        self.assertEqual(result, expected)
        result = general.hashstring(test_string, sha=1, utf8=True)
        self.assertEqual(result, expected.encode())
Esempio n. 9
0
def setup_db_datapoint():
    """Create the database for Datapoint table testing.

    Args:
        None

    Returns:
        results: List of dicts of values to expect

    """
    # Initialize key variables
    idx_datapoint = 1
    results = []
    timestamp = general.normalized_timestamp()
    id_datapoint = general.hashstring(general.randomstring())
    devicename = general.hashstring(general.randomstring())
    id_agent = general.hashstring(general.randomstring())
    devicename = general.randomstring()
    agent_name = general.randomstring()

    # Drop the database and create tables
    initialize_db()

    # Initialize agent variables
    agent_data = {}
    agent_data['devicename'] = devicename
    agent_data['id_agent'] = id_agent
    agent_data['agent'] = agent_name
    agent_data['timestamp'] = timestamp
    (idx_device, idx_agent) = setup_db_deviceagent(agent_data,
                                                   initialize=False)

    # Get DeviceAgent index value
    deviceagent = hagent.GetDeviceAgent(idx_device, idx_agent)
    idx_deviceagent = deviceagent.idx_deviceagent()

    # Create dict of expected results
    expected = {
        'value': 100,
        'idx_datapoint': idx_datapoint,
        'timestamp': timestamp
    }

    # Insert Department data into database
    dept_data = Department(code=general.randomstring().encode())
    database = db.Database()
    database.add_all([dept_data], 1035)

    # Insert Billcode data into database
    bill_data = Billcode(code=general.randomstring().encode())
    database = db.Database()
    database.add_all([bill_data], 1039)

    # Insert Datapoint data into database
    new_data = Datapoint(idx_deviceagent=idx_deviceagent,
                         id_datapoint=general.encode(id_datapoint))
    database = db.Database()
    database.add_all([new_data], 1072)

    # Add value to expected
    expected['id_datapoint'] = id_datapoint
    results.append(expected)

    # Return
    return results