#!/usr/bin/env python3
# Copyright (c) 2008 Arastra, Inc.  All rights reserved.
# Arastra, Inc. Confidential and Proprietary.

""" Simple memory size test which checks that the total amount of system
memory (as seen by linux) is equivalent to the expected memory size. """

import Tac, optparse, sys, re # pylint: disable=deprecated-module

parser = optparse.OptionParser()
parser.usage = """%prog size-in-MB
'size' is an integer representing the number of MB of memory we expect, where
MB is defined as 1024*1024 bytes."""
( options, args ) = parser.parse_args()
if len( args ) != 1:
   parser.error( "One argument expect, the size of memory in MB" )
try:
   expectedSizeMB = int( args[ 0 ] )
except ValueError:
   parser.error( "Size argument must be an integer" )

meminfo = open( "/proc/meminfo" ).read() # pylint: disable=consider-using-with
totalSizeKB = int( re.search( r"MemTotal:\s+(\d+) kB", meminfo ).group( 1 ) )
totalSizeMB = totalSizeKB / 1024.0

# NOTE We assert that the total size as reported by /proc/meminfo is within
# 128 MB of what we expect it to be. The number reported by /proc/meminfo
# is not exactly the total memory size - Ed thinks this could be due to
# reserved memory areas or memory being taken by the graphics chip.
# We don't need to be incredibly accurate - the memverify diag will check
# the spd of the memory modules to see what their exact size is. This diag
# is really just to check that linux can actually see all of the available
# memory.
fudge = 128

if ( totalSizeMB > expectedSizeMB ) or ( totalSizeMB + fudge < expectedSizeMB ):
   # pylint: disable-next=consider-using-f-string
   sys.stderr.write( "Memory size is %dMB, expected %dMB\n"
                     %( totalSizeMB, expectedSizeMB ) )
   sys.exit( 1 )
