2014-04-24 2 views
2

현재 mongodb 리턴기를 사용하는 saltstack 구현과 관련하여보고 목적으로 저장되어있는 결과를 쿼리하려고합니다. 불행히도 기 returner 데이터베이스에 정보를 기록하는 방식은 다음과 같습니다mongodb 키가 변수이고 파이썬을 사용하여 결과를 집계하는 쿼리 데이터

db.hostname21.find ({ "20140421035007,474,763는": {$가 존재 : 1}}, {_id : 0}) 꽤.()

{ 
    "fun" : "state.sls", 
    "20140421035007474763" : { 
      "file_|-Get-Logins-Stats_|-/scripts/server_logins_stats_|-managed" : { 
        "comment" : "File /scripts/server_logins_stats is in the correct state", 
        "__run_num__" : 2, 
        "changes" : { 

        }, 
        "name" : "/scripts/server_logins_stats", 
        "result" : true 
      }, 
      "service_|-Logger_|-rsyslog_|-running" : { 
        "comment" : "Service rsyslog is already enabled, and is in the desired state", 
        "__run_num__" : 1, 
        "changes" : { 

        }, 
        "name" : "rsyslog", 
        "result" : true 
      }, 
      "cmd_|-Run_Script_|-/scripts/server_logins_stats_|-run" : { 
        "comment" : "Command \"/scripts/server_logins_stats\" run", 
        "__run_num__" : 4, 
        "changes" : { 
          "pid" : 20899, 
          "retcode" : 0, 
          "stderr" : "", 
          "stdout" : "0" 
        }, 
        "name" : "/scripts/server_logins_stats", 
        "result" : true 
      }, 
      "cron_|-Schedule_Run_|-/scripts/server_logins_stats_|-present" : { 
        "comment" : "Cron /scripts/server_logins_stats already present", 
        "__run_num__" : 3, 
        "changes" : { 

        }, 
        "name" : "/scripts/server_logins_stats", 
        "result" : true 
      }, 
      "pkg_|-nc_|-nc_|-installed" : { 
        "comment" : "Package nc is already installed", 
        "__run_num__" : 0, 
        "changes" : { 

        }, 
        "name" : "nc", 
        "result" : true 
      } 
    } 
} 

당신은 키가 끊임없이 변화하는 대신 각 스크립트를 식별하는 키를 가지고 여기에 볼 수 있습니다. 그래서 궁극적으로 내가 할 수 있나요 원하는

 "20140421041507478163" : [ 
      "Pillar failed to render with the following messages:", 
      "Specified SLS 'globals' in environment 'Production' is not available on the salt master" 
     ], 
     "fun" : "state.sls" 

: 그러나, 나는 그들이 어떤 키가 실패 문자열의 단지 배열임을 식별이없는 것을 제외하고 실패가 꽤 지속적으로 포맷 된 것을 발견했다 작업, 호스트 및 실패의 본질뿐만 아니라 전체 성공 및 실패 횟수를 식별하여 각 실패를보고 할 수 있어야합니다. 각 호스트 (미니언)가 자신 만의 컬렉션을 만들었다는 것을 알게되면. 그래서 내가 작업이 실제로 해당 호스트에서 실행 된 경우 확인하기 위해 컬렉션을 반복하는 파이썬 스크립트있어 :

import datetime 
import pymongo 


#hosts = ["mongoDBStaging", "mongoDBUAT"] 
hosts = ["mongodbuat"] 

for host in hosts: 
    conn = pymongo.Connection(host) 
    mdb = conn['salt'] 
    collections = set(mdb.collection_names()) 


    hosts = [] 
    jids = [] 

    # for every collection, identify whether it is a host or a job 
    for c in collections: 
     # if the collection is a host add it to the host array 
     if not (len(c) == 20 and int(c)): 
      #print "{0} is a host".format(c) 
      hosts.append(c) 
     # other wise add it to the job array 
     else: 
      #print "{0} is a jid".format(c) 
      jids.append(c) 


    for h in hosts: 
     # for every job in a host connect to that collection 
     # and search for the job id to see if it exists 
     # and what its return was so we can report on that info 
     for j in jids: 
      coll = conn['salt'][h] 
      #print "%s collection, %s jid" % (coll, j) 
      for doc in coll.find({j: {'$exists': True}, "fun": "state.sls"}, {"_id": 0}): 
       print "{0}".format(coll) 
       print "{0} is a doc".format(doc) 

을하지만 난 사실 여부를 확인하는 결과로 조회 할 수 있도록 사투를 벌인거야 성공했는지 아닌지. 각 문서의 결과를 읽기 위해 반환되는 문서의 요소를 추출 할 수 있습니다.

누군가가 지속적으로 키가 결과에 도달하는 데 도움이되는 결과로 일관되게 쿼리 할 수있는 방법에 대한 제안 사항이있는 경우.

+0

"스키마"가 잔인합니다. 그것을 바꿀 수 있습니까? – reptilicus

+0

@reptilicus 나는 그것을 원한다. 그러나 그것은 나의 통제하에 있지 않은 소금 스택을 위해 전체 반환자를 다시 쓰는 것을 포함 할 것이다. 그래서 지금은 그 옵션이 테이블에 없다고 말하자. – rhealitycheck

+0

그 사람은 빤다. 모든 문서에 "재미"키가 있고 타임 스탬프 키가 있습니까? – reptilicus

답변

1

궁금한 점이 있으시면. 나는 다음 파이썬 코드를 사용하여 내 자신의 문제를 해결했다. 퍼포먼스 나 mongodb를 최대한 활용하는 것이 가장 좋지만 작동하지 않습니다. 나는 아마도 쉘 내에서 쿼리가 꽤 제한적이라면 mongodb를 사용하기 위해 소금 반환기를 업데이트하는 것이 좋습니다.

import datetime 
import pymongo 
import json 
import re 

hosts = ["mongodbuat"] 

# initialize failures and successes 
failures = 0 
successes = 0 

for host in hosts: 
    conn = pymongo.Connection(host) 
    mdb = conn['salt'] 
    collections = set(mdb.collection_names()) 

    hosts = [] 
    jids = [] 

    # for every collection, identify whether it is a host or a job 
    for c in collections: 
     # if the collection is a host add it to the host array 
     if not (len(c) == 20 and int(c)): 
      hosts.append(c) 
     # otherwise add it to the job array 
     else: 
      jids.append(c) 


    for h in hosts: 
     # for every job in a host connect to that collection 
     # and search for the job id to see if it exists 
     # and what its return was so we can report on that info 
     for j in jids: 
      coll = conn['salt'][h] 

      # search for the json documents returned from mongodb 
      # if the jobid exists in that host 
      for doc in coll.find({j: {'$exists': True}, "fun": "state.sls"}, {"_id": 0}): 

       # if the jobid exists find the host name in a readable format 
       c = str(coll) 
       thishost = '' 
       match = re.search('(\w+)\.spottrading\.com',c) 
       if match: 
        thishost = match.group(1) 

       # search the document returned in the form of a dictionary for 
       # the states you want to report on 
       for jobid, states in doc.iteritems(): 
        if re.search('\d+', jobid): 
         print '\njob id =', jobid 
         if isinstance(states, list): 
          print states 
          failures += 1 
         elif isinstance(states, dict): 
          for job, data in states.iteritems(): 
           print '\tjob: {0}, result: {1}'.format(job, data[u'result']) 
          successes += 1 

print "{0} successes, {1} failures".format(successes, failures)       
관련 문제