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