first rough version of a complete sfi myslice
[sfa.git] / sfa / client / manifolduploader.py
1 #!/usr/bin/env python
2 #
3 # inspired from tophat/bin/uploadcredential.py
4 #
5 # the purpose here is to let people upload their delegated credentials
6 # to a manifold/myslice infrastructure, without the need for having to
7 # install a separate tool; so duplicating this code is suboptimal in
8 # terms of code sharing but acceptable for hopefully easier use
9 #
10 # As of April 2013, manifold is moving from old-fashioned API known as
11 # v1, that offers an AddCredential API call, towards a new API v2 that
12 # manages credentials with the same set of Get/Update calls as other
13 # objects
14
15 # Since this code targets the future we favour v2, however in case
16 # this won't work the v1 way is attempted too
17 #
18
19 ## this for now points at demo.myslice.info, but sounds like a
20 ## better default for the long run
21 DEFAULT_URL = "http://myslice.onelab.eu:7080"
22 DEFAULT_PLATFORM = 'ple'
23
24 import xmlrpclib
25 import getpass
26
27 class ManifoldUploader:
28     """A utility class for uploading delegated credentials to a manifold/MySlice infrastructure"""
29
30     # platform is a name internal to the manifold deployment, 
31     # that maps to a testbed, like e.g. 'ple'
32     def __init__ (self, logger, url=None, platform=None, username=None, password=None, ):
33         self._url=url
34         self._platform=platform
35         self._username=username
36         self._password=password
37         self.logger=logger
38
39     def username (self):
40         if not self._username: 
41             self._username=raw_input("Enter your manifold username: ")
42         return self._username            
43
44     def password (self):
45         if not self._password: 
46             username=self.username()
47             self._password=getpass.getpass("Enter password for manifold user %s: "%username)
48         return self._password            
49
50     def platform (self):
51         if not self._platform: 
52             self._platform=raw_input("Enter your manifold platform [%s]: "%DEFAULT_PLATFORM)
53             if self._platform.strip()=="": self._platform = DEFAULT_PLATFORM
54         return self._platform            
55
56     def url (self):
57         if not self._url: 
58             self._url=raw_input("Enter the URL for your manifold API [%s]: "%DEFAULT_URL)
59             if self._url.strip()=="": self._url = DEFAULT_URL
60         return self._url            
61
62     # does the job for one credential
63     # expects the credential (string) and an optional message for reporting
64     # return True upon success and False otherwise
65     def upload (self, delegated_credential, message=None):
66         url=self.url()
67         platform=self.platform()
68         username=self.username()
69         password=self.password()
70         auth = {'AuthMethod': 'password', 'Username': username, 'AuthString': password}
71         if not message: message=""
72
73         try:
74             self.logger.debug("Connecting manifold url %s"%url)
75             manifold = xmlrpclib.Server(url, allow_none = 1)
76             # the code for a V2 interface
77             query= { 'action':       'update',
78                      'fact_table':   'local:account',
79                      'filters':      [ ['platform', '=', platform] ] ,
80                      'params':       {'credential': delegated_credential, },
81                      }
82             try:
83                 self.logger.debug("Trying v2 method Update %s"%message)
84                 retcod2=manifold.Update (auth, query)
85             except Exception,e:
86                 # xxx we need a constant constant for UNKNOWN, how about using 1
87                 MANIFOLD_UNKNOWN=1
88                 retcod2={'code':MANIFOLD_UNKNOWN,'output':"%s"%e}
89             if retcod2['code']==0:
90                 info=""
91                 if message: info += message+" "
92                 info += 'v2 upload OK'
93                 self.logger.info(info)
94                 return True
95             #print delegated_credential, "upload failed,",retcod['output'], \
96             #    "with code",retcod['code']
97             # the code for V1
98             try:
99                 self.logger.debug("Trying v1 method AddCredential %s"%message)
100                 retcod1=manifold.AddCredential(auth, delegated_credential, platform)
101             except Exception,e:
102                 retcod1=e
103             if retcod1==1:
104                 info=""
105                 if message: info += message+" "
106                 info += 'v1 upload OK'
107                 self.logger.info(message)
108                 return True
109             # everything has failed, let's report
110             if message: self.logger.error("Could not upload %s"%message)
111             else: self.logger.error("Could not upload credential")
112             self.logger.info("  V2 Update returned code %s and error %s"%(retcod2['code'],retcod2['output']))
113             self.logger.info("  V1 AddCredential returned code %s (expected 1)"%retcod1)
114             return False
115         except Exception, e:
116             if message: self.logger.error("Could not upload %s %s"%(message,e))
117             else:        self.logger.error("Could not upload credential %s"%e)
118             if self.logger.debugEnabled():
119                 import traceback
120                 traceback.print_exc()
121
122 ### this is mainly for unit testing this class but can come in handy as well
123 def main ():
124     from argparse import ArgumentParser
125     parser = ArgumentParser (description="manifoldupoader simple tester.")
126     parser.add_argument ('credential_files',metavar='FILE',type=str,nargs='+',
127                          help="the filenames to upload")
128     parser.add_argument ('-u','--url',dest='url', action='store',default=None,
129                          help='the URL of the manifold API')
130     parser.add_argument ('-p','--platform',dest='platform',action='store',default=None,
131                          help='the manifold platform name')
132     parser.add_argument ('-U','--user',dest='username',action='store',default=None,
133                          help='the manifold username')
134     parser.add_argument ('-P','--password',dest='password',action='store',default=None,
135                          help='the manifold password')
136     args = parser.parse_args ()
137     
138     from sfa.util.sfalogging import sfi_logger
139     uploader = ManifoldUploader (url=args.url, platform=args.platform,
140                                  username=args.username, password=args.password,
141                                  logger=sfi_logger)
142     for filename in args.credential_files:
143         with file(filename) as f:
144             result=uploader.upload (f.read(),filename)
145             sfi_logger.info('... result=%s'%result)
146
147 if __name__ == '__main__':
148     main()