def execute(self):
"""
Returns GSuite events based on given app/activity.
Other parameters are optional.
"""
logging.debug("Authenticating to GSuite")
self.get_credentials()
self.http = self.credentials.authorize(httplib2.Http())
self.service = discovery.build('admin', 'reports_v1', http=self.http)
logging.debug("Retrieving %s events from: %s to %s", self.app, convert_time(self.s_time), convert_time(self.e_time))
self.results = self.service.activities().list(userKey=self.user,
applicationName=self.app,
startTime=self.s_time,
endTime=self.e_time,
maxResults=self.max).execute()
return self.results.get('items', [])
python类items()的实例源码
def processConfigFile(self, configFile=None):
if configFile is not None:
self.__serverConfig = ConfigParser.ConfigParser()
self.__serverConfig.read(configFile)
sections = self.__serverConfig.sections()
# Let's check the log file
self.__logFile = self.__serverConfig.get('global','log_file')
if self.__logFile != 'None':
logging.basicConfig(filename = self.__logFile,
level = logging.DEBUG,
format="%(asctime)s: %(levelname)s: %(message)s",
datefmt = '%m/%d/%Y %I:%M:%S %p')
# Remove the global one
del(sections[sections.index('global')])
self._shares = {}
for i in sections:
self._shares[i] = dict(self.__serverConfig.items(i))
def __repr__(self, *, indent=1, header=False):
result = []
if header:
result.extend([' ' * indent, '<', self.__class__.__name__, '>\n'])
indent += 1
for k, v in sorted(self.__dict__.items()):
if k.startswith('_'):
continue
result.append(' ' * indent)
result.append(k)
result.append(': ')
if isinstance(v, Octopus):
result.append('\n')
result.append(v.__repr__(indent=indent + 1, header=False))
else:
result.append(str(v))
result.append('\n')
return ''.join(result)
def processConfigFile(self, configFile=None):
if configFile is not None:
self.__serverConfig = ConfigParser.ConfigParser()
self.__serverConfig.read(configFile)
sections = self.__serverConfig.sections()
# Let's check the log file
self.__logFile = self.__serverConfig.get('global','log_file')
if self.__logFile != 'None':
logging.basicConfig(filename = self.__logFile,
level = logging.DEBUG,
format="%(asctime)s: %(levelname)s: %(message)s",
datefmt = '%m/%d/%Y %I:%M:%S %p')
# Remove the global one
del(sections[sections.index('global')])
self._shares = {}
for i in sections:
self._shares[i] = dict(self.__serverConfig.items(i))
def processConfigFile(self, configFile=None):
if configFile is not None:
self.__serverConfig = ConfigParser.ConfigParser()
self.__serverConfig.read(configFile)
sections = self.__serverConfig.sections()
# Let's check the log file
self.__logFile = self.__serverConfig.get('global','log_file')
if self.__logFile != 'None':
logging.basicConfig(filename = self.__logFile,
level = logging.DEBUG,
format="%(asctime)s: %(levelname)s: %(message)s",
datefmt = '%m/%d/%Y %I:%M:%S %p')
# Remove the global one
del(sections[sections.index('global')])
self._shares = {}
for i in sections:
self._shares[i] = dict(self.__serverConfig.items(i))
def __init__(self, filename, header):
config = SafeConfigParser()
cfgfile = config.read(filename)
if not cfgfile:
raise ValueError('Config file not found:', filename)
self.__dict__.update(config.items(header))
def getShares(connId, smbServer):
config = smbServer.getServerConfig()
sections = config.sections()
# Remove the global one
del(sections[sections.index('global')])
shares = {}
for i in sections:
shares[i] = dict(config.items(i))
return shares
def searchShare(connId, share, smbServer):
config = smbServer.getServerConfig()
if config.has_section(share):
return dict(config.items(share))
else:
return None
def items(self):
return self.__dict__.items()
def processing(self, config, path=None):
for k, v in config.items():
p = '.'.join(i for i in (path, k) if i)
for processor in self:
m = processor.match(self.context, p, v)
if m is None:
continue
if m.process:
self.on_ready.append(m.process)
break
else:
if isinstance(v, Mapping):
self.processing(v, p)
def getShares(connId, smbServer):
config = smbServer.getServerConfig()
sections = config.sections()
# Remove the global one
del(sections[sections.index('global')])
shares = {}
for i in sections:
shares[i] = dict(config.items(i))
return shares
def searchShare(connId, share, smbServer):
config = smbServer.getServerConfig()
if config.has_section(share):
return dict(config.items(share))
else:
return None
def getShares(connId, smbServer):
config = smbServer.getServerConfig()
sections = config.sections()
# Remove the global one
del(sections[sections.index('global')])
shares = {}
for i in sections:
shares[i] = dict(config.items(i))
return shares
def searchShare(connId, share, smbServer):
config = smbServer.getServerConfig()
if config.has_section(share):
return dict(config.items(share))
else:
return None
def parse_config(self, arguments=None):
finalconfig = {}
args = self.parser.parse_args(arguments)
config = configparser.SafeConfigParser()
try:
with open(args.config) as fdconfig:
config.readfp(fdconfig)
except Exception as e:
msg = "Ignoring configuration file '%s'"
self.logger.warn(msg % (args.config))
for section in self.PARAMETERS.keys():
config.add_section(section)
else:
self.logger.info("Read configuration file '%s'" % args.config)
for section in self.PARAMETERS.keys():
cfgsection = dict(config.items(section))
for var, required in self.PARAMETERS[section].iteritems():
try:
# build env variables like IRONIC_URL
envparameter = section.upper() + '_' + var.upper()
cfgsection[var] = os.environ[envparameter]
msg = "Reading env variable '%s'" % envparameter
self.logger.debug(msg)
except:
pass
if required and not var in cfgsection:
msg = "Variable '%s.%s' not defined and it is required!"
msg = msg % (section, var)
self.logger.error(msg)
raise ValueError(msg)
finalconfig[section] = cfgsection
self.args = args
return finalconfig
def getShares(connId, smbServer):
config = smbServer.getServerConfig()
sections = config.sections()
# Remove the global one
del(sections[sections.index('global')])
shares = {}
for i in sections:
shares[i] = dict(config.items(i))
return shares
def searchShare(connId, share, smbServer):
config = smbServer.getServerConfig()
if config.has_section(share):
return dict(config.items(share))
else:
return None
def load_config(conf_file):
"""Loads redfish.conf file
Loads and parsers the system conf file into config global var
Loads json schemas into schemas_dict global var
Established a connection with OneView and sets in as ov_conn
global var
Args:
conf_file: string with the conf file name
Returns:
None
Exception:
OneViewRedfishResourceNotFoundError:
- if conf file not found
- if any of the schemas files are not found
- if the schema directory is not found
OneViewRedFishResourceNotAccessibleError:
- if can't access schema's directory
HPOneViewException:
- if fails to connect to oneview
"""
config = load_conf(conf_file)
globals()['config'] = config
# Config file read set global vars
# Setting ov_config
ov_config = dict(config.items('oneview_config'))
ov_config['credentials'] = dict(config.items('credentials'))
ov_config['api_version'] = int(ov_config['api_version'])
globals()['ov_config'] = ov_config
# Setting schemas_dict
schemas = dict(config.items('schemas'))
globals()['schemas'] = schemas
registries = dict(config.items('registry'))
# Load schemas | Store schemas | Connect to OneView
try:
ov_client = OneViewClient(ov_config)
globals()['ov_client'] = ov_client
registry_dict = load_registry(
config['redfish']['registry_dir'],
registries)
globals()['registry_dict'] = registry_dict
store_schemas(config['redfish']['schema_dir'])
except errors.OneViewRedfishResourceNotFoundError as e:
raise errors.OneViewRedfishError(
'Failed to load schemas or registries: {}'.format(e)
)
except Exception as e:
raise errors.OneViewRedfishError(
'Failed to connect to OneView: {}'.format(e)
)
def get_oneview_client(session_id=None, is_service_root=False):
"""Establishes a OneView connection to be used in the module
Establishes a OV connection if one does not exists.
If one exists, do a single OV access to check if its sill
valid. If not tries to establish a new connection.
Sets the connection on the ov_conn global var
Args:
session_id: The ID of a valid authenticated session, if the
authentication_mode is session. Defaults to None.
is_service_root: Informs if who is calling this function is the
ServiceRoot blueprint. If true, even if authentication_mode is
set to session it will use the information on the conf file to
return a connection. This is a workaround to allow ServiceRoot
to retrieve the appliance UUID before user logs in.
Returns:
OneViewClient object
Exceptions:
HPOneViewException if can't connect or reconnect to OV
"""
config = globals()['config']
auth_mode = config["redfish"]["authentication_mode"]
if auth_mode == "conf" or is_service_root:
# Doing conf based authentication
ov_client = globals()['ov_client']
ov_config = globals()['ov_config']
# Check if connection is ok yet
try:
ov_client.connection.get('/rest/logindomains')
return ov_client
# If expired try to make a new connection
except Exception:
try:
logging.exception('Re-authenticated')
ov_client.connection.login(ov_config['credentials'])
return ov_client
# if faild abort
except Exception:
raise
else:
# Auth mode is session
oneview_config = dict(config.items('oneview_config'))
oneview_config['credentials'] = {"sessionID": session_id}
oneview_config['api_version'] = int(oneview_config['api_version'])
try:
oneview_client = OneViewClient(oneview_config)
oneview_client.connection.get('/rest/logindomains')
return oneview_client
except Exception:
logging.exception("Failed to recover session based connection")
raise
def generate_certificate(dir_name, file_name, key_length, key_type="rsa"):
"""Create self-signed cert and key files
Args:
dir_name: name of the directory to store the files
file_name: name of the files that will be created. It will append
.crt to certificate file and .key to key file
key_length: key length in bits
key_type: crypto type: RSA or DSA; defaults to RSA
Returns:
Nothing
Exceptions:
Raise exceptions on error
"""
config = globals()['config']
private_key = OpenSSL.crypto.PKey()
if key_type == "rsa":
private_key.generate_key(OpenSSL.crypto.TYPE_RSA, key_length)
elif key_type == "dsa":
private_key.generate_key(OpenSSL.crypto.TYPE_DSA, key_length)
else:
message = "Invalid key_type"
logging.error(message)
raise errors.OneViewRedfishError(message)
if not config.has_option("ssl-cert-defaults", "commonName"):
config["ssl-cert-defaults"]["commonName"] = get_ip()
cert = OpenSSL.crypto.X509()
cert_subject = cert.get_subject()
cert_defaults = dict(config.items("ssl-cert-defaults"))
for key, value in cert_defaults.items():
setattr(cert_subject, key, value)
cert.set_serial_number(1)
cert.gmtime_adj_notBefore(0)
cert.gmtime_adj_notAfter(10 * 365 * 24 * 60 * 60)
cert.set_issuer(cert.get_subject())
cert.set_pubkey(private_key)
cert.sign(private_key, "sha1")
# Save Files
with open(os.path.join(dir_name, file_name + ".crt"), "wt") as f:
f.write(OpenSSL.crypto.dump_certificate(
OpenSSL.crypto.FILETYPE_PEM, cert).decode("UTF-8"))
with open(os.path.join(dir_name, file_name + ".key"), "wt") as f:
f.write(OpenSSL.crypto.dump_privatekey(
OpenSSL.crypto.FILETYPE_PEM, private_key).decode("UTF-8"))