Accessing existing grains from a custom grain?

328 views
Skip to first unread message

Robert Parker

unread,
Feb 17, 2015, 5:16:55 PM2/17/15
to salt-...@googlegroups.com
I need the ability to access existing grains that are defined by the core.py grains file as well as those defined in /etc/salt/grains in my custom grain.  This custom grain runs on a Solr node and queries zookeeper from the local API to return the clusterstate.json and from there parse whether the node is active or failed or a shard leader, etc.  Except that I need to access grains that are already defined in the core.py as well as set in /etc/salt/grains in order to properly parse the data in the json.  here's a forced example, it seems that __grains__ is not available in custom grains as with custom modules.  What lib must I import to have access to already defined grains?  Also, will this custom grain always be parsed on the fly whenever there's a grains.get/grains.item call? I want the grain to contain the latest information in the clusterstate.json that it pulls from Solr/zookeeper.  For example, I would want to define a custom grain for "solrleader" that always reflects in real time whether that minion is the leader in a SolrCloud shard as defined by grabbing and parsing the clusterstate.json via the Solr API, and doing so requires knowing things like the collection name and shard is as defined in /etc/salt/grains.  Is this a chicken and egg problem?

#!/usr/bin/env python

import urllib2
import json
import socket

localhost= __grains__['id'] 
#localhost = socket.gethostname()

def getsolrcluster():
  grains = {}
  url = "http://"+localhost+":8080/solr/zookeeper?detail=true&path=%2Fclusterstate.json"
  try:
    response = urllib2.urlopen(url)
  except:
    grains['solrclusterstate']="Exception thrown. No Solr detected at http://%s:8080/solr"
  raw = response.read()
  data = json.loads(raw)
  grains['solrclusterstate']=data["znode"]["data"]
  return grains

And when I try to import the custom grain:

minion# salt-call saltutil.sync_grains
[WARNING ] Failed to import grain solrgrains, this is due most likely to a syntax error. Traceback raised:
Traceback (most recent call last):
  File "/usr/lib/python2.6/site-packages/salt/loader.py", line 925, in load_modules
    ), fn_, path, desc
  File "/var/cache/salt/minion/extmods/grains/solrgrains.py", line 7, in <module>
    localhost= __grains__['id']
NameError: name '__grains__' is not defined

 

Guillermo A Menjivar

unread,
May 15, 2015, 11:26:58 PM5/15/15
to salt-...@googlegroups.com
Dont know, you got it working. For the record, I think this will do it. This will load the grains object that the minion has defined.


import salt.config
import salt.loader

__opts__ = salt.config.minion_config('/etc/salt/minion')
__grains__ = salt.loader.grains(__opts__)
Reply all
Reply to author
Forward
0 new messages