cb4873e73461bc859407b99ffd8f05a67e2ebebb
[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.util.sfalogging import logger
25
26 from sfa.trust.gid import create_uuid    
27 from sfa.trust.certificate import convert_public_key, Keypair
28
29 from sfa.openstack.openstack_shell import OpenstackShell    
30
31 from sfa.storage.alchemy import dbsession
32 from sfa.storage.persistentobjs import RegRecord, RegAuthority, RegUser, RegSlice, RegNode
33
34 from sfa.importer.sfaImport import sfaImport, _cleanup_string
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     shell = OpenstackShell(config)
72     sfaImporter.create_top_level_records()
73     
74     # create dict of all existing sfa records
75     existing_records = {}
76     existing_hrns = []
77     key_ids = []
78     for record in dbsession.query(RegRecord):
79         existing_records[ (record.hrn, record.type,) ] = record
80         existing_hrns.append(record.hrn) 
81             
82         
83     # Get all users
84     persons = shell.user_get_all()
85     persons_dict = {}
86     keys_filename = config.config_path + os.sep + 'person_keys.py' 
87     old_person_keys = load_keys(keys_filename)
88     person_keys = {} 
89     for person in persons:
90         hrn = config.SFA_INTERFACE_HRN + "." + person.id
91         persons_dict[hrn] = person
92         old_keys = old_person_keys.get(person.id, [])
93         keys = [k.public_key for k in shell.key_pair_get_all_by_user(person.id)]
94         person_keys[person.id] = keys
95         update_record = False
96         if old_keys != keys:
97             update_record = True
98         if hrn not in existing_hrns or \
99                (hrn, 'user') not in existing_records or update_record:    
100             urn = hrn_to_urn(hrn, 'user')
101             
102             if keys:
103                 try:
104                     pkey = convert_public_key(keys[0])
105                 except:
106                     logger.log_exc('unable to convert public key for %s' % hrn)
107                     pkey = Keypair(create=True)
108             else:
109                 logger.warn("Import: person %s does not have a PL public key"%hrn)
110                 pkey = Keypair(create=True) 
111             person_gid = sfaImporter.AuthHierarchy.create_gid(urn, create_uuid(), pkey)
112             person_record = RegUser ()
113             person_record.type='user'
114             person_record.hrn=hrn
115             person_record.gid=person_gid
116             person_record.authority=get_authority(hrn)
117             dbsession.add(person_record)
118             dbsession.commit()
119             logger.info("Import: imported person %s" % person_record)
120
121     # Get all projects
122     projects = shell.project_get_all()
123     projects_dict = {}
124     for project in projects:
125         hrn = config.SFA_INTERFACE_HRN + '.' + project.id
126         projects_dict[hrn] = project
127         if hrn not in existing_hrns or \
128         (hrn, 'slice') not in existing_records:
129             pkey = Keypair(create=True)
130             urn = hrn_to_urn(hrn, 'slice')
131             project_gid = sfaImporter.AuthHierarchy.create_gid(urn, create_uuid(), pkey)
132             project_record = RegSlice ()
133             project_record.type='slice'
134             project_record.hrn=hrn
135             project_record.gid=project_gid
136             project_record.authority=get_authority(hrn)
137             dbsession.add(project_record)
138             dbsession.commit()
139             logger.info("Import: imported slice: %s" % project_record)  
140     
141     # remove stale records    
142     system_records = [interface_hrn, root_auth, interface_hrn + '.slicemanager']
143     for (record_hrn, type) in existing_records.keys():
144         if record_hrn in system_records:
145             continue
146         
147         record = existing_records[(record_hrn, type)]
148         if record.peer_authority:
149             continue
150
151         if type == 'user':
152             if record_hrn in persons_dict:
153                 continue  
154         elif type == 'slice':
155             if record_hrn in projects_dict:
156                 continue
157         else:
158             continue 
159         
160         record_object = existing_records[ (record_hrn, type) ]
161         logger.info("Import: removing %s " % record)
162         dbsession.delete(record_object)
163         dbsession.commit()
164                                    
165     # save pub keys
166     logger.info('Import: saving current pub keys')
167     save_keys(keys_filename, person_keys)                
168         
169 if __name__ == "__main__":
170     main()