initial checkin of openstack import script
[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 try:
31     from nova.auth.manager import AuthManager, db, context
32 except ImportError:
33     AuthManager = None
34     
35
36 def process_options():
37
38    (options, args) = getopt.getopt(sys.argv[1:], '', [])
39    for opt in options:
40        name = opt[0]
41        val = opt[1]
42
43
44 def load_keys(filename):
45     keys = {}
46     tmp_dict = {}
47     try:
48         execfile(filename, tmp_dict)
49         if 'keys' in tmp_dict:
50             keys = tmp_dict['keys']
51         return keys
52     except:
53         return keys
54
55 def save_keys(filename, keys):
56     f = open(filename, 'w')
57     f.write("keys = %s" % str(keys))
58     f.close()
59
60 def main():
61
62     process_options()
63     config = Config()
64     sfaImporter = sfaImport()
65     logger=sfaImporter.logger
66     logger.setLevelFromOptVerbose(config.SFA_API_LOGLEVEL)
67     if not config.SFA_REGISTRY_ENABLED:
68         sys.exit(0)
69     root_auth = config.SFA_REGISTRY_ROOT_AUTH
70     interface_hrn = config.SFA_INTERFACE_HRN
71     if  AuthManager:
72         auth_manager = AuthManager()
73     else:    
74         logger.info("Unable to import nova.auth.manager. Doesn't look like openstack-copute is installed. Exiting...")
75         sys.exit(0)    
76     sfaImporter.create_top_level_records()
77     
78     # create dict of all existing sfa records
79     existing_records = {}
80     existing_hrns = []
81     key_ids = []
82     table = SfaTable()
83     results = table.find()
84     for result in results:
85         existing_records[(result['hrn'], result['type'])] = result
86         existing_hrns.append(result['hrn']) 
87             
88         
89     # Get all users
90     persons = auth_manager.get_users()
91     persons_dict = {}
92     keys_filename = config.config_path + os.sep + 'person_keys.py' 
93     old_person_keys = load_keys(keys_filename)    
94     person_keys = {} 
95     for person in persons:
96         hrn = config.SFA_INTERFACE_HRN + "." + person.id
97         old_keys = old_person_keys.get(person.id, [])
98         keys = db.key_pair_get_all_by_user(context.get_admin_context(), person.id)
99         person_keys[person.id] = [key.public_key for key in keys]
100         update_record = False
101         if old_keys != keys:
102             update_record = True
103         if hrn not in existing_hrns or \
104                (hrn, 'user') not in existing_records or update_record:    
105             urn = hrn_to_urn(hrn, 'user')
106             if keys:
107                 try:
108                     pkey = convert_public_key(key)
109                 except:
110                     logger.warn('unable to convert public key for %s' % hrn)
111                     pkey = Keypair(create=True)
112             else:
113                 logger.warn("Import: person %s does not have a PL public key"%hrn)
114                 pkey = Keypair(create=True) 
115                 person_gid = sfaImporter.AuthHierarchy.create_gid(urn, create_uuid(), pkey)
116                 person_record = SfaRecord(hrn=hrn, gid=person_gid, type="user", \
117                                               authority=get_authority(hrn))
118                 persons_dict[person_record['hrn']] = person_record
119                 person_record.sync()
120
121     # Get all projects
122     projects = db.project_get_all(context.get_admin_context())
123     projects_dict = {}
124     for project in projects:
125         hrn = config.SFA_INTERFACE_HRN + '.' + project.id
126         if hrn not in existing_hrns or \
127         (hrn, 'slice') not in existing_records:
128             pkey = Keypair(create=True)
129             urn = hrn_to_urn(hrn, 'slice')
130             project_gid = sfaImporter.AuthHierarchy.create_gid(urn, create_uuid(), pkey)
131             project_record = SfaRecord(hrn=hrn, gid=project_gid, type="slice",
132                                        authority=get_authority(hrn))
133             projects_dict[project_record['hrn']] = project_record
134             project_record.sync(verbose=True) 
135     
136     # remove stale records    
137     system_records = [interface_hrn, root_auth, interface_hrn + '.slicemanager']
138     for (record_hrn, type) in existing_records.keys():
139         if record_hrn in system_records:
140             continue
141         
142         record = existing_records[(record_hrn, type)]
143         if record['peer_authority']:
144             continue
145
146         if type == 'user':
147             if record_hrn in persons_dict:
148                 continue  
149         elif type == 'slice':
150             if record_hrn in projects_dict:
151                 continue
152         else:
153             continue 
154         
155         record_object = existing_records[(record_hrn, type)]
156         record = SfaRecord(dict=record_object)
157         record.delete()
158                                    
159     # save pub keys
160     logger.info('Import: saving current pub keys')
161     save_keys(keys_filename, person_keys)                
162         
163 if __name__ == "__main__":
164     main()