reslove multiple records at once
[sfa.git] / sfa / server / sfa-clean-peer-records.py
1 #!/usr/bin/python
2
3 import sys
4 import os
5 import traceback
6 from sfa.util.namespace import *
7 from sfa.util.table import SfaTable
8 from sfa.util.prefixTree import prefixTree
9 from sfa.plc.api import SfaAPI
10 from sfa.util.config import Config
11 from sfa.trust.certificate import Keypair
12 from sfa.trust.hierarchy import Hierarchy
13 from sfa.util.report import trace, error
14 from sfa.server.registry import Registries
15 from sfa.util.xmlrpcprotocol import *
16 import socket
17
18 def main():
19     config = Config()
20     if not config.SFA_REGISTRY_ENABLED:
21         sys.exit(0)
22
23     # Get the path to the sfa server key/cert files from 
24     # the sfa hierarchy object
25     sfa_hierarchy = Hierarchy()
26     sfa_key_path = sfa_hierarchy.basedir
27     key_file = os.path.join(sfa_key_path, "server.key")
28     cert_file = os.path.join(sfa_key_path, "server.cert")
29     key = Keypair(filename=key_file) 
30
31     # get a connection to our local sfa registry
32     # and a valid credential
33     authority = config.SFA_INTERFACE_HRN
34     url = 'http://%s:%s/' %(config.SFA_REGISTRY_HOST, config.SFA_REGISTRY_PORT)
35     registry = xmlrpcprotocol.get_server(url, key_file, cert_file)
36     sfa_api = SfaAPI(key_file = key_file, cert_file = cert_file, interface='registry')
37     credential = sfa_api.getCredential()
38
39     # get peer registries
40     registries = Registries(sfa_api)
41     tree = prefixTree()
42     tree.load(registries.keys())
43     
44     # get local peer records
45     table = SfaTable()
46     peer_records = table.find({'~peer_authority': None})
47     found_records = []
48     hrn_dict = {}
49     for record in peer_records:
50         registry_hrn = tree.best_match(record['hrn'])
51         if registry_hrn not in hrn_dict:
52             hrn_dict[registry_hrn] = []
53         hrn_dict[registry_hrn].append(record['hrn'])
54
55     # attempt to resolve the record at the authoritative interface 
56     for registry_hrn in hrn_dict:
57         if registry_hrn in registries:
58             records = []
59             target_hrns = hrn_dict[registry_hrn]    
60             try:
61                 records = registries[registry_hrn].resolve(credential, target_hrns)
62                 found_records.extend([record['hrn'] for record in records])
63             except:
64                 traceback.print_exc()
65
66     # remove what wasnt found 
67     for peer_record in peer_records:
68         if peer_record['hrn'] not in found_records:
69             registries[sfa_api.hrn].remove(credential, peer_record)
70                 
71 if __name__ == '__main__':
72     main()