Commit 7e71429a authored by Rob Carleski's avatar Rob Carleski 🇮🇸
Browse files

Remove google_create_resource

parent 1d8d6161
#!/usr/bin/env python
import argparse
import logging
import logging.handlers
import re
import string
import yaml
from subprocess import check_output as cmd
from subprocess import CalledProcessError
from time import sleep
class Resource:
def __init__(self, args, config):
self.__dict__.update(args)
self.config = config
self.logger = logging.getLogger(__name__)
self.resource_id = ''
_allowed = string.ascii_letters + string.digits
for char in self.name:
if char in _allowed:
self.resource_id += char.lower()
def create_resource(self):
try:
cmd([
self.config['google']['gam_command'],
'create',
'resource',
self.resource_id,
self.name,
'description',
self.description,
'type',
self.resource_type
])
sleep(1)
except CalledProcessError:
self.logger.error(
'Failed to create resource.',
extra={'entity': self.name}
)
exit(2)
try:
resource_info = cmd([
self.config['google']['gam_command'],
'info',
'resource',
self.resource_id
])
self.email = re.findall(b'Email: (.+)', resource_info)[0]
except CalledProcessError:
self.logger.error(
'Failed to fetch resource data after creation.',
extra={'entity': self.name}
)
exit(2)
def add_resource_owners(self):
for owner in self.owners:
try:
cmd([
self.config['google']['gam_command'],
'calendar',
self.email,
'add',
'owner',
owner
])
except CalledProcessError:
self.logger.warning(
'Failed to add {} as calendar owner'.format(owner),
extra={'entity': self.name}
)
continue
def strip_global_access(self):
try:
cmd([
self.config['google']['gam_command'],
'calendar',
self.email,
'delete',
'user',
'domain'
])
cmd([
self.config['google']['gam_command'],
'calendar',
self.email,
'delete',
'user',
'default'
])
except CalledProcessError as e:
self.logger.warning(
'Unable to remove domain-wide access to resource: {}'.format(
e.output
),
extra={'entity': self.name}
)
def generate_canned_text(self):
canned_text = '''
Hello,
Your requested resource calendar has been created. As the requester of
the resource, you and your fellow owners should now see it listed in
your own Google calendar.
Information about this new resource is as follows:
Calendar Name: {}
Calendar Type: {}
Calendar Description: {}
Calendar Owners: {}
Calendar ID: {}
If you have any questions about how to utilize this calendar, please
consult the documentation found at the following link:
http://documentation.its.umich.edu/node/660
If any of the above information is incorrect, please feel free to reply
to this message and your incident will be automatically reopened.'''.format(
self.name,
self.resource_type,
self.description,
','.join(self.owners),
self.email
)
print(
'============================================',
canned_text
)
def main():
helptext = '''examples:
google-create-resource -n AL1-B1-2510 -o kmoss aaliyah
google-create-resource --name AL1-B1-2510 --owners kmoss aaliyah
--type 'Private Office'
'''
parser = argparse.ArgumentParser(
description='Creates a new resource in GSuite',
epilog=helptext,
formatter_class=argparse.RawDescriptionHelpFormatter
)
parser.add_argument(
'--name',
'-n',
help='The name to assign to the resource.',
required=True
)
parser.add_argument(
'--owners',
'-o',
help='Users to give management access to.',
nargs='+',
required=True
)
parser.add_argument(
'--resource_type',
'-t',
help='The resource type.'
)
parser.add_argument(
'--description',
'-d',
help='A description of the resource.'
)
parser.add_argument(
'--config',
'-c',
help='The CAK config to use.',
default='/etc/collab-admin-kit.yml'
)
args = parser.parse_args()
# Open the CAK Config
with open(args.config) as stream:
config = yaml.load(stream, Loader=yaml.BaseLoader)
# Get the root logger and set the debug level
logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)
# Create a syslog handler, set format, and associate.
sh = logging.handlers.SysLogHandler(
address='/dev/log',
facility=config['general']['log_facility']
)
formatter = logging.Formatter(config['general']['log_format'])
sh.setFormatter(formatter)
logger.addHandler(sh)
# Create a console handler, set format, and associate.
ch = logging.StreamHandler()
formatter = logging.Formatter(config['general']['console_format'])
ch.setFormatter(formatter)
logger.addHandler(ch)
resource = Resource(args, config)
resource.create_resource()
resource.add_resource_owners()
resource.strip_global_access()
resource.generate_canned_text()
if __name__ == '__main__':
main()
import google_create_resource
import os
import pytest
import yaml
data_dir = os.path.join(os.path.dirname(__file__) + '/data/')
config = data_dir + 'test_cak_config.yml'
def test_create(capsys):
args = {
'name': 'Test Resource',
'owners': ['user1', 'user2'],
'resource_type': 'test resource',
'description': 'a test resource'
}
resource = google_create_resource.Resource(
args,
yaml.load(open(config), Loader=yaml.BaseLoader)
)
resource.create_resource()
resource.add_resource_owners()
resource.strip_global_access()
resource.generate_canned_text()
captured = capsys.readouterr()
assert 'Calendar Name: Test Resource' in captured.out
def test_with_bad_owner(caplog):
args = {
'name': 'Test Resource',
'owners': ['user1', 'failuser'],
'resource_type': 'test resource',
'description': 'a test resource'
}
resource = google_create_resource.Resource(
args,
yaml.load(open(config), Loader=yaml.BaseLoader)
)
resource.create_resource()
resource.add_resource_owners()
errorstr = 'Failed to add failuser as calendar owner'
assert errorstr in caplog.text
def test_create_duplicate(caplog):
with pytest.raises(SystemExit):
args = {
'name': 'duplicate',
'owners': ['user1', 'user2'],
'resource_type': 'test resource',
'description': 'a test resource'
}
resource = google_create_resource.Resource(
args,
yaml.load(open(config), Loader=yaml.BaseLoader)
)
resource.create_resource()
def test_fail_retrieval(caplog):
with pytest.raises(SystemExit):
args = {
'name': 'missing',
'owners': ['user1', 'user2'],
'resource_type': 'test resource',
'description': 'a test resource'
}
resource = google_create_resource.Resource(
args,
yaml.load(open(config), Loader=yaml.BaseLoader)
)
resource.create_resource()
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment