use sfa.openstack.openstack_shell to interact with openstack back end
[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         old_keys = old_person_keys.get(person.id, [])
90         keys = shell.key_pair_get_all_by_user(person.id)
91         person_keys[person.id] = [key.public_key for key in keys]
92         update_record = False
93         if old_keys != keys:
94             update_record = True
95         if hrn not in existing_hrns or \
96                (hrn, 'user') not in existing_records or update_record:    
97             urn = hrn_to_urn(hrn, 'user')
98             if keys:
99                 try:
100                     pkey = convert_public_key(key)
101                 except:
102                     logger.warn('unable to convert public key for %s' % hrn)
103                     pkey = Keypair(create=True)
104             else:
105                 logger.warn("Import: person %s does not have a PL public key"%hrn)
106                 pkey = Keypair(create=True) 
107                 person_gid = sfaImporter.AuthHierarchy.create_gid(urn, create_uuid(), pkey)
108                 person_record = SfaRecord(hrn=hrn, gid=person_gid, type="user", \
109                                               authority=get_authority(hrn))
110                 persons_dict[person_record['hrn']] = person_record
111                 person_record.sync()
112
113     # Get all projects
114     projects = shell.project_get_all()
115     projects_dict = {}
116     for project in projects:
117         hrn = config.SFA_INTERFACE_HRN + '.' + project.id
118         if hrn not in existing_hrns or \
119         (hrn, 'slice') not in existing_records:
120             pkey = Keypair(create=True)
121             urn = hrn_to_urn(hrn, 'slice')
122             project_gid = sfaImporter.AuthHierarchy.create_gid(urn, create_uuid(), pkey)
123             project_record = SfaRecord(hrn=hrn, gid=project_gid, type="slice",
124                                        authority=get_authority(hrn))
125             projects_dict[project_record['hrn']] = project_record
126             project_record.sync() 
127     
128     # remove stale records    
129     system_records = [interface_hrn, root_auth, interface_hrn + '.slicemanager']
130     for (record_hrn, type) in existing_records.keys():
131         if record_hrn in system_records:
132             continue
133         
134         record = existing_records[(record_hrn, type)]
135         if record['peer_authority']:
136             continue
137
138         if type == 'user':
139             if record_hrn in persons_dict:
140                 continue  
141         elif type == 'slice':
142             if record_hrn in projects_dict:
143                 continue
144         else:
145             continue 
146         
147         record_object = existing_records[(record_hrn, type)]
148         record = SfaRecord(dict=record_object)
149         record.delete()
150                                    
151     # save pub keys
152     logger.info('Import: saving current pub keys')
153     save_keys(keys_filename, person_keys)                
154         
155 if __name__ == "__main__":
156     main()