Setting tag sfa-2.0-10
[sfa.git] / sfa / importer / sfa-import-openstack.py
1 #!/usr/bin/python
2 #
3 ##
4 # Import PLC records into the SFA database. It is indended that this tool be
5 # run once to create SFA records that reflect the current state of the
6 # planetlab database.
7 #
8 # The import tool assumes that the existing PLC hierarchy should all be part
9 # of "planetlab.us" (see the root_auth and level1_auth variables below).
10 #
11 # Public keys are extracted from the users' SSH keys automatically and used to
12 # create GIDs. This is relatively experimental as a custom tool had to be
13 # written to perform conversion from SSH to OpenSSL format. It only supports
14 # RSA keys at this time, not DSA keys.
15 ##
16
17 import os
18 import getopt
19 import sys
20
21 from sfa.util.config import Config
22 from sfa.util.xrn import Xrn, get_leaf, get_authority, hrn_to_urn
23 from sfa.util.plxrn import hostname_to_hrn, slicename_to_hrn, email_to_hrn, hrn_to_pl_slicename
24 from sfa.storage.table import SfaTable
25 from sfa.storage.record import SfaRecord
26 from sfa.trust.certificate import convert_public_key, Keypair
27 from sfa.trust.gid import create_uuid
28 from sfa.importer.sfaImport import sfaImport, _cleanup_string
29 from sfa.util.sfalogging import logger
30 from sfa.openstack.openstack_shell import OpenstackShell    
31
32 def process_options():
33
34    (options, args) = getopt.getopt(sys.argv[1:], '', [])
35    for opt in options:
36        name = opt[0]
37        val = opt[1]
38
39
40 def load_keys(filename):
41     keys = {}
42     tmp_dict = {}
43     try:
44         execfile(filename, tmp_dict)
45         if 'keys' in tmp_dict:
46             keys = tmp_dict['keys']
47         return keys
48     except:
49         return keys
50
51 def save_keys(filename, keys):
52     f = open(filename, 'w')
53     f.write("keys = %s" % str(keys))
54     f.close()
55
56 def main():
57
58     process_options()
59     config = Config()
60     sfaImporter = sfaImport()
61     logger=sfaImporter.logger
62     logger.setLevelFromOptVerbose(config.SFA_API_LOGLEVEL)
63     if not config.SFA_REGISTRY_ENABLED:
64         sys.exit(0)
65     root_auth = config.SFA_REGISTRY_ROOT_AUTH
66     interface_hrn = config.SFA_INTERFACE_HRN
67     shell = OpenstackShell(config)
68     sfaImporter.create_top_level_records()
69     
70     # create dict of all existing sfa records
71     existing_records = {}
72     existing_hrns = []
73     key_ids = []
74     table = SfaTable()
75     results = table.find()
76     for result in results:
77         existing_records[(result['hrn'], result['type'])] = result
78         existing_hrns.append(result['hrn']) 
79             
80         
81     # Get all users
82     persons = shell.user_get_all()
83     persons_dict = {}
84     keys_filename = config.config_path + os.sep + 'person_keys.py' 
85     old_person_keys = load_keys(keys_filename)    
86     person_keys = {} 
87     for person in persons:
88         hrn = config.SFA_INTERFACE_HRN + "." + person.id
89         persons_dict[hrn] = person
90         old_keys = old_person_keys.get(person.id, [])
91         keys = [k.public_key for k in shell.key_pair_get_all_by_user(person.id)]
92         person_keys[person.id] = keys
93         update_record = False
94         if old_keys != keys:
95             update_record = True
96         if hrn not in existing_hrns or \
97                (hrn, 'user') not in existing_records or update_record:    
98             urn = hrn_to_urn(hrn, 'user')
99             
100             if keys:
101                 try:
102                     pkey = convert_public_key(keys[0])
103                 except:
104                     logger.log_exc('unable to convert public key for %s' % hrn)
105                     pkey = Keypair(create=True)
106             else:
107                 logger.warn("Import: person %s does not have a PL public key"%hrn)
108                 pkey = Keypair(create=True) 
109             person_gid = sfaImporter.AuthHierarchy.create_gid(urn, create_uuid(), pkey)
110             person_record = SfaRecord(hrn=hrn, gid=person_gid, type="user", \
111                                           authority=get_authority(hrn))
112             logger.info("Import: importing %s " % person_record.summary_string())
113             person_record.sync()
114
115     # Get all projects
116     projects = shell.project_get_all()
117     projects_dict = {}
118     for project in projects:
119         hrn = config.SFA_INTERFACE_HRN + '.' + project.id
120         projects_dict[hrn] = project
121         if hrn not in existing_hrns or \
122         (hrn, 'slice') not in existing_records:
123             pkey = Keypair(create=True)
124             urn = hrn_to_urn(hrn, 'slice')
125             project_gid = sfaImporter.AuthHierarchy.create_gid(urn, create_uuid(), pkey)
126             project_record = SfaRecord(hrn=hrn, gid=project_gid, type="slice",
127                                        authority=get_authority(hrn))
128             projects_dict[project_record['hrn']] = project_record
129             logger.info("Import: importing %s " % project_record.summary_string())
130             project_record.sync() 
131     
132     # remove stale records    
133     system_records = [interface_hrn, root_auth, interface_hrn + '.slicemanager']
134     for (record_hrn, type) in existing_records.keys():
135         if record_hrn in system_records:
136             continue
137         
138         record = existing_records[(record_hrn, type)]
139         if record['peer_authority']:
140             continue
141
142         if type == 'user':
143             if record_hrn in persons_dict:
144                 continue  
145         elif type == 'slice':
146             if record_hrn in projects_dict:
147                 continue
148         else:
149             continue 
150         
151         record_object = existing_records[(record_hrn, type)]
152         record = SfaRecord(dict=record_object)
153         logger.info("Import: removing %s " % record.summary_string())
154         record.delete()
155                                    
156     # save pub keys
157     logger.info('Import: saving current pub keys')
158     save_keys(keys_filename, person_keys)                
159         
160 if __name__ == "__main__":
161     main()