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

from influxdb import InfluxDBClient
# pylint: disable=W0401
from influxdb.exceptions import *

import requests
import urllib3
import Tac

urllib3.disable_warnings( urllib3.exceptions.InsecureRequestWarning )


SMALL_STORAGE_LIMIT_BYTES = 4 * 2 ** 30


def getFlashSize( ):
   """
   Get the size of the flash storage on the device in bytes.
   :return: bytes of flash storage
   """
   output = Tac.run( [ '/bin/df', '-k', '--output=size',
                       '/mnt/flash/' ], stdout=Tac.CAPTURE, stderr=Tac.CAPTURE )
   size = int( output.split( '\n' )[ 1 ].strip( ) )
   return size * 1024

def createDatabase( database, client ):
   try:
      client.create_database( database )
   except requests.exceptions.ConnectionError:
      return False
   return True

def createRetentionPolicy( client, **kwargs ):
   try:
      client.create_retention_policy( **kwargs )
   except InfluxDBClientError:
      try:
         client.alter_retention_policy( **kwargs )
      except InfluxDBClientError:
         raise
   except requests.exceptions.ConnectionError:
      return False
   return True

def main( database ):
   client = InfluxDBClient( database=database )

   Tac.waitFor( lambda: createDatabase( database, client ),
                description=f"Wait for database {database} creation" )

   if getFlashSize( ) < SMALL_STORAGE_LIMIT_BYTES:
      # This limit is calculated give that after measurement over a
      # day, influx on the system consumes ~140kB / min.
      # This limit will approximately keep us to a 400MB db.
      duration = '2d'
   else:
      duration = '1w'

   Tac.waitFor(
      lambda: createRetentionPolicy(
         client, name='mm', duration=duration,
         replication=1, default=True ),
      description="Wait for creating retention policy"
   )


if __name__ == '__main__':
   import sys

   if len( sys.argv ) > 1:
      databaseName = sys.argv[ 1 ]
   else:
      databaseName = 'telegraf'

   main( databaseName )
