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

import AgentSupport
import Tac

pathsToDump = [ ( "debug/pprof/heap", "heap.pprof" ),
                ( "debug/vars", "vars.json" ),
                ( "rest/Orphanage/", "orphans" ),
                ( "meta/collSize/", "collSize" ),
                ( "debug/mounts", "mounts" ),
                ( "meta/paths", "paths" ),
                ( "dataStruct/allAftUsers", "aftUsers" ),
                ( "debug/pprof/profile?seconds=30", "profile_30s.pprof" ),
                ( "debug/pprof/goroutine?debug=2", "goroutine.pprof" ) ]

filepath = "/var/log/%s_dump.%s"
agentName = 'Gribi'

def dumpVar( path, filestring ):
   # The port (6062) is the hardcoded port opened by Gribi
   argv = [ 'curl', '-s', 'localhost:6062/%s' % path ]
   try:
      with open( filepath % ( agentName, filestring ), "wb" ) as f:
         Tac.run( argv, stdout=f, stderr=f, text=False )
   except Tac.SystemCommandError as e:
      if e.error == 7:
         print( "Connection denied. Is %s running?" % agentName )
      else:
         print( "Curl error dumping variable: %s" % e.error )
      return False
   return True

def agentLogFunction():
   # Iterate over and collect different debug vars into corresponding files
   for t in pathsToDump:
      dumpVar( t[ 0 ], t[ 1 ] )

if __name__ == '__main__':
   AgentSupport.main( agentName, agentLogFunction=agentLogFunction )

