def main(): admin.init( base.ResourceHandler( GoogleCredentials, handler=GoogleCredentialsHandler, ), admin.CONTEXT_APP_AND_USER, )
def handle( endpoint, handler=AdminExternalHandler, context_info=admin.CONTEXT_APP_ONLY, ): """ Handle request. :param endpoint: REST endpoint :param handler: REST handler :param context_info: :return: """ real_handler = type( handler.__name__, (handler, ), {'endpoint': endpoint}, ) admin.init(real_handler, ctxInfo=context_info)
name = self.callerArgs.id logger.info('DEBUG %s' % name) new = en.Entity(ENDPOINT, name, namespace=self.appName, owner=self.userName) for arg in required_args: new[arg] = self.callerArgs[arg] for arg in optional_args: if arg in ['disabled']: next try: new[arg] = self.callerArgs[arg] except: pass en.setEntity(new, sessionKey = self.getSessionKey()) def handleRemove(self, confInfo): name = self.callerArgs.id en.deleteEntity(ENDPOINT, name, namespace=self.appName, owner=self.userName, sessionKey = self.getSessionKey()) admin.init(DMBackfillHandler, admin.CONTEXT_APP_ONLY)
self.shouldAutoList = False def setup(self): self.supportedArgs.addOptArg('*') def handleList(self, confInfo): app_conf = AppConf(splunk.getLocalServerInfo(), self.getSessionKey()) config = app_conf.get_config(self.callerArgs.id) settings = config['jirasend'] if 'jirasend' in config else {} item = confInfo['jirasend'] item['jira_url'] = settings['jira_url'] if settings['jira_url'] else 'http://your.server/' item['jira_username'] = settings['jira_username'] if settings['jira_username'] else '' item['jira_password'] = PASSWORD_PLACEHOLDER def handleEdit(self, confInfo): if self.callerArgs.id == 'jirasend': app_conf = AppConf(splunk.getLocalServerInfo(), self.getSessionKey()) settings = app_conf.get_settings(self.callerArgs.id) settings[self.callerArgs.id] = {} if 'jira_url' in self.callerArgs: settings[self.callerArgs.id]['jira_url'] = self.callerArgs['jira_url'][0] if 'jira_username' in self.callerArgs: settings[self.callerArgs.id]['jira_username'] = self.callerArgs['jira_username'][0] if 'jira_password' in self.callerArgs: password = self.callerArgs['jira_password'][0] if password and password != PASSWORD_PLACEHOLDER: settings[app_conf.password_store] = password app_conf.update_settings(self.callerArgs.id, settings) admin.init(InstallHandler, admin.CONTEXT_APP_ONLY)
def main(): admin.init(GoogleCloudMonitorMetrics, admin.CONTEXT_NONE)
'aws_iam_role', 'metric_dimensions', 'metric_names', 'metric_namespace', 'period', 'polling_interval', 'sourcetype', 'statistics', 'disabled', 'use_metric_format', ] GROUP_FIELDS = [ 'metric_dimensions', 'metric_names', 'metric_namespace', 'statistics' ] class InputsProxyHandler(BaseInputRestHandler): def __init__(self, *args, **kwargs): self.opt_args = ARGS self.required_args = [] self.group_fields = GROUP_FIELDS self.input_name = 'aws_cloudwatch' BaseInputRestHandler.__init__(self, *args, **kwargs) return admin.init(InputsProxyHandler, admin.CONTEXT_APP_ONLY)
en.setEntity(ent, self.getSessionKey(), uri=ent.id + '/acl') ent = self.get() confItem = confInfo[self.callerArgs.id] acl = copy.deepcopy(meta) confItem.actions = self.requestedAction confItem.setMetadata(admin.EAI_ENTRY_ACL, acl) except splunk.ResourceNotFound as ex: logger.exception('handleACL Failed - arguments = %s, exception = %s' % (self.callerArgs, ex)) def get(self): app, user = self._namespace_and_owner() return en.getEntity(self._endpoint, self.callerArgs.id, namespace=app, owner=user, sessionKey=self.getSessionKey()) @property def _endpoint(self): return ENDPOINT def _namespace_and_owner(self): app = self.appName user = self.userName return app, user admin.init(EventgenHandler, admin.CONTEXT_APP_ONLY)
import aws_bootstrap_env import splunk.admin as admin from splunktalib.rest_manager import multimodel import aws_settings_base_rh class SQSLogging(aws_settings_base_rh.AWSLogging): keyMap = {'level': 'log_level'} class SQSSettings(multimodel.MultiModel): endpoint = "configs/conf-aws_sqs" modelMap = { 'logging': SQSLogging, } if __name__ == "__main__": admin.init( multimodel.ResourceHandler(SQSSettings), admin.CONTEXT_APP_AND_USER, )
configured = stanza[KEY_CONFIGURED_VERSION] # obtain version from app conf file if STANZA_VERSION in appConf: stanza = appConf[STANZA_VERSION] logger.info("%s %s" % (STANZA_VERSION, stanza)) if KEY_VERSION in stanza: current = stanza[KEY_VERSION] logger.info("configured %s, current %s" % (configured, current)) return (configured, current) # handler for reload def handleReload(self, confInfo): logger.info("reset requested %s" % self.requestedAction) (configured, current) = self.getVersions() if configured == current: # reset is_configured to true in app.conf when configured_version value in setup conf file is equal to version value in app conf file. postargs = {'configured': True} response, content = splunk.rest.simpleRequest( '/apps/local/splunk_app_for_nix', self.getSessionKey(), postargs=postargs) logger.info("reset completed %s" % (response, )) # initialize the handler admin.init(ResetApp, admin.CONTEXT_APP_AND_USER)
import splunk.admin as admin import sc_rest import core.manager logger = core.manager.setup_logging('scHeadlinesHandler') class ScHeadlinesHandler(sc_rest.BaseResource): required_args = ['alert_name', 'message', 'label'] optional_args = ['description', 'disabled'] endpoint = 'admin/conf-headlines' if __name__ == "__main__": admin.init(sc_rest.ResourceHandler(ScHeadlinesHandler), admin.CONTEXT_APP_ONLY)
if to_remove in cleaned_params: del cleaned_params[to_remove] # Return the cleaned parameters return cleaned_params @staticmethod def stringToIntegerOrDefault( str_value, default_value=None ): """ Converts the given string to an integer or returns none if it is not a valid integer. Arguments: str_value -- A string value of the integer to be converted. default_value -- The value to be used if the string is not an integer. """ # If the value is none, then don't try to convert it if str_value is None: return default_value # Try to convert the string to an integer try: return int(str(str_value).strip()) except ValueError: # Return none if the value could not be converted return default_value # initialize the handler if __name__ == "__main__": admin.init(WebsiteMonitoringRestHandler, admin.CONTEXT_NONE)
item['jira_password'] = PASSWORD_PLACEHOLDER for k in DEFAULT_SETTINGS: item['default_' + k] = jira_settings.get(k, '') item['import'] = '0' def handleEdit(self, confInfo): if self.callerArgs.id == 'jira': jira_settings = get_jira_settings(splunk.getLocalServerInfo(), self.getSessionKey()) if 'jira_url' in self.callerArgs: jira_settings['jira_url'] = self.callerArgs['jira_url'][0] if 'jira_username' in self.callerArgs: jira_settings['jira_username'] = self.callerArgs['jira_username'][0] if 'jira_password' in self.callerArgs: password = self.callerArgs['jira_password'][0] if password and password != PASSWORD_PLACEHOLDER: jira_settings['jira_password'] = password for k in DEFAULT_SETTINGS: if 'default_' + k in self.callerArgs: jira_settings[k] = self.callerArgs['default_' + k][0] if not validate_jira_settings(jira_settings): raise admin.ArgValidationException, "Error connecting to JIRA server" update_jira_settings(jira_settings, splunk.getLocalServerInfo(), self.getSessionKey()) if 'import' in self.callerArgs and self.callerArgs['import'][0] in ('1', 'true'): try: generate_jira_dialog(jira_settings, splunk.getLocalServerInfo(), self.getSessionKey()) except Exception, e: raise admin.AdminManagerException("Error importing settings from Jira, check server URL and credentials: " + str(e)) admin.init(JiraAlertsInstallHandler, admin.CONTEXT_APP_ONLY)
from splunk import admin import sc_rest class OpcServerConfRes(object): endpoint = '/admin/conf-opcservers' optional_args = [] required_args = ['dcomhost', 'domain', 'user', 'password', 'progid', 'clsid'] transient_args = [] if __name__ == "__main__": admin.init(sc_rest.ResourceHandler(OpcServerConfRes), admin.CONTEXT_NONE)
def main(): admin.init(GoogleSubscriptions, admin.CONTEXT_NONE)
en.setEntity(ent) def handleCreate(self, confInfo): name = self.callerArgs.id new = en.Entity(ENDPOINT, name, namespace=self.appName, owner=self.userName) for arg in required_args: new[arg] = self.callerArgs[arg] for arg in optional_args: try: new[arg] = self.callerArgs[arg] except: pass en.setEntity(new, sessionKey = self.getSessionKey()) def handleRemove(self, confInfo): name = self.callerArgs.id en.deleteEntity(ENDPOINT, name, namespace=self.appName, owner=self.userName, sessionKey = self.getSessionKey()) admin.init(UnixHandler, admin.CONTEXT_APP_ONLY)
import splunk.admin as admin import sc_rest import core.manager logger = core.manager.setup_logging('splunk') class AlertsOverlayHandler(sc_rest.BaseResource): required_args = ['threshold_type'] optional_args = ['business_impact', 'description', 'escalation', 'remediation', 'threshold_min', 'threshold_max', 'threshold_unit'] endpoint = 'admin/conf-alert_overlay' if __name__ == "__main__": admin.init(sc_rest.ResourceHandler(AlertsOverlayHandler), admin.CONTEXT_APP_ONLY)
(v, repr(e))) logger.debug("%s Writing new config for %s: %s", facility, config_id, str(new_config)) try: # Write the config stanza self.writeConf(config_file, config_id, new_config) except BaseException as e: logger.exception("%s Error writing config: %s", facility, e) # Update settings once they are saved by the user def handleRemove(self, confInfo): facility = config_file + '_delete' logger = setup_logger(app_config["log_level"], setup_log, facility) logger.debug(config_file + " delete handler started") config_id = self.callerArgs.id logger.debug("Config: %s" % config_id) try: en.deleteEntity('/configs/conf-' + config_file, self.callerArgs.id, namespace=self.appName, owner=self.userName, sessionKey=self.getSessionKey()) except BaseException as e: logger.exception(e) # initialize the handler admin.init(SetupApp, admin.CONTEXT_APP_AND_USER)
confInfo[stanza].append(key, val) ''' After user clicks Save on setup screen, take updated parameters, normalize them, and save them somewhere ''' def handleEdit(self, confInfo): name = self.callerArgs.id args = self.callerArgs if self.callerArgs.data['C_KEY'][0] in [None, '']: self.callerArgs.data['C_KEY'][0] = 'ABC123' if self.callerArgs.data['C_SECRET'][0] in [None, '']: self.callerArgs.data['C_SECRET'][0] = '1234567890abcefgh1234567890abcdef' if self.callerArgs.data['REDIRECT_URI'][0] in [None, '']: self.callerArgs.data['REDIRECT_URI'][0] = 'http://127.0.0.1:8080' ''' Since we are using a conf file to store parameters, write them to the [setupentity] stanza in <appname>/local/myappsetup.conf ''' self.writeConf('appconfig', 'Authentication', self.callerArgs.data) self.writeConf('appconfig', 'Activity', self.callerArgs.data) # initialize the handler admin.init(ConfigApp, admin.CONTEXT_NONE)
force = False if FORCE in self.callerArgs: force = bundle_paths.parse_boolean(self.callerArgs[FORCE][0]) try: bundle, status = appbuilder.installApp(location, force) except splunk.RESTException as e: raise admin.InternalException(e.msg) upgraded = (status == bundle_paths.BundleInstaller.STATUS_UPGRADED) appName = bundle.name(raw=True) or '' confInfo[appName].append('name', appName) confInfo[appName].append('location', bundle.location() or '') confInfo[appName].append('status', 'upgraded' if upgraded else 'installed') confInfo[appName].append('source_location', location) if not upgraded: reloader = 'apps/local/_reload' else: reloader = 'apps/local/%s/_reload' % urllib.quote(bundle.name()) rest.simpleRequest(reloader, sessionKey=self.getSessionKey()) def handleList(self, confInfo): pass admin.init(AppInstallHandler, admin.CONTEXT_APP_ONLY)
# read param 'count', 'offset' ] _interface_impl = None def __init__(self, *args, **kwargs): super(self.__class__, self).__init__(*args, **kwargs) self._interface_impl = EMAlertInterfaceImpl(self.getSessionKey()) def setup(self): if self.requestedAction == admin.ACTION_CREATE or self.requestedAction == admin.ACTION_EDIT: for arg in self.WRITE_REQUIRED_PARAMS: self.supportedArgs.addReqArg(arg) if self.requestedAction != admin.ACTION_REMOVE: for arg in self.READ_OPTIONAL_PARAMS: self.supportedArgs.addOptArg(arg) def handleList(self, confInfo): self._interface_impl.handleList(self.callerArgs, confInfo) def handleEdit(self, confInfo): self._interface_impl.handleEdit(self.callerArgs, confInfo) def handleCreate(self, confInfo): self._interface_impl.handleCreate(self.callerArgs, confInfo) def handleRemove(self, confInfo): self._interface_impl.handleRemove(self.callerArgs, confInfo) admin.init(EMAlertInterface, admin.CONTEXT_APP_ONLY)
from splunk import admin import sc_rest class OpcServerConfRes(object): endpoint = '/admin/conf-opcservers' optional_args = [] required_args = [ 'dcomhost', 'domain', 'user', 'password', 'progid', 'clsid' ] transient_args = [] if __name__ == "__main__": admin.init(sc_rest.ResourceHandler(OpcServerConfRes), admin.CONTEXT_NONE)
# self.callerArgs.data['field_3'][0] = '60' # if int(self.callerArgs.data['field_2_boolean'][0]) == 1: # self.callerArgs.data['field_2_boolean'][0] = '0' # else: # self.callerArgs.data['field_2_boolean'][0] = '1' self.normalizeStringFields(['user','password'], self.callerArgs.data) self.callerArgs.data['password'][0] = base64.encodestring( self.callerArgs.data['password'][0] ) ''' Since we are using a conf file to store parameters, write them to the [setupentity] stanza in <appname>/local/myappsetup.conf ''' self.writeConf('keynote', 'keynote', self.callerArgs.data) def normalizeStringFields(self, fieldNames, data): for f in fieldNames: v = data[f][0] if v is None: v = '' data[f][0] = v.strip() # initialize the handler admin.init(KeynoteConfigApp, admin.CONTEXT_APP_ONLY) #admin.CONTEXT_NONE)
# let's make sure this thing exists, first... existing = admin.ConfigInfo() self.handleList(existing) if not self.callerArgs.id in existing: raise admin.ArgValidationException( "Cannot remove '%s', it does not exist." % self.callerArgs.id) # now that we're sure, set it to disabled and write it out. settsDict = self.readConf("imap")[self.callerArgs.id] settsDict["disabled"] = "true" self.updateConf("imap", self.callerArgs.id, settsDict) # ----------------------------------- # edits a config item from imap.conf # ----------------------------------- def handleEdit(self, confInfo): # let's make sure this thing exists, first... existing = admin.ConfigInfo() self.handleList(existing) if not self.callerArgs.id in existing: raise admin.ArgValidationException( "Cannot edit '%s', it does not exist." % self.callerArgs.id) self.updateConf("imap", self.callerArgs.id, self.callerArgs.data) admin.init( IMAPHandler, admin.ACTION_CREATE | admin.ACTION_EDIT | admin.ACTION_LIST | admin.ACTION_REMOVE)
def handleCreate(self, confInfo): name = self.callerArgs.id new = en.Entity(ENDPOINT, name, namespace=self.appName, owner=self.userName) for arg in required_args: new[arg] = self.callerArgs[arg] for arg in optional_args: if arg in ['disabled']: continue try: new[arg] = self.callerArgs[arg] except: pass en.setEntity(new, sessionKey=self.getSessionKey()) def handleRemove(self, confInfo): name = self.callerArgs.id en.deleteEntity(ENDPOINT, name, namespace=self.appName, owner=self.userName, sessionKey = self.getSessionKey()) admin.init(HadoopOpsComponentsHandler, admin.CONTEXT_APP_ONLY)
_errorIf('Mac verify error: invalid password?', output, 'Invalid PKCS12 password?') # Write output to splunkd.log just in case sys.stderr.write(output.replace('\n', '\\n')) def handleEdit(self, confInfo): """Respond to save event""" for field in eNcoreConfig.FIELDS: key = field['name'] if self.callerArgs.data[key][0] in [None, '']: self.callerArgs.data[key][0] = field['default'] self.callerArgs.data['changed'][0] = '1' # Do the real configuration here self._configure() # Don't save the password self.callerArgs.data['pkcs12_password'] = '' # And always reset pkcs12 processing self.callerArgs.data['process_pkcs12'] = '0' # Write to splunk config self.writeConf(eNcoreConfig.CONFIG_FILE, 'main', self.callerArgs.data) # initialize the handler admin.init(eNcoreConfig, admin.CONTEXT_NONE)
if self.callerArgs.data['index'][0] in [None, '']: self.callerArgs.data['index'][0] = '' if self.callerArgs.data['default_owner'][0] in [None, '']: self.callerArgs.data['default_owner'][0] = '' if self.callerArgs.data['default_impact'][0] in [None, '']: self.callerArgs.data['default_impact'][0] = '' if self.callerArgs.data['default_urgency'][0] in [None, '']: self.callerArgs.data['default_urgency'][0] = '' if self.callerArgs.data['default_priority'][0] in [None, '']: self.callerArgs.data['default_priority'][0] = '' if self.callerArgs.data['user_directories'][0] in [None, '']: self.callerArgs.data['user_directories'][0] = '' if self.callerArgs.data['default_notify_user_template'][0] in [None, '']: self.callerArgs.data['default_notify_user_template'][0] = '' #if int(self.callerArgs.data['save_results'][0]) == 1: # self.callerArgs.data['save_results'][0] = '1' #else: # self.callerArgs.data['save_results'][0] = '0' self.writeConf('alert_manager', 'settings', self.callerArgs.data) # initialize the handler admin.init(AlertHandlerApp, admin.CONTEXT_APP_AND_USER)
# Fix Nulls for key in self.callerArgs.data.keys(): if self.callerArgs.data[key][0] is None: self.callerArgs.data[key][0] = '' # Strip trailing and leading whitespace self.callerArgs.data[key][0] = self.callerArgs.data[key][ 0].strip() logger.info("function=handleEdit status=complete") del self.callerArgs.data["password"] self.writeConf('protectwise', 'config', self.callerArgs.data) except admin.HandlerSetupException, e: exc_type, exc_obj, exc_tb = sys.exc_info() fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1] logger.error( "type={} action=arg_validation_fatal_error line={} file={} message={}" .format(type(e), exc_tb.tb_lineno, fname, e)) raise e except Exception, e: exc_type, exc_obj, exc_tb = sys.exc_info() fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1] logger.error( "action=handleEdit_fatal_error type={} line={} file={} message={}" .format(type(e), exc_tb.tb_lineno, fname, e)) raise e # initialize the handler admin.init(ConfigApp, admin.CONTEXT_NONE)
def main(): admin.init(WorkOrgchartHandler, admin.CONTEXT_NONE)
roles = [] # Get the imported roles importedRoles = Transitioners.getImportedRoles(role, rolesDict) # For each imported role, get the roles imported by each role for importedRole in importedRoles: # If the role is not already in the list (i.e. has not yet been seen, then process it) if importedRole not in roles: # Append the given role (provided it isn't the role we are looking for) if importedRole != role: roles.append(importedRole) # Get the imported roles list traversedRoles = Transitioners.traverseRoles( 'role_' + importedRole, rolesDict, roles) # Add the unique set of roles for r in traversedRoles: if r not in roles: roles.append(r) # Return the roles return roles # initialize the handler admin.init(Transitioners, admin.CONTEXT_APP_AND_USER)
# Create a package of an application if self.customAction == 'package': appName = self.callerArgs.id try: url, path = appbuilder.packageApp(appName) confInfo['Package'].append('name', appName) confInfo['Package'].append('url', url) confInfo['Package'].append('path', path) except splunk.RESTException, e: raise admin.ArgValidationException(e.msg) ''' This handler is overridden by UIAppsHandler ''' def handleList(self, confInfo): pass def _getFieldValue(args, fieldName, defaultVal=None, maxLen=None): value = args[fieldName][0] or defaultVal if fieldName in args else defaultVal if value and maxLen and len(value) > maxLen: raise admin.ArgValidationException(i18n.ungettext('App %(fieldName)s cannot be longer than %(maxLen)s character.', 'App %(fieldName)s cannot be longer than %(maxLen)s characters.', maxLen) % {'fieldName' : fieldName, 'maxLen' : maxLen} ) return value # initialize the handler, and add the actions it supports. admin.init(LocalAppsHandler, admin.CONTEXT_NONE)
encryptedArgs = {'arn'} validators = { 'arn': validator.Pattern('^arn:[^\s:]+:iam::\d+:role(:|/)[^/:\s]+$') } class IAMHandler(base.BaseRestHandler): def handleEdit(self, confInfo): super(IAMHandler, self).handleEdit(confInfo) self._append_to_summary() def handleCreate(self, confInfo): super(IAMHandler, self).handleCreate(confInfo) self._append_to_summary() def _append_to_summary(self): role_name = self.callerArgs.id role_arn = self.callerArgs.data['arn'][0] account_util.append_assume_role_to_summary( name=role_name, arn=role_arn, session_key=self.getSessionKey()) # override handler name, as the cred_mgmt.py uses handler name as a part of the password realm (which is a bad as well as legacy design) def _getHandlerName(self): return 'BaseRestHandler' if __name__ == "__main__": admin.init( base.ResourceHandler(IAMRole, handler=IAMHandler), admin.CONTEXT_APP_AND_USER, )
indexes += "thawedPath = {0}/{1}/thaweddb\n".format(splunkdbdirpath, index) indexes += "disabled = false\n" indexes += "\n" # Creates inputs.conf under APP_DIR/local dir. If the file already exists, it is saved before being overwritten. if not os.path.exists(os.path.join(applocaldirpath, 'inputs.conf')): with file(os.path.join(applocaldirpath, 'inputs.conf'),'w') as inputsDest: inputsDest.write(inputs) else: with file(os.path.join(applocaldirpath, 'inputs.conf'+datetime.datetime.now().strftime("%Y%m%dT%H%M%S")),'w') as inputsPrevConfig: with file(os.path.join(applocaldirpath, 'inputs.conf'),'r') as inputsTemplate: config = inputsTemplate.read() inputsPrevConfig.write(config) with file(os.path.join(applocaldirpath, 'inputs.conf'),'w') as inputsTemplate: inputsTemplate.write(inputs) # Creates indexes.conf under APP_DIR/local dir if len(listNewindexes) != 0: with file(os.path.join(applocaldirpath, 'indexes.conf'),'a') as indexesDest: indexesDest.write(indexes) en.getEntities('data/indexes/_reload', sessionKey = self.getSessionKey()) en.getEntities('data/inputs/monitor/_reload', sessionKey = self.getSessionKey()) en.getEntities('data/inputs/script/_reload', sessionKey = self.getSessionKey()) # initialize the handler admin.init(ConfigHpfeeds, admin.CONTEXT_NONE)
def user_app(self): app = self.context != admin.CONTEXT_NONE and self.appName or "-" user = self.context == admin.CONTEXT_APP_AND_USER and \ self.userName or "nobody" return user, app def handleList(self, confInfo): user, app = self.user_app() try: url = '{uri}/servicesNS/{user}/{app}/data/indexes' \ '?output_mode=json&search=isInternal=0+disabled=0&count=-1' \ ''.format(uri=rest.makeSplunkdUri(), user=user, app=app) response, content = \ rest.simpleRequest(url, sessionKey=self.getSessionKey(), method='GET', raiseAllErrors=True) res = json.loads(content) if 'entry' in res: ent = {'indexes': [entry['name'] for entry in res['entry']]} util.make_conf_item(confInfo['splunk_ta_ui_indexes'], ent) except Exception as exc: error_ctl.RestHandlerError.ctl(-1, msgx=exc, logLevel=logging.INFO) return if __name__ == '__main__': admin.init(IndexHandler, admin.CONTEXT_APP_AND_USER)
''' Copyright (C) 2005 - 2010 Splunk Inc. All Rights Reserved. ''' import splunk.admin as admin import splunk.entity as entity class EventGenApp(admin.MConfigHandler): ''' Set up supported arguments ''' def setup(self): #if self.requestedAction == admin.ACTION_EDIT: # for arg in ['field_1', 'field_2_boolean', 'field_3']: # self.supportedArgs.addOptArg(arg) pass def handleList(self, confInfo): confDict = self.readConfCtx('eventgen') if confDict != None: for stanza, settings in confDict.items(): for key, value in settings.items(): if key != 'eai:acl': confInfo[stanza].append(key, str(value)) else: confInfo[stanza].setMetadata(key, value) # initialize the handler admin.init(EventGenApp, admin.CONTEXT_APP_AND_USER)
import aws_bootstrap_env import splunk.admin as admin from splunktalib.rest_manager import multimodel import aws_settings_base_rh class BillingCurLogging(aws_settings_base_rh.AWSLogging): keyMap = {"level": "log_level"} class BillingCurSettings(multimodel.MultiModel): endpoint = "configs/conf-aws_settings" modelMap = { "logging": BillingCurLogging, } class BillingCurSettingsHandler(aws_settings_base_rh.AWSSettingHandler): stanzaName = 'aws_billing_cur' if __name__ == "__main__": admin.init( multimodel.ResourceHandler(BillingCurSettings, BillingCurSettingsHandler), admin.CONTEXT_APP_AND_USER)
en.setEntity(ent, sessionKey=self.getSessionKey()) def handleCreate(self, confInfo): name = self.callerArgs.id new = en.Entity(ENDPOINT, name, namespace=self.appName, owner=self.userName) for arg in required_args: new[arg] = self.callerArgs[arg] for arg in optional_args: if arg in ["disabled"]: continue try: new[arg] = self.callerArgs[arg] except: pass en.setEntity(new, sessionKey=self.getSessionKey()) def handleRemove(self, confInfo): name = self.callerArgs.id en.deleteEntity(ENDPOINT, name, namespace=self.appName, owner=self.userName, sessionKey=self.getSessionKey()) admin.init(HadoopOpsHeadlinesHandler, admin.CONTEXT_APP_ONLY)
import aws_bootstrap_env import splunk.admin as admin from splunktalib.rest_manager import multimodel import aws_settings_base_rh class AWSLogsSettings(aws_settings_base_rh.AWSLogging): keyMap = {'level': 'log_level'} class S3IncrementalSettings(multimodel.MultiModel): endpoint = 'configs/conf-aws_settings' modelMap = { 'splunk_ta_aws_logs': AWSLogsSettings, } if __name__ == '__main__': admin.init( multimodel.ResourceHandler(S3IncrementalSettings), admin.CONTEXT_APP_AND_USER, )
def main(): admin.init(GoogleProjects, admin.CONTEXT_NONE)
password = mgr.get_clear_password(account[url_k], self.dummy, self.appName) if password: user_pass = password.split(self.userpass_sep) account[user_k], account[passwd_k] = user_pass def _verify_creds(self): _LOGGER.info("Verify credentials") confDict = self.readConf("service_now") assert confDict self._decrypt_username_password(confDict) config = {} for _, stanza_settings in confDict.iteritems(): config.update(stanza_settings) try: # When reset account, verify credentials. sc.SnowConfig.verify_user_pass(config) except Exception: err_msg = ("Failed to validate ServiceNow account. " "Please verify credentials, urls for " "ServiceNow and proxy, and try again. Reason=%s") _LOGGER.error(err_msg, traceback.format_exc()) raise admin.ArgValidationException(err_msg) admin.init(SetupRestHandler, admin.CONTEXT_APP_ONLY)
for to_remove in cls.UNSAVED_PARAMS: if to_remove in cleaned_params: del cleaned_params[to_remove] # Return the cleaned parameters return cleaned_params @staticmethod def stringToIntegerOrDefault( str_value, default_value=None ): """ Converts the given string to an integer or returns none if it is not a valid integer. Arguments: str_value -- A string value of the integer to be converted. default_value -- The value to be used if the string is not an integer. """ # If the value is none, then don't try to convert it if str_value is None: return default_value # Try to convert the string to an integer try: return int(str(str_value).strip()) except ValueError: # Return none if the value could not be converted return default_value # initialize the handler admin.init(WebsiteInputRestHandler, admin.CONTEXT_NONE)
if self.requestedAction == admin.ACTION_EDIT: for arg in self.spark_args: self.supportedArgs.addOptArg(arg) def handleList(self, confInfo): confDict = self.readConf(c.spark) if confDict is not None: for stanza, settings in confDict.items(): for key, val in settings.items(): if key in self.spark_args and val is None: val = "" confInfo[stanza].append(key, val) def handleEdit(self, confInfo): args = self.callerArgs.data for arg in self.spark_args: if args.get(arg, None) and args[arg][0] is None: args[arg][0] = "" spark_settings = {} for k in self.spark_args: if args.get(k): spark_settings[k] = args[k][0] if spark_settings: self.writeConf(c.spark, c.spark_settings, spark_settings) admin.init(ConfigApp, admin.CONTEXT_APP_ONLY)
sender = self.gfa('from') if sender.find("@") == -1: sender = sender + '@' + socket.gethostname() if sender.endswith("@"): sender = sender + 'localhost' message['From'] = sender message.attach(MIMEText(body, bodyformat, _charset=charset)) # send the mail if not use_ssl: smtp = smtplib.SMTP(mailserver) else: smtp = smtplib.SMTP_SSL(mailserver) if use_tls: smtp.starttls() if len(username) > 0: smtp.login(username, password) smtp.sendmail(sender, recipients, message.as_string()) smtp.quit() # initialize the handler admin.init(SendemailRestHandler, admin.CONTEXT_APP_AND_USER)
def handleEdit(self, _): # pylint: disable=invalid-name """ super() method - handles populating KVStore with default values """ session_key = self.getSessionKey() splunk_home = os.environ.get("SPLUNK_HOME") default_file = os.path.join(splunk_home, "etc", "apps", "broken_hosts", "default", "data", "expectedTime.csv.default") with open(default_file, "r", encoding='utf-8') as opened_file: reader = csv.DictReader(opened_file) for line in reader: self.write_line(session_key, line) @staticmethod def write_line(session_key, line): """ Writes line to KVStore, called in handleEdit() """ splunk.rest.simpleRequest( '/servicesNS/nobody/broken_hosts/storage/collections/data/expectedTime', method='POST', jsonargs=json.dumps(line), sessionKey=session_key) # initialize the handler admin.init(BrokenHostsSetup, admin.CONTEXT_NONE)
new_item = self.kao.insert_single_item(item) new_item = json.loads(new_item) confInfo[new_item['_key']].append('id', item) logger.info('create feedback for %s' % (item[ARG_RESOURCE_ID])) return new_item def _merge_details(self, recomm_id): item = {} try: item = json.loads(self.recomm_kao.get_item_by_key(recomm_id)) except: logger.info('failed to find recomm_item %s' % recomm_id) return False feedback_item = {} for key in [ARG_RESOURCE_ID, ARG_DIMENSION, ARG_FEATURE, ARG_PRIORITY, ARG_ACTION]: feedback_item[key] = item[key] feedback_item[ARG_RECOMM_ID] = recomm_id feedback_item['splunk_account'] = self.userName feedback_item[ARG_FEEDBACK] = self.callerArgs[ARG_FEEDBACK][0] feedback_item[ARG_TIMESTAMP] = int(self.callerArgs[ARG_TIMESTAMP][0]) / 1000 return feedback_item admin.init(RecommActionHandler, admin.CONTEXT_APP_ONLY)
def main(): admin.init( base.ResourceHandler(MonitoringInputs), admin.CONTEXT_APP_AND_USER, )
cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT ) p.wait() lines = p.stdout.readlines() output = [] [output.append(str(line, "utf-8")) for line in lines] confInfo["success_message"] = ("output", output) def is_file(self, confInfo): file_path = self.callerArgs.data["file_path"][0] if os.path.exists(file_path): if os.path.isfile(file_path): confInfo["success_message"] = ( "positive_response", "{} is a regular file.".format(file_path), ) else: confInfo["success_message"] = ( "negative_response", "{} is not a regular file.".format(file_path), ) else: confInfo["error_message"] = ( "negative_response", "Path {} does not exist.".format(file_path), ) if __name__ == "__main__": admin.init(Splunk_TA_Modinput_Test, admin.CONTEXT_APP_AND_USER)
int(val) except ValueError: raise InvalidParameterValueException(key, val, "must be a valid integer") # Is comment required elif stanza == 'comment' and key == LogReview.PARAM_COMMENT_REQUIRED: try: util.normalizeBoolean(val, enableStrictMode=True) except ValueError: raise InvalidParameterValueException(key, val, "must be a valid boolean") # Is urgency override allowed elif (stanza == 'notable_editing' or stanza is None) and key == LogReview.PARAM_ALLOW_URGENCY_OVERRIDE: try: util.normalizeBoolean(val, enableStrictMode=True) except ValueError: raise InvalidParameterValueException(key, val, "must be a valid boolean") # Check to make sure the related config options that relate to the given parameters are acceptable if stanza != "default" and onlyCheckProvidedFields == False: # Add checks for field values that depend on the value of other field values here # Warn if some of the required fields were not provided if len(required_fields) > 0: raise InvalidConfigException("The following fields must be defined in the configuration but were not: " + ",".join(required_fields) ) # initialize the handler admin.init(LogReview, admin.CONTEXT_APP_AND_USER)
self.added_thread_limit_validator = True # Call the super class convertParams() return super(WebsiteMonitoringRestHandler, self).convertParams(name, cleaned_params, to_string) @log_function_invocation def handleList(self, confInfo): """ Provide the list of configuration options. Arguments confInfo -- The object containing the information about what is being requested. """ # Read the current settings from the conf file confDict = self.readConf(self.conf_file) # Set the settings if confDict != None: for stanza, settings in confDict.items(): for key, val in settings.items(): if key == self.PARAM_THREAD_LIMIT and int(val) > 25 and ServerInfo.is_on_cloud(session_key=self.getSessionKey()): confInfo[stanza].append(key, 25) else: confInfo[stanza].append(key, val) # initialize the handler if __name__ == "__main__": admin.init(WebsiteMonitoringRestHandler, admin.CONTEXT_NONE)
def main(): admin.init(KafkaRestHandler, admin.CONTEXT_NONE)
'proxy_enabled': normaliser.Boolean(), } outputExtraFields = ('eai:acl', 'acl', 'eai:attributes', 'eai:appName', 'eai:userName') class TenableScSettings(base.BaseModel): defaultVals = { 'disable_ssl_certificate_validation': '0', } outputExtraFields = ('eai:acl', 'acl', 'eai:attributes', 'eai:appName', 'eai:userName', 'disable_ssl_certificate_validation') class Setting(multimodel.MultiModel): endpoint = "configs/conf-nessus" modelMap = { 'nessus_loglevel': Logging, 'nessus_proxy': Proxy, 'tenable_sc_settings': TenableScSettings } cap4endpoint = '' cap4get_cred = '' if __name__ == "__main__": admin.init( multimodel.ResourceHandler(Setting, handler=NessusSettingsHandler), admin.CONTEXT_APP_AND_USER, )
# --------------------------------------- def handleRemove(self, confInfo): # let's make sure this thing exists, first... existing = admin.ConfigInfo() self.handleList(existing) if not self.callerArgs.id in existing: raise admin.ArgValidationException, "Cannot remove '%s', it does not exist." % self.callerArgs.id # now that we're sure, set it to disabled and write it out. settsDict = self.readConf("imap")[self.callerArgs.id] settsDict["disabled"] = "true" self.updateConf("imap", self.callerArgs.id, settsDict) # ----------------------------------- # edits a config item from imap.conf # ----------------------------------- def handleEdit(self, confInfo): # let's make sure this thing exists, first... existing = admin.ConfigInfo() self.handleList(existing) if not self.callerArgs.id in existing: raise admin.ArgValidationException, "Cannot edit '%s', it does not exist." % self.callerArgs.id self.updateConf("imap", self.callerArgs.id, self.callerArgs.data) admin.init(IMAPHandler, admin.ACTION_CREATE | admin.ACTION_EDIT | admin.ACTION_LIST | admin.ACTION_REMOVE)
import aws_bootstrap_env import os import sys import re import splunk.admin as admin from splunktalib.rest_manager import multimodel import aws_settings_base_rh class CloudWatchLogsLogging(aws_settings_base_rh.AWSLogging): keyMap = { 'level': 'log_level' } class CloudWatchLogsSettings(multimodel.MultiModel): endpoint = "configs/conf-aws_cloudwatch_logs" modelMap = { 'logging': CloudWatchLogsLogging, } if __name__ == "__main__": admin.init(multimodel.ResourceHandler(CloudWatchLogsSettings), admin.CONTEXT_APP_AND_USER)
name = self.callerArgs.id args = self.callerArgs if self.callerArgs.data['index'][0] in [None, '']: self.callerArgs.data['index'][0] = '' if self.callerArgs.data['default_owner'][0] in [None, '']: self.callerArgs.data['default_owner'][0] = '' if self.callerArgs.data['default_priority'][0] in [None, '']: self.callerArgs.data['default_priority'][0] = '' if self.callerArgs.data['user_directories'][0] in [None, '']: self.callerArgs.data['user_directories'][0] = '' if self.callerArgs.data['default_notify_user_template'][0] in [ None, '' ]: self.callerArgs.data['default_notify_user_template'][0] = '' #if int(self.callerArgs.data['save_results'][0]) == 1: # self.callerArgs.data['save_results'][0] = '1' #else: # self.callerArgs.data['save_results'][0] = '0' self.writeConf('alert_manager', 'settings', self.callerArgs.data) # initialize the handler admin.init(AlertHandlerApp, admin.CONTEXT_APP_AND_USER)
for stanza in stanzas: logger.info("Remove %s", stanza) ta_conf_mgr.update({c.name: stanza, c.removed: "1"}) @staticmethod def _clearPasswords(settings, cred_fields): for k, val in settings.iteritems(): if isinstance(val, dict): return ConfigApp._clearPasswords(val, cred_fields) elif isinstance(val, (str, unicode)): if k in cred_fields: settings[k] = "" @staticmethod def _setNoneValues(stanza): for k, v in stanza.iteritems(): if v is None: stanza[k] = "" @staticmethod def _configChanges(new_config, origin_config): for k, v in new_config.iteritems(): if k in ConfigApp.cred_fields and v == "": continue if v != origin_config.get(k): return True return False admin.init(ConfigApp, admin.CONTEXT_APP_ONLY)
content = helper.get_cluster_info(uri + 'servicesNS/nobody/splunk-checker/storage/collections/data/clusterinfo') # TODO: transform to confInfo for cluster_info in content: confInfo[cluster_info['cluster_id']]['cluster_info'] = json.dumps(cluster_info) def handleCreate(self, confInfo): post_data = self.callerArgs.data cluster_id = post_data['cluster_id'][0] splunk_info = dict() cluster_info = dict() for item in post_data.keys(): if item != 'cluster_id': confInfo[cluster_id][item] = post_data[item][0] cluster_items = ['cluster_id', 'enable_cluster', 'enable_shcluster', 'replication_factor', 'search_factor'] for item in post_data.keys(): if item in cluster_items: cluster_info[item] = post_data[item][0] else: splunk_info[item] = post_data[item][0] cluster_info['peers'] = [] cluster_info['peers'].append(splunk_info) helper = KVStoreHelper(self.getSessionKey()) uri = rest.makeSplunkdUri() helper.update_cluster_info(uri + 'servicesNS/nobody/splunk-checker/storage/collections/data/clusterinfo', cluster_info) if __name__ == "__main__": admin.init(StoreCluster, admin.CONTEXT_APP_AND_USER)
import splunk_config_handler as ch import splunk.admin as admin ''' # Sets a ConfigHandler that supports all settings in # app_utils.APP_CONFIG_FILE ''' admin.init(ch.buildConfigHandler(), admin.CONTEXT_NONE)