Get a splunk search

    CLI Example:

        splunk_search.get 'my search name'
353343
def get(name, profile="splunk"):
    '''
    
    '''
    client = _get_splunk(profile)
    search = None
    # uglyness of splunk lib
    try:
        search = client.saved_searches[name]
    except KeyError:
        pass
    return search
1366110
def get_user(email, profile="splunk", **kwargs):
    '''
    
    '''

    user_map = list_users(profile)
    user_found = email.lower() in user_map.keys()

    if not kwargs.get('user_details', False) and user_found:
        # The user is in splunk group, just return
        return True
    elif kwargs.get('user_details', False) and user_found:
        user = user_map[email.lower()]

        response = {}
        for field in ['defaultApp', 'realname', 'name', 'email']:
            response[field] = user[field]

        response['roles'] = []
        for role in user.role_entities:
            response['roles'].append(role.name)

        return response

    return False
549454
def get(self, *args, **kwargs):
        
        self.session.username = 'gmr'

        session = self.session.as_dict()
        if session['last_request_at']:
            session['last_request_at'] = str(date.fromtimestamp(
                                             session['last_request_at']))

        # Send a JSON string for our test
        self.write({'message': 'Hello World',
                    'request': {'method': self.request.method,
                                'protocol': self.request.protocol,
                                'path': self.request.path,
                                'query': self.request.query,
                                'remote_ip': self.request.remote_ip,
                                'version': self.request.version},
                    'session': session,
                    'tinman': {'version':  __version__}})
        self.finish()
1145663
def query(action=None,
          command=None,
          args=None,
          method='GET',
          location=None,
          data=None):
    '''
    
    '''
    user = config.get_cloud_config_value(
        'user', get_configured_provider(), __opts__, search_global=False
    )

    if not user:
        log.error('username is required for Joyent API requests. Please set one in your provider configuration')

    password = config.get_cloud_config_value(
        'password', get_configured_provider(), __opts__,
        search_global=False
    )

    verify_ssl = config.get_cloud_config_value(
        'verify_ssl', get_configured_provider(), __opts__,
        search_global=False, default=True
    )

    ssh_keyfile = config.get_cloud_config_value(
        'private_key', get_configured_provider(), __opts__,
        search_global=False, default=True
    )

    if not ssh_keyfile:
        log.error('ssh_keyfile is required for Joyent API requests.  Please set one in your provider configuration')

    ssh_keyname = config.get_cloud_config_value(
        'keyname', get_configured_provider(), __opts__,
        search_global=False, default=True
    )

    if not ssh_keyname:
        log.error('ssh_keyname is required for Joyent API requests.  Please set one in your provider configuration')

    if not location:
        location = get_location()

    api_host_suffix = config.get_cloud_config_value(
        'api_host_suffix', get_configured_provider(), __opts__,
        search_global=False, default=JOYENT_API_HOST_SUFFIX
    )

    path = get_location_path(location=location, api_host_suffix=api_host_suffix)

    if action:
        path += action

    if command:
        path += '/{0}'.format(command)

    log.debug('User: \'%s\' on PATH: %s', user, path)

    if (not user) or (not ssh_keyfile) or (not ssh_keyname) or (not location):
        return None

    timenow = datetime.datetime.utcnow()
    timestamp = timenow.strftime('%a, %d %b %Y %H:%M:%S %Z').strip()
    rsa_key = salt.crypt.get_rsa_key(ssh_keyfile, None)
    if HAS_M2:
        md = EVP.MessageDigest('sha256')
        md.update(timestamp.encode(__salt_system_encoding__))
        digest = md.final()
        signed = rsa_key.sign(digest, algo='sha256')
    else:
        rsa_ = PKCS1_v1_5.new(rsa_key)
        hash_ = SHA256.new()
        hash_.update(timestamp.encode(__salt_system_encoding__))
        signed = rsa_.sign(hash_)
    signed = base64.b64encode(signed)
    user_arr = user.split('/')
    if len(user_arr) == 1:
        keyid = '/{0}/keys/{1}'.format(user_arr[0], ssh_keyname)
    elif len(user_arr) == 2:
        keyid = '/{0}/users/{1}/keys/{2}'.format(user_arr[0], user_arr[1], ssh_keyname)
    else:
        log.error('Malformed user string')

    headers = {
        'Content-Type': 'application/json',
        'Accept': 'application/json',
        'X-Api-Version': JOYENT_API_VERSION,
        'Date': timestamp,
        'Authorization': 'Signature keyId="{0}",algorithm="rsa-sha256" {1}'.format(
            keyid,
            signed.decode(__salt_system_encoding__)
        ),
    }

    if not isinstance(args, dict):
        args = {}

    # post form data
    if not data:
        data = salt.utils.json.dumps({})

    return_content = None
    result = salt.utils.http.query(
        path,
        method,
        params=args,
        header_dict=headers,
        data=data,
        decode=False,
        text=True,
        status=True,
        headers=True,
        verify_ssl=verify_ssl,
        opts=__opts__,
    )
    log.debug('Joyent Response Status Code: %s', result['status'])
    if 'headers' not in result:
        return [result['status'], result['error']]

    if 'Content-Length' in result['headers']:
        content = result['text']
        return_content = salt.utils.yaml.safe_load(content)

    return [result['status'], return_content]
93420
def get(self, key, namespace=None):
        """"""
        # Short-circuit to reduce overhead.
        if not _CONFIG_OVERRIDE:
            return NO_VALUE
        full_key = generate_uppercase_key(key, namespace)
        logger.debug('Searching %s for %s', self, full_key)
        return get_key_from_envs(reversed(_CONFIG_OVERRIDE), full_key)
1369660
def get_by_name(self, name, namespace=None):
        
        if not namespace:
            namespace, name = get_namespace_from_name(name)
        if not namespace:
            namespace = AuthConfigManager.get_access_token().username
        try:
            response = self.request('GET', '%s/%s/%s' % (self.url, namespace, name))
            return Dataset.from_dict(response.json())
        except NotFoundException:
            return None
262823
def _query_service(self, name):
        """"""
        if self.query_cmd:
            try:
                return sos_get_command_output("%s %s" % (self.query_cmd, name))
            except Exception:
                return None
        return None
1233018
def create(name, profile="splunk", **kwargs):
    '''
    
    '''
    client = _get_splunk(profile)
    search = client.saved_searches.create(name, **kwargs)

    # use the REST API to set owner and permissions
    # this is hard-coded for now; all managed searches are app scope and
    # readable by all
    config = __salt__['config.option'](profile)
    url = "https://{0}:{1}".format(config.get('host'), config.get('port'))
    auth = (config.get('username'), config.get('password'))
    data = {
        "owner": config.get("username"),
        "sharing": "app",
        "perms.read": "*",
    }
    _req_url = "{0}/servicesNS/{1}/search/saved/searches/{2}/acl".format(
        url, config.get("username"), urllib.quote(name)
    )
    requests.post(_req_url, auth=auth, verify=True, data=data)
    return _get_splunk_search_props(search)
361010
def _get_resource(resource, name=None, resource_id=None, region=None,
                  key=None, keyid=None, profile=None):
    '''
    
    '''

    if not _exactly_one((name, resource_id)):
        raise SaltInvocationError('One (but not both) of name or id must be '
                                  'provided.')

    conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)

    f = 'get_all_{0}'.format(resource)
    if not f.endswith('s'):
        f = f + 's'
    get_resources = getattr(conn, f)
    filter_parameters = {}

    if name:
        filter_parameters['filters'] = {'tag:Name': name}
    if resource_id:
        filter_parameters['{0}_ids'.format(resource)] = resource_id

    try:
        r = get_resources(**filter_parameters)
    except BotoServerError as e:
        if e.code.endswith('.NotFound'):
            return None
        raise

    if r:
        if len(r) == 1:
            if name:
                _cache_id(name, sub_resource=resource,
                          resource_id=r[0].id,
                          region=region,
                          key=key, keyid=keyid,
                          profile=profile)
            return r[0]
        else:
            raise CommandExecutionError('Found more than one '
                                        '{0} named "{1}"'.format(
                                            resource, name))
    else:
        return None
1123613
def endpoint_search(auth=None, **kwargs):
    '''
    
    '''
    cloud = get_operator_cloud(auth)
    kwargs = _clean_kwargs(**kwargs)
    return cloud.search_endpoints(**kwargs)
831305
def get(name):
    '''
    
    '''
    cmd = 'sysctl -n {0}'.format(name)
    out = __salt__['cmd.run'](cmd, python_shell=False)
    return out
908787
def search(self, name):
        
        pattern = re.compile(name)
        result = {}
        for i in self.__allstockno:
            query = re.search(pattern, self.__allstockno[i])
            if query:
                query.group()
                result[i] = self.__allstockno[i]
        return result
785497
def _get_splunk(profile):
    '''
    
    '''
    config = __salt__['config.option'](profile)

    key = "splunk.{0}:{1}:{2}:{3}".format(
        config.get('host'),
        config.get('port'),
        config.get('username'),
        config.get('password')
    )

    if key not in __context__:
        __context__[key] = splunklib.client.connect(
            host=config.get('host'),
            port=config.get('port'),
            username=config.get('username'),
            password=config.get('password'))

    return __context__[key]
923079
def _query(action=None,
           command=None,
           args=None,
           method='GET',
           header_dict=None,
           data=None):
    '''
    
    '''
    vm_ = get_configured_provider()
    apikey = config.get_cloud_config_value(
        'apikey', vm_, __opts__, search_global=False
    )
    sharedsecret = config.get_cloud_config_value(
        'sharedsecret', vm_, __opts__, search_global=False
    )

    path = 'https://api.gogrid.com/api/'

    if action:
        path += action

    if command:
        path += '/{0}'.format(command)

    log.debug('GoGrid URL: %s', path)

    if not isinstance(args, dict):
        args = {}

    epoch = six.text_type(int(time.time()))
    hashtext = ''.join((apikey, sharedsecret, epoch))
    args['sig'] = salt.utils.hashutils.md5_digest(hashtext)
    args['format'] = 'json'
    args['v'] = '1.0'
    args['api_key'] = apikey

    if header_dict is None:
        header_dict = {}

    if method != 'POST':
        header_dict['Accept'] = 'application/json'

    decode = True
    if method == 'DELETE':
        decode = False

    return_content = None
    result = salt.utils.http.query(
        path,
        method,
        params=args,
        data=data,
        header_dict=header_dict,
        decode=decode,
        decode_type='json',
        text=True,
        status=True,
        opts=__opts__,
    )
    log.debug('GoGrid Response Status Code: %s', result['status'])

    return result['dict']
748069
def _find_service_name(self):
        
        space = predix.admin.cf.spaces.Space()
        services = space.get_services()
        for service in services:
            if service.startswith('logstash'):
                return service

        return 'logstash-3'
435588
def splunk(cmd, user='admin', passwd='changeme'):
    """"""
    return sudo('/opt/splunkforwarder/bin/splunk {c} -auth {u}:{p}'
                .format(c=cmd, u=user, p=passwd))
198183
def get_id_by_name(api, search_name):
    
    entities = api.get_all(q='name==' + "'" + search_name + "'").content
    if entities:
        return entities[0].id
    return