text
stringlengths
0
1.05M
meta
dict
'''Arsenal API Db Reports.''' # Copyright 2015 CityGrid Media, LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # import logging from pyramid.view import view_config from pyramid.response import Response from sqlalchemy.orm.exc import NoResultFound from arsenalweb.views.api.common import ( api_200, ) from arsenalweb.models.common import ( DBSession, Base, ) LOG = logging.getLogger(__name__) @view_config(route_name='api_reports_db', request_method='GET', request_param='schema=true', renderer='json') def api_reports_db_schema(request): '''Schema document for tags API''' tag = { } return tag @view_config(route_name='api_reports_db', request_method='GET', renderer='json') def api_reports_db_read(request): '''Process read requests for the /api/reports/db route.''' query = DBSession.execute("SHOW STATUS WHERE Variable_name IN ('wsrep_local_recv_que_avg', 'wsrep_connected', 'wsrep_cluster_conf_id', 'wsrep_cluster_state_uuid', 'wsrep_local_state_comment', 'wsrep_cluster_status', 'wsrep_cluster_size', 'wsrep_ready')") db_status = {} for row in query: db_status[row[0]] = row[1] row_counts = {} for my_table in Base.metadata.tables.keys(): LOG.debug('Counting rows in table {0}'.format(my_table)) table_count = DBSession.execute('SELECT COUNT(*) FROM {0}'.format(my_table)) table_count = table_count.fetchone() row_counts[my_table] = table_count[0] LOG.debug('table: {0} count: {1}'.format(my_table, table_count[0])) db_status['row_counts'] = row_counts LOG.debug(db_status) return api_200(results=db_status)
{ "repo_name": "CityGrid/arsenal", "path": "server/arsenalweb/views/api/reports/db.py", "copies": "1", "size": "2149", "license": "apache-2.0", "hash": -8702274184045836000, "line_mean": 34.2295081967, "line_max": 258, "alpha_frac": 0.6947417403, "autogenerated": false, "ratio": 3.454983922829582, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.4649725663129582, "avg_score": null, "num_lines": null }
'''Arsenal API ec2_instance.''' # Copyright 2015 CityGrid Media, LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # import logging from datetime import datetime from pyramid.view import view_config from sqlalchemy.orm.exc import NoResultFound from arsenalweb.views.api.common import ( api_500, collect_params, ) from arsenalweb.models.common import ( DBSession, ) from arsenalweb.models.ec2_instances import ( Ec2Instance, Ec2InstanceAudit, ) LOG = logging.getLogger(__name__) def find_ec2_instance_by_id(instance_id): '''Find an ec2_instance by it's instance_id. Returns an ec2_instance if found, raises NoResultFound otherwise.''' LOG.debug('Searching for ec2_instance by instance_id: {0}'.format(instance_id)) ec2 = DBSession.query(Ec2Instance) ec2 = ec2.filter(Ec2Instance.instance_id == instance_id) return ec2.one() def create_ec2_instance(instance_id=None, updated_by=None, **kwargs): '''Create a new ec2_instance. Required params: instance_id: A string that is the ec2 instance ID. updated_by : A string that is the user making the update. Optional kwargs: ami_id : A string that is the ami_id. hostname : A string that is the hostname. instance_id : A string that is the instance_id. instance_type : A string that is the instance_type. availability_zone: A string that is the availability_zone. profile : A string that is the profile. reservation_id : A string that is the reservation_id. security_groups : A string that is the security_groups. ''' try: LOG.info('Creating new ec2_instance id: {0}'.format(instance_id)) utcnow = datetime.utcnow() ec2 = Ec2Instance(instance_id=instance_id, updated_by=updated_by, created=utcnow, updated=utcnow, **kwargs) DBSession.add(ec2) DBSession.flush() audit = Ec2InstanceAudit(object_id=ec2.id, field='instance_id', old_value='created', new_value=ec2.instance_id, updated_by=updated_by, created=utcnow) DBSession.add(audit) DBSession.flush() return ec2 except Exception as ex: msg = 'Error creating new ec2_instance id: {0} ' \ 'exception: {1}'.format(instance_id, ex) LOG.error(msg) return api_500(msg=msg) def update_ec2_instance(ec2, **kwargs): '''Update an existing ec2_instance. Required params: ec2: The existing ec2 object to update. updated_by : A string that is the user making the update. Optional kwargs: ami_id : A string that is the ami_id. hostname : A string that is the hostname. instance_type : A string that is the instance_type. availability_zone: A string that is the availability_zone. profile : A string that is the profile. reservation_id : A string that is the reservation_id. security_groups : A string that is the security_groups. ''' try: # Convert everything that is defined to a string. my_attribs = kwargs.copy() for my_attr in my_attribs: if my_attribs.get(my_attr): my_attribs[my_attr] = str(my_attribs[my_attr]) LOG.info('Updating ec2_instance ec2_instance_id={0}'.format(ec2.instance_id)) utcnow = datetime.utcnow() for attribute in my_attribs: if attribute == 'instance_id': LOG.debug('Skipping update to ec2.instance_id.') continue old_value = getattr(ec2, attribute) new_value = my_attribs[attribute] if old_value != new_value and new_value: if not old_value: old_value = 'None' LOG.debug('Updating ec2_instance: {0} attribute: ' '{1} new_value: {2}'.format(ec2.instance_id, attribute, new_value)) audit = Ec2InstanceAudit(object_id=ec2.id, field=attribute, old_value=old_value, new_value=new_value, updated_by=my_attribs['updated_by'], created=utcnow) DBSession.add(audit) setattr(ec2, attribute, new_value) DBSession.flush() return ec2 except Exception as ex: LOG.error('Error updating ec2_instance instance_id={0},' 'exception={1}'.format(ec2.instance_id, repr(ex))) raise @view_config(route_name='api_ec2_instances', request_method='GET', request_param='schema=true', renderer='json') def api_ec2_instances_schema(request): '''Schema document for the ec2_instances API.''' ec2 = { } return ec2 @view_config(route_name='api_ec2_instances', permission='api_write', request_method='PUT', renderer='json') def api_ec2_instance_write(request): '''Process write requests for /api/ec2_instances route.''' try: req_params = [ 'instance_id', ] opt_params = [ 'ami_id', 'availability_zone', 'hostname', 'instance_type', 'profile', 'reservation_id', 'security_groups', ] params = collect_params(request, req_params, opt_params) LOG.debug('Searching for ec2_instance id: {0}'.format(params['instance_id'])) try: ec2 = find_ec2_instance_by_id(params['instance_id']) ec2 = update_ec2_instance(ec2, **params) except NoResultFound: ec2 = create_ec2_instance(**params) return ec2 except Exception as ex: msg = 'Error writing to ec2_instances API: {0} exception: {1}'.format(request.url, repr(ex)) LOG.error(msg) return api_500(msg=msg)
{ "repo_name": "CityGrid/arsenal", "path": "server/arsenalweb/views/api/ec2_instances.py", "copies": "1", "size": "6789", "license": "apache-2.0", "hash": 916379930126695700, "line_mean": 33.2878787879, "line_max": 112, "alpha_frac": 0.5759316541, "autogenerated": false, "ratio": 4.045887961859356, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5121819615959357, "avg_score": null, "num_lines": null }
'''Arsenal API ENC for puppet.''' # Copyright 2015 CityGrid Media, LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # import logging from pyramid.view import view_config from sqlalchemy.orm.exc import NoResultFound from arsenalweb.models.common import ( DBSession, ) from arsenalweb.models.nodes import ( Node, ) from arsenalweb.views.api.common import ( api_200, api_400, api_500, api_501, ) from arsenalweb.views.api.data_centers import ( find_data_center_by_id, ) LOG = logging.getLogger(__name__) def find_node_by_name_and_status(settings, node_name): '''Find a node by name, filtered by statuses''' try: status_ids = [s for s in settings['arsenal.enc.status_ids'].splitlines() if s] except KeyError as ex: msg = 'You must define arsenal.enc.status_ids in the main settings file to ' \ 'enable the enc.' LOG.error(msg) raise type(ex)(ex.message + ' {0}'.format(msg)) node = DBSession.query(Node) node = node.filter(Node.status_id.in_(status_ids)) node = node.filter(Node.name == node_name) return node.one() def process_tags(tags, tag_type): '''Processes tags. If the value is 'True' or 'False', converts it to a boolean. Otherwise returns as-is (what about integers?).''' results = {} for tag in tags: LOG.debug('{0} tag: {1}={2}'.format(tag_type, tag.name, tag.value)) if tag.value == 'True': results[tag.name] = bool(tag.value) elif tag.value == 'False': results[tag.name] = bool('') else: try: my_value = tag.value my_value = int(my_value) except ValueError: pass results[tag.name] = my_value return results def process_node_enc(settings, node_name, param_sources=False): '''Process enc for node. Merges tags from the following three objects in order from least to most specific: node_group data_center node Multiple node groups are sorted and take priority..?''' results = {} results['classes'] = [] results['parameters'] = {} results['status'] = { 'name': None, } if param_sources: results['param_sources'] = {} try: node = find_node_by_name_and_status(settings, node_name) results['name'] = node.name results['id'] = node.id results['status'] = node.status LOG.debug('node name is: {0}'.format(node.name)) LOG.debug('node datacenter is: {0}'.format(node.data_center_id)) # What happens when there's more than one node group? What tags # win, alphabetic? for node_group in node.node_groups: LOG.debug('node_group: {0}'.format(node_group.name)) results['classes'].append(node_group.name) my_tags = process_tags(node_group.tags, 'node_group') results['parameters'].update(my_tags) if param_sources: for tag in my_tags: results['param_sources'][tag] = 'node_group' data_center = find_data_center_by_id(node.data_center_id) my_tags = process_tags(data_center.tags, 'data_center') results['parameters'].update(my_tags) if param_sources: for tag in my_tags: results['param_sources'][tag] = 'data_center' my_tags = process_tags(node.tags, 'node') results['parameters'].update(my_tags) if param_sources: for tag in my_tags: results['param_sources'][tag] = 'node' except NoResultFound: LOG.debug('node not found: {0}'.format(node_name)) except (AttributeError, KeyError): raise return results @view_config(route_name='api_enc', request_method='GET', renderer='json') def api_enc(request): '''External node classifier for puppet. Takes a required request parameter 'name', finds all node_groups associated witht he node, and all tags merged based on the following hierarchy: node_group data_center node Optional request parameter 'param_sources' will add an additional key that identifies what level of the hierarchy each tag comes from. Returns a dict.''' settings = request.registry.settings try: try: name = request.params['name'] except KeyError as ex: msg = "Bad Request. Parameter 'name' is required." LOG.error(msg) return api_400(msg=msg) try: param_sources = request.params['param_sources'] except KeyError: param_sources = False LOG.debug('Starting enc for node: {0}'.format(name)) try: results = process_node_enc(settings, name, param_sources=param_sources) except (AttributeError, KeyError) as ex: return api_501(msg=repr(ex)) except Exception as ex: msg = 'Error calling enc! Exception: {0}'.format(repr(ex)) LOG.error(msg) return api_500(msg=msg) return api_200(results=results)
{ "repo_name": "CityGrid/arsenal", "path": "server/arsenalweb/views/api/enc.py", "copies": "1", "size": "5630", "license": "apache-2.0", "hash": 3331748297912140300, "line_mean": 32.1176470588, "line_max": 86, "alpha_frac": 0.6150976909, "autogenerated": false, "ratio": 3.840381991814461, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.4955479682714461, "avg_score": null, "num_lines": null }
'''Arsenal API hardware_profiles.''' # Copyright 2015 CityGrid Media, LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # import logging from datetime import datetime from pyramid.view import view_config from pyramid.response import Response from sqlalchemy.orm.exc import NoResultFound from arsenalweb.models.common import ( DBSession, ) from arsenalweb.models.hardware_profiles import ( HardwareProfile, HardwareProfileAudit, ) from arsenalweb.views import ( get_authenticated_user, ) from arsenalweb.views.api.common import ( api_500, ) LOG = logging.getLogger(__name__) def get_hardware_profile(name): '''Get a hardware_profile from the database.''' try: query = DBSession.query(HardwareProfile) query = query.filter(HardwareProfile.name == name) hardware_profile = query.one() return hardware_profile except (NoResultFound, AttributeError): LOG.debug('hardware_profile not found name={0},'.format(name)) return None def create_hardware_profile(name, manufacturer, model, user_id): '''Create a new hardware_profile.''' try: LOG.info('Creating new hardware_profile name={0},manufacturer={1},' 'model={2}'.format(name, manufacturer, model)) utcnow = datetime.utcnow() hardware_profile = HardwareProfile(name=name, manufacturer=manufacturer, model=model, updated_by=user_id, created=utcnow, updated=utcnow) DBSession.add(hardware_profile) DBSession.flush() audit = HardwareProfileAudit(object_id=hardware_profile.id, field='name', old_value='created', new_value=hardware_profile.name, updated_by=user_id, created=utcnow) DBSession.add(audit) DBSession.flush() return hardware_profile except Exception as ex: LOG.error('Error creating new harware_profile name={1},manufacturer={2},' 'model={3},exception={4}'.format(name, manufacturer, model, ex)) raise def update_hardware_profile(hardware_profile, name, manufacturer, model, user_id): '''Update an existing hardware_profile.''' try: LOG.info('Updating hardware_profile name={0},manufacturer={1},' 'model={2}'.format(name, manufacturer, model)) utcnow = datetime.utcnow() for attribute in ['name', 'manufacturer', 'model']: if getattr(hardware_profile, attribute) != locals()[attribute]: LOG.debug('Updating hardware profile {0}: {1}'.format(attribute, locals()[attribute])) audit = HardwareProfileAudit(object_id=hardware_profile.id, field=attribute, old_value=getattr(hardware_profile, attribute), new_value=locals()[attribute], updated_by=user_id, created=utcnow) DBSession.add(audit) hardware_profile.name = name hardware_profile.manufacturer = manufacturer hardware_profile.model = model hardware_profile.updated_by = user_id DBSession.flush() return hardware_profile except Exception as ex: LOG.error('Error updating hardware_profile name={0},manufacturer={1},' 'model={2},exception={3}'.format(name, manufacturer, model, ex)) raise @view_config(route_name='api_hardware_profiles', request_method='GET', request_param='schema=true', renderer='json') def api_hardware_profiles_schema(request): '''Schema document for the hardware_profiles API.''' hardware_profile = { 'id': 'Integer', 'name': 'String', 'model': 'String', 'manufacturer': 'String', 'created': 'Timestamp', 'updated': 'Timestamp', 'updated_by': 'String', } return hardware_profile @view_config(route_name='api_hardware_profiles', permission='api_write', request_method='PUT', renderer='json') def api_hardware_profile_write(request): '''Process write requests for /api/hardware_profiles route.''' try: auth_user = get_authenticated_user(request) payload = request.json_body name = payload['name'].rstrip() manufacturer = payload['manufacturer'].rstrip() model = payload['model'].rstrip() hardware_profile = get_hardware_profile(name) if not hardware_profile: hardware_profile = create_hardware_profile(name, manufacturer, model, auth_user['user_id']) else: update_hardware_profile(hardware_profile, name, manufacturer, model, auth_user['user_id']) LOG.debug('hardware_profile is: {0}'.format(hardware_profile.__dict__)) return hardware_profile except Exception as ex: msg = 'Error writing to harware_profiles API={0},exception={1}'.format(request.url, ex) LOG.error(msg) return api_500(msg=msg)
{ "repo_name": "CityGrid/arsenal", "path": "server/arsenalweb/views/api/hardware_profiles.py", "copies": "1", "size": "6297", "license": "apache-2.0", "hash": 3949316808963697700, "line_mean": 35.8245614035, "line_max": 116, "alpha_frac": 0.5602667937, "autogenerated": false, "ratio": 4.748868778280543, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5809135571980544, "avg_score": null, "num_lines": null }
'''Arsenal API hypervisor_vm_assignments.''' # Copyright 2015 CityGrid Media, LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # import logging from datetime import datetime from pyramid.view import view_config from pyramid.response import Response from sqlalchemy.orm.exc import NoResultFound from arsenalweb.views import ( get_authenticated_user, ) from arsenalweb.models.common import ( DBSession, ) from arsenalweb.models.nodes import ( NodeAudit, ) from arsenalweb.views.api.common import ( api_200, api_404, api_500, ) LOG = logging.getLogger(__name__) def guest_vms_to_hypervisor(guest_vms, hypervisor, action, user_id): '''Manage guest vm assignment/deassignments to a hypervisor. Takes a list if Node objects and assigns/deassigns them to/from the hypervisor. guest_vms: a list of Node objects to assign as guests to a hypervisor. hypervisor: A Node object to assign the guest_vms to. action: A string defining whether to assign ('PUT') or de-assign ('DELETE') the guest vms to/from the hypervisor. user_id: A sting representing the user_id making this change. ''' resp = {hypervisor.name: []} try: for guest_vm in guest_vms: resp[hypervisor.name].append(guest_vm.unique_id) utcnow = datetime.utcnow() if action == 'PUT': LOG.debug('HVMS: {0}'.format(hypervisor.guest_vms)) if not guest_vm in hypervisor.guest_vms: hypervisor.guest_vms.append(guest_vm) audit = NodeAudit(object_id=hypervisor.id, field='guest_vm_id', old_value='assigned', new_value=guest_vm.id, updated_by=user_id, created=utcnow) DBSession.add(audit) if action == 'DELETE': try: hypervisor.guest_vms.remove(guest_vm) audit = NodeAudit(object_id=hypervisor.id, field='guest_vm_id', old_value=guest_vm.id, new_value='deassigned', updated_by=user_id, created=utcnow) DBSession.add(audit) except (ValueError, AttributeError): try: DBSession.remove(audit) except UnboundLocalError: pass DBSession.add(hypervisor) DBSession.flush() except (NoResultFound, AttributeError): return api_404(msg='hypervisor not found') except Exception as ex: msg = 'Error updating hypervisor: exception={0}'.format(ex) LOG.error(msg) return api_500(msg=msg) return api_200(results=resp) @view_config(route_name='api_hypervisor_vm_assignments', request_method='GET', request_param='schema=true', renderer='json') def api_hypervisor_vm_assignments_schema(request): '''Schema document for the hypervisor_vm_assignments API.''' hva = { } return hva @view_config(route_name='api_hypervisor_vm_assignments', permission='api_write', request_method='PUT', renderer='json') def api_hypervisor_vm_assignments_write(request): '''Process write requests for the /api/hypervisor_vm_assignments route.''' try: auth_user = get_authenticated_user(request) payload = request.json_body parent_node_id = int(payload['parent_node_id']) child_node_id = int(payload['child_node_id']) LOG.info('Checking for hypervisor_vm_assignment child_node_id={0}'.format(child_node_id)) try: hva = DBSession.query(HypervisorVmAssignment) hva = hva.filter(HypervisorVmAssignment.child_node_id == child_node_id) hva = hva.one() except NoResultFound: try: LOG.info('Creating new hypervisor_vm_assignment parent_node_id={0},' 'child_node_id={1}'.format(parent_node_id, child_node_id)) utcnow = datetime.utcnow() hva = HypervisorVmAssignment(parent_node_id=parent_node_id, child_node_id=child_node_id, updated_by=auth_user['user_id'], created=utcnow, updated=utcnow) DBSession.add(hva) DBSession.flush() except Exception as ex: LOG.error('Error creating new hypervisor_vm_assignment parent_node_id={0},' 'child_node_id={1},exception={2}'.format(parent_node_id, child_node_id, ex)) raise else: try: LOG.info('Updating hypervisor_vm_assignment parent_node_id={0},' 'child_node_id={1}'.format(parent_node_id, child_node_id)) hva.parent_node_id = parent_node_id hva.child_node_id = child_node_id hva.updated_by = auth_user['user_id'] DBSession.flush() except Exception as ex: LOG.error('Error updating hypervisor_vm_assignment' 'parent_node_id={0},child_node_id={1},' 'exception={2}'.format(parent_node_id, child_node_id, ex)) raise except Exception as ex: LOG.error('Error writing to hypervisor_vm_assignment API={0},' 'exception={1}'.format(request.url, ex)) return Response(json={'error': str(ex)}, content_type='application/json', status_int=500)
{ "repo_name": "CityGrid/arsenal", "path": "server/arsenalweb/views/api/hypervisor_vm_assignments.py", "copies": "1", "size": "6522", "license": "apache-2.0", "hash": 7282204172557788000, "line_mean": 39.2592592593, "line_max": 124, "alpha_frac": 0.5550444649, "autogenerated": false, "ratio": 4.356713426853707, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5411757891753707, "avg_score": null, "num_lines": null }
'''Arsenal API IpAddresses.''' # Copyright 2015 CityGrid Media, LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # import logging from datetime import datetime from pyramid.view import view_config from sqlalchemy.orm.exc import NoResultFound from sqlalchemy.orm.exc import MultipleResultsFound from arsenalweb.models.common import ( DBSession, ) from arsenalweb.models.ip_addresses import ( IpAddress, IpAddressAudit, ) from arsenalweb.models.network_interfaces import ( NetworkInterfaceAudit, ) from arsenalweb.views import ( get_authenticated_user, ) from arsenalweb.views.api.common import ( api_200, api_400, api_404, api_500, api_501, collect_params, ) LOG = logging.getLogger(__name__) # Functions def find_ip_addr_by_addr(ip_address): '''Find an ip_address by ip_address. Return an object if found, raises an exception otherwise.''' LOG.debug('Searching for ip_address.ip_address: ' '{0}'.format(ip_address)) ip_addr = DBSession.query(IpAddress) ip_addr = ip_addr.filter(IpAddress.ip_address == ip_address) return ip_addr.one() def find_ip_addr_by_id(ip_addr_id): '''Find a ip_address by id. Return an object if found, raises an exception otherwise.''' LOG.debug('Searching for ip_address.id: {0}'.format(ip_addr_id)) ip_addr = DBSession.query(IpAddress) ip_addr = ip_addr.filter(IpAddress.id == ip_addr_id) return ip_addr.one() def create_ip_addr(ip_address=None, updated_by=None): '''Create a new ip_address.''' try: LOG.info('Creating new ip_address: {0}'.format(ip_address)) utcnow = datetime.utcnow() ip_address = IpAddress(ip_address=ip_address, updated_by=updated_by, created=utcnow, updated=utcnow) DBSession.add(ip_address) DBSession.flush() ip_address_audit = IpAddressAudit(object_id=ip_address.id, field='ip_address', old_value='created', new_value=ip_address.ip_address, updated_by=updated_by, created=utcnow) DBSession.add(ip_address_audit) DBSession.flush() except Exception as ex: msg = 'Error creating ip_address: {0} exception: {2}'.format(ip_address, ex) LOG.error(msg) return api_500(msg=msg) return ip_address def update_ip_addr(ip_address=None, user_id=None): '''Update an ip_address. We are not allowing this for now, just a placeholder. If we decide to add feilds we want to allow in the future, copy the implementation from netowrk_interfaces.''' return None def ip_address_to_net_if(ip_address, net_if, user): '''Assign an ip_address to a network_interface. ip_address = An IpAddress object. net_if = A NetworkInterface object. user = A string representing the user_id making the change. ''' LOG.debug('START ip_address_to_net_if()') resp = {ip_address.ip_address: []} try: utcnow = datetime.utcnow() with DBSession.no_autoflush: resp[ip_address.ip_address].append(net_if.unique_id) orig_net_if_ip_addr_id = net_if.ip_address_id net_if.ip_address_id = ip_address.id if orig_net_if_ip_addr_id != ip_address.id: net_if_audit = NetworkInterfaceAudit(object_id=net_if.id, field='ip_address_id', old_value=orig_net_if_ip_addr_id, new_value=ip_address.id, updated_by=user, created=utcnow) DBSession.add(net_if_audit) LOG.debug('Creating audit entry for ip_address assignment ' 'to network_interface...') ip_addr_audit = IpAddressAudit(object_id=ip_address.id, field='net_if_assignment', old_value='created', new_value=net_if.id, updated_by=user, created=utcnow) DBSession.add(ip_addr_audit) DBSession.add(net_if) DBSession.flush() except (NoResultFound, AttributeError): return api_404(msg='ip_address not found') except MultipleResultsFound: msg = 'Bad request: network_interface_id is not unique: {0}'.format(net_if.id) return api_400(msg=msg) except Exception as ex: msg = 'Error updating ip_address: exception={0}'.format(ex) LOG.error(msg) return api_500(msg=msg) LOG.debug('RETURN assign_status()') return api_200(results=resp) @view_config(route_name='api_ip_addresses', request_method='GET', request_param='schema=true', renderer='json') def api_ip_addresses_schema(request): '''Schema document for the ip_addresses API.''' ip_addresses = { } return ip_addresses # TODO: Need to create the perms if we start allowing manual updates @view_config(route_name='api_ip_addresses', permission='ip_address_write', request_method='PUT', renderer='json') def api_ip_addreses_write(request): '''Process write requests for /api/ip_addreses route.''' try: req_params = [ 'ip_address', ] opt_params = [] params = collect_params(request, req_params, opt_params) params['unique_id'] = params['unique_id'].lower() try: ip_addr = find_ip_addr_by_addr(params['ip_address']) update_ip_addr(ip_addr, **params) except NoResultFound: net_if = create_ip_addr(**params) return net_if except Exception as ex: msg = 'Error writing to network_interfaces API={0},exception={1}'.format(request.url, ex) LOG.error(msg) return api_500(msg=msg) # TODO: Need to create the perms if we start allowing manual add/delete @view_config(route_name='api_ip_address_r', permission='ip_address_delete', request_method='DELETE', renderer='json') @view_config(route_name='api_ip_address_r', permission='ip_address_write', request_method='PUT', renderer='json') def api_ip_address_write_attrib(request): '''Process write requests for the /api/ip_address/{id}/{resource} route.''' LOG.debug('START api_ip_address_write_attrib()') resource = request.matchdict['resource'] payload = request.json_body auth_user = get_authenticated_user(request) LOG.debug('Updating {0}'.format(request.url)) # First get the network_interfaces, then figure out what to do to it. ip_addr = find_ip_addr_by_id(request.matchdict['id']) LOG.debug('ip_addr is: {0}'.format(ip_addr)) # List of resources allowed resources = [ 'undef', ] if resource in resources: try: actionable = payload[resource] if resource == 'undef': LOG.warn('Not allowed.') resp = [] except KeyError: msg = 'Missing required parameter: {0}'.format(resource) return api_400(msg=msg) except Exception as ex: LOG.error('Error updating ip_addresses: {0} ' 'exception: {1}'.format(request.url, ex)) return api_500(msg=str(ex)) else: return api_501() return resp
{ "repo_name": "CityGrid/arsenal", "path": "server/arsenalweb/views/api/ip_addresses.py", "copies": "1", "size": "8295", "license": "apache-2.0", "hash": 6378957677813578000, "line_mean": 34.1483050847, "line_max": 117, "alpha_frac": 0.5860156721, "autogenerated": false, "ratio": 3.953765490943756, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.0009348561504471829, "num_lines": 236 }
'''Arsenal API network_interfaces.''' # Copyright 2015 CityGrid Media, LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # import logging from datetime import datetime from pyramid.view import view_config from sqlalchemy.orm.exc import NoResultFound from arsenalweb.models.common import ( DBSession, ) from arsenalweb.models.ip_addresses import ( IpAddressAudit, ) from arsenalweb.models.nodes import ( NodeAudit, ) from arsenalweb.models.network_interfaces import ( NetworkInterface, NetworkInterfaceAudit, ) from arsenalweb.views import ( get_authenticated_user, ) from arsenalweb.views.api.common import ( api_200, api_400, api_404, api_500, api_501, collect_params, ) LOG = logging.getLogger(__name__) # Functions def find_net_if_by_unique_id(unique_id): '''Find a network_interface by unique_id. Return an object if found, raises an exception otherwise.''' unique_id = unique_id.lower() LOG.debug('Searching for network_interface.unique_id: ' '{0}'.format(unique_id)) net_if = DBSession.query(NetworkInterface) net_if = net_if.filter(NetworkInterface.unique_id == unique_id) return net_if.one() def find_net_if_by_id(net_if_id): '''Find a network_interface by id. Return an object if found, raises an exception otherwise.''' LOG.debug('Searching for network_interface.id: {0}'.format(net_if_id)) net_if = DBSession.query(NetworkInterface) net_if = net_if.filter(NetworkInterface.id == net_if_id) return net_if.one() def create_net_if(name=None, unique_id=None, updated_by=None, ip_address_id=None, bond_master=None, port_description=None, port_number=None, port_switch=None, port_vlan=None,): '''Create a new network_interface.''' try: # Convert everything that is defined to a string. my_attribs = locals().copy() for my_attr in my_attribs: if my_attribs.get(my_attr): my_attribs[my_attr] = str(my_attribs[my_attr]) # Guarantee unique_id is lowercase unique_id = unique_id.lower() # Guarantee ip_address_id is an int try: ip_address_id = int(ip_address_id) except TypeError: pass LOG.info('Creating new network_interface name: {0} unique_id: {1} ' 'ip_address_id: {2} updated_by: {3} bond_master: {4} port_description: ' '{5} port_number: {6} port_switch: {7} port_vlan: ' '{8}'.format(name, unique_id, ip_address_id, updated_by, bond_master, port_description, port_number, port_switch, port_vlan)) utcnow = datetime.utcnow() net_if = NetworkInterface(name=name, unique_id=unique_id, ip_address_id=ip_address_id, bond_master=bond_master, port_description=port_description, port_number=port_number, port_switch=port_switch, port_vlan=port_vlan, updated_by=updated_by, created=utcnow, updated=utcnow) DBSession.add(net_if) DBSession.flush() audit = NetworkInterfaceAudit(object_id=net_if.id, field='unique_id', old_value='created', new_value=net_if.unique_id, updated_by=updated_by, created=utcnow) DBSession.add(audit) if ip_address_id: LOG.debug('Creating audit entry for ip_address assignment ' 'to network_interface...') ip_addr_audit = IpAddressAudit(object_id=ip_address_id, field='net_if_assignment', old_value='created', new_value=net_if.id, updated_by=updated_by, created=utcnow) DBSession.add(ip_addr_audit) DBSession.flush() return net_if except Exception as ex: msg = 'Error creating new network_interface name: {0} unique_id: {1} ' \ 'ip_address_id: {2} updated_by: {3} bond_master: {4} port_description: ' \ '{5} port_number: {6} port_switch: {7} port_vlan: {8} ' \ 'exception: {9}'.format(name, unique_id, ip_address_id, updated_by, bond_master, port_description, port_number, port_switch, port_vlan, ex) LOG.error(msg) return api_500(msg=msg) def update_net_if(net_if, name=None, unique_id=None, updated_by=None, ip_address_id=None, bond_master=None, port_description=None, port_number=None, port_switch=None, port_vlan=None,): '''Update an existing network_interface.''' try: # Convert everything that is defined to a string. my_attribs = locals().copy() my_attribs.pop('net_if') for my_attr in my_attribs: if my_attribs.get(my_attr): my_attribs[my_attr] = str(my_attribs[my_attr]) # Guarantee unique_id is lowercase my_attribs['unique_id'] = my_attribs['unique_id'].lower() # Guarantee ip_address_id is an int try: my_attribs['ip_address_id'] = int(my_attribs['ip_address_id']) except TypeError: pass LOG.info('Updating network_interface.unique_id: ' '{0}'.format(my_attribs['unique_id'])) utcnow = datetime.utcnow() for attribute in my_attribs: if attribute == 'unique_id': LOG.debug('Skipping update to unique_id.') continue old_value = getattr(net_if, attribute) new_value = my_attribs[attribute] if old_value != new_value and new_value: if not old_value: old_value = 'None' LOG.debug('Updating network_interface: {0} attribute: ' '{1} new_value: {2}'.format(my_attribs['unique_id'], attribute, new_value)) net_if_audit = NetworkInterfaceAudit(object_id=net_if.id, field=attribute, old_value=old_value, new_value=new_value, updated_by=updated_by, created=utcnow) DBSession.add(net_if_audit) setattr(net_if, attribute, new_value) if attribute == 'ip_address_id': LOG.debug('Creating audit entry for ip_address assignment ' 'to network_interface...') ip_addr_audit = IpAddressAudit(object_id=my_attribs['ip_address_id'], field='net_if_assignment', old_value=old_value, new_value=new_value, updated_by=updated_by, created=utcnow) DBSession.add(ip_addr_audit) DBSession.flush() return net_if except Exception as ex: msg = 'Error updating network_interface name: {0} unique_id: {1} ' \ 'ip_address_id: {2} user: {3} bond_master: {4} port_description: ' \ '{5} port_number: {6} port_switch: {7} port_vlan: {8} ' \ 'exception: {9}'.format(name, my_attribs['unique_id'], ip_address_id, updated_by, bond_master, port_description, port_number, port_switch, port_vlan, ex) LOG.error(msg) raise def net_ifs_to_node(network_interfaces, node, action, user_id): '''Manage network_interface assignment/deassignments to a node. Takes a list if network_interface objects and assigns/deassigns them to/from the node. network_interfaces: a list of NetworkInterface objects to assign to a node. node: A Node object to assign the network_interfaces to. action: A string defining whether to assign ('PUT') or de-assign ('DELETE') the network interfaces to/from the node. user_id: A sting representing the user_id making this change. ''' resp = {node.name: []} try: for net_if in network_interfaces: resp[node.name].append(net_if.unique_id) utcnow = datetime.utcnow() if action == 'PUT': if not net_if in node.network_interfaces: node.network_interfaces.append(net_if) audit = NodeAudit(object_id=node.id, field='network_interface_id', old_value='assigned', new_value=net_if.id, updated_by=user_id, created=utcnow) DBSession.add(audit) if action == 'DELETE': try: node.network_interfaces.remove(net_if) audit = NodeAudit(object_id=node.id, field='network_interface_id', old_value=net_if.id, new_value='deassigned', updated_by=user_id, created=utcnow) DBSession.add(audit) except (ValueError, AttributeError): try: DBSession.remove(audit) except UnboundLocalError: pass DBSession.add(node) DBSession.flush() except (NoResultFound, AttributeError): return api_404(msg='node not found') except Exception as ex: msg = 'Error updating node: exception={0}'.format(ex) LOG.error(msg) return api_500(msg=msg) return api_200(results=resp) # Routes @view_config(route_name='api_network_interfaces', request_method='GET', request_param='schema=true', renderer='json') def api_node_groups_schema(request): '''Schema document for the network_interfaces API.''' network_interfaces = { } return network_interfaces # FIXME: Need to create the perms if we start allowing manual updates @view_config(route_name='api_network_interfaces', permission='network_interface_write', request_method='PUT', renderer='json') def api_network_interfaces_write(request): '''Process write requests for /api/network_interfaces route.''' try: req_params = [ 'name', 'unique_id', ] opt_params = [ 'ip_address', 'bond_master', 'port_description', 'port_number', 'port_switch', 'port_vlan', ] params = collect_params(request, req_params, opt_params) params['unique_id'] = params['unique_id'].lower() try: net_if = find_net_if_by_unique_id(params['unique_id']) update_net_if(net_if, **params) except NoResultFound: net_if = create_net_if(**params) return net_if except Exception as ex: msg = 'Error writing to network_interfaces API={0},exception={1}'.format(request.url, ex) LOG.error(msg) return api_500(msg=msg) # FIXME: Need to create the perms if we start allowing manual add/delete @view_config(route_name='api_network_interface_r', permission='network_interface_delete', request_method='DELETE', renderer='json') @view_config(route_name='api_network_interface_r', permission='network_interface_write', request_method='PUT', renderer='json') def api_network_interface_write_attrib(request): '''Process write requests for the /api/network_interfaces/{id}/{resource} route.''' resource = request.matchdict['resource'] payload = request.json_body auth_user = get_authenticated_user(request) LOG.debug('Updating {0}'.format(request.url)) # First get the network_interfaces, then figure out what to do to it. net_if = find_net_if_by_id(request.matchdict['id']) LOG.debug('net_if is: {0}'.format(net_if)) # List of resources allowed resources = [ 'undef', ] if resource in resources: try: actionable = payload[resource] if resource == 'undef': LOG.warn('Not allowed.') resp = [] except KeyError: msg = 'Missing required parameter: {0}'.format(resource) return api_400(msg=msg) except Exception as ex: LOG.error('Error updating network_interfaces: {0} ' 'exception: {1}'.format(request.url, ex)) return api_500(msg=str(ex)) else: return api_501() return resp
{ "repo_name": "CityGrid/arsenal", "path": "server/arsenalweb/views/api/network_interfaces.py", "copies": "1", "size": "15163", "license": "apache-2.0", "hash": 2533437066470021600, "line_mean": 37.4847715736, "line_max": 131, "alpha_frac": 0.4971311746, "autogenerated": false, "ratio": 4.52762018512989, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.0007706299387367842, "num_lines": 394 }
'''Arsenal API node_groups.''' # Copyright 2015 CityGrid Media, LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # import logging from datetime import datetime from pyramid.view import view_config from sqlalchemy.orm.exc import NoResultFound from sqlalchemy.orm.exc import MultipleResultsFound from arsenalweb.models.common import ( DBSession, ) from arsenalweb.models.nodes import ( NodeAudit, ) from arsenalweb.models.node_groups import ( NodeGroup, NodeGroupAudit, ) from arsenalweb.views import ( get_authenticated_user, ) from arsenalweb.views.api.common import ( api_200, api_400, api_404, api_500, api_501, ) from arsenalweb.views.api.nodes import ( find_node_by_id, ) LOG = logging.getLogger(__name__) # Functions def find_node_group_by_name(name): '''Find a node_group by name.''' node_group = DBSession.query(NodeGroup) node_group = node_group.filter(NodeGroup.name == name) return node_group.one() def find_node_group_by_id(node_group_id): '''Find a node_group by id.''' node_group = DBSession.query(NodeGroup) node_group = node_group.filter(NodeGroup.id == node_group_id) return node_group.one() def create_node_group(name, owner, description, notes_url, user): '''Create a new node_group.''' try: LOG.info('Creating new node_group name: {0} owner: {1} ' 'description: {2} notes_url: {3}'.format(name, owner, description, notes_url)) utcnow = datetime.utcnow() node_group = NodeGroup(name=name, owner=owner, description=description, notes_url=notes_url, updated_by=user, created=utcnow, updated=utcnow) DBSession.add(node_group) DBSession.flush() audit = NodeGroupAudit(object_id=node_group.id, field='name', old_value='created', new_value=node_group.name, updated_by=user, created=utcnow) DBSession.add(audit) DBSession.flush() return node_group except Exception as ex: msg = 'Error creating new node_group name: {0} owner: {1} ' \ 'description: {2} notes_url: {3} exception: {4}'.format(name, owner, description, notes_url, ex) LOG.error(msg) return api_500(msg=msg) def nodes_to_node_groups(node_group, nodes, action, auth_user): '''Manage node_group assignment/deassignments. Takes a list of node ids and assigns/deassigns them to/from the node group.''' resp = {node_group.name: []} try: for node_id in nodes: node = find_node_by_id(node_id) resp[node_group.name].append(node.name) utcnow = datetime.utcnow() if action == 'PUT': if not node in node_group.nodes: node_group.nodes.append(node) audit = NodeAudit(object_id=node.id, field='node_group_id', old_value='assigned', new_value=node_group.id, updated_by=auth_user['user_id'], created=utcnow) DBSession.add(audit) if action == 'DELETE': try: node_group.nodes.remove(node) audit = NodeAudit(object_id=node.id, field='node_group_id', old_value=node_group.id, new_value='deassigned', updated_by=auth_user['user_id'], created=utcnow) DBSession.add(audit) except (ValueError, AttributeError): try: DBSession.remove(audit) except UnboundLocalError: pass DBSession.add(node_group) DBSession.flush() except (NoResultFound, AttributeError): return api_404(msg='node not found') except MultipleResultsFound: msg = 'Bad request: node_id is not unique: {0}'.format(node_id) return api_400(msg=msg) except Exception as ex: msg = 'Error updating node: exception={0}'.format(ex) LOG.error(msg) return api_500(msg=msg) return resp # Routes @view_config(route_name='api_node_groups', request_method='GET', request_param='schema=true', renderer='json') def api_node_groups_schema(request): '''Schema document for the node_groups API.''' node_groups = { } return node_groups @view_config(route_name='api_node_groups', permission='node_group_write', request_method='PUT', renderer='json') def api_node_groups_write(request): '''Process write requests for /api/node_groups route.''' try: auth_user = get_authenticated_user(request) payload = request.json_body name = payload['name'].rstrip() owner = payload['owner'].rstrip() description = payload['description'].rstrip() try: notes_url = payload['notes_url'].rstrip() except: notes_url = None LOG.debug('Searching for node_group name={0}'.format(name)) try: node_group = find_node_group_by_name(name) try: LOG.info('Updating node_group name={0}'.format(name)) utcnow = datetime.utcnow() for attribute in ['name', 'owner', 'description', 'notes_url']: if getattr(node_group, attribute) != locals()[attribute]: LOG.debug('Updating node group {0}: {1}'.format(attribute, locals()[attribute])) old_value = getattr(node_group, attribute) if not old_value: old_value = 'None' node_group_audit = NodeGroupAudit(object_id=node_group.id, field=attribute, old_value=old_value, new_value=locals()[attribute], updated_by=auth_user['user_id'], created=utcnow) DBSession.add(node_group_audit) node_group.name = name node_group.owner = owner node_group.description = description node_group.notes_url = notes_url node_group.updated_by = auth_user['user_id'] DBSession.flush() except Exception as ex: msg = 'Error updating node_group name: {0} owner: {1} ' \ 'description: {2} notes_url: {3} exception: {4}'.format(name, owner, description, notes_url, ex) LOG.error(msg) return api_500(msg=msg) except NoResultFound: node_group = create_node_group(name, owner, description, notes_url, auth_user['user_id']) return api_200(results=node_group) except Exception as ex: msg = 'Error writing to node_groups API={0},exception={1}'.format(request.url, ex) LOG.error(msg) return api_500(msg=msg) @view_config(route_name='api_node_group_r', permission='node_group_delete', request_method='DELETE', renderer='json') @view_config(route_name='api_node_group_r', permission='node_group_write', request_method='PUT', renderer='json') def api_node_group_write_attrib(request): '''Process write requests for the /api/node_groups/{id}/{resource} route.''' resource = request.matchdict['resource'] payload = request.json_body auth_user = get_authenticated_user(request) LOG.debug('Updating {0}'.format(request.url)) # First get the node_group, then figure out what to do to it. node_group = find_node_group_by_id(request.matchdict['id']) LOG.debug('node_group is: {0}'.format(node_group)) # List of resources allowed resources = [ 'nodes', 'tags', ] if resource in resources: try: actionable = payload[resource] if resource == 'tags': resp = manage_tags(node_group, actionable, request.method) if resource == 'nodes': resp = nodes_to_node_groups(node_group, actionable, request.method, auth_user) except KeyError: msg = 'Missing required parameter: {0}'.format(resource) return api_400(msg=msg) except Exception as ex: LOG.error('Error updating node_groups={0},exception={1}'.format(request.url, ex)) return api_500(msg=str(ex)) else: return api_501() return api_200(results=resp)
{ "repo_name": "CityGrid/arsenal", "path": "server/arsenalweb/views/api/node_groups.py", "copies": "1", "size": "10846", "license": "apache-2.0", "hash": -4905445956066552000, "line_mean": 37.0561403509, "line_max": 117, "alpha_frac": 0.4905956113, "autogenerated": false, "ratio": 4.640992725716731, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5631588337016731, "avg_score": null, "num_lines": null }
'''Arsenal API Node Reports.''' # Copyright 2015 CityGrid Media, LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # import logging import re from pyramid.view import view_config from pyramid.response import Response from sqlalchemy.orm.exc import NoResultFound from arsenalweb.views.api.common import ( api_200, ) from arsenalweb.models.common import ( DBSession, ) from arsenalweb.models.hardware_profiles import ( HardwareProfile, ) from arsenalweb.models.nodes import ( Node, ) from arsenalweb.models.operating_systems import ( OperatingSystem, ) from arsenalweb.models.statuses import ( Status, ) LOG = logging.getLogger(__name__) def sanitize_input(input_string): '''Sanitize strings for use as graphite metrics.''' # FIXME: I'm sure this can be better a = re.compile('((?<=[a-z0-9])[A-Z]|(?!^)[A-Z](?=[a-z]))') convert = a.sub(r'\1', input_string).lower().strip() convert = ' '.join(convert.split()) convert = convert.replace(' ', '_') convert = convert.replace('-', '_') convert = convert.replace('.', '_') convert = convert.replace(',', '') convert = convert.replace('__', '_') convert = convert.replace('+', '_plus') convert = convert.replace('(', '') convert = convert.replace(')', '') return convert @view_config(route_name='api_reports_nodes', request_method='GET', renderer='json') def api_reports_node_read(request): '''Process read requests for the /api/reports/node route.''' node_metrics = {} try: LOG.debug('Generating metrics...') statuses = DBSession.query(Status) statuses = statuses.all() hw_profiles = DBSession.query(HardwareProfile) hw_profiles = hw_profiles.all() operating_systems = DBSession.query(OperatingSystem) operating_systems = operating_systems.all() node_metrics['status'] = {} for status in statuses: LOG.debug('Status id: {0}'.format(status.id)) node = DBSession.query(Node) node = node.filter(Node.status_id == status.id) node_count = node.count() node_metrics['status'][status.name] = node_count node_metrics['operating_system'] = {} for operating_system in operating_systems: LOG.debug('Operating System id: {0}'.format(operating_system.id)) node = DBSession.query(Node) node = node.filter(Node.operating_system_id == operating_system.id) node_count = node.count() os_name = sanitize_input('{0} {1}'.format(operating_system.variant, operating_system.version_number)) node_metrics['operating_system'][os_name] = node_count node_metrics['hardware_profile'] = {} for hw_profile in hw_profiles: LOG.debug('Hardware Profile id: {0}'.format(hw_profile.id)) node = DBSession.query(Node) node = node.filter(Node.hardware_profile_id == hw_profile.id) node_count = node.count() hw_profile_name = sanitize_input('{0} {1}'.format(hw_profile.manufacturer, hw_profile.model)) node_metrics['hardware_profile'][hw_profile_name] = node_count except NoResultFound: LOG.error('This should never happen') LOG.debug('Metrics: {0}'.format(node_metrics)) return api_200(results=node_metrics)
{ "repo_name": "CityGrid/arsenal", "path": "server/arsenalweb/views/api/reports/nodes.py", "copies": "1", "size": "3979", "license": "apache-2.0", "hash": -7662446073656668000, "line_mean": 33.3017241379, "line_max": 87, "alpha_frac": 0.6290525258, "autogenerated": false, "ratio": 3.9009803921568627, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5030032917956863, "avg_score": null, "num_lines": null }
'''Arsenal API nodes.''' # Copyright 2015 CityGrid Media, LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # import logging import json from datetime import datetime from pyramid.view import view_config from sqlalchemy.orm.exc import NoResultFound from sqlalchemy.orm.exc import MultipleResultsFound from arsenalweb.models.common import ( DBSession, ) from arsenalweb.models.nodes import ( Node, NodeAudit, ) from arsenalweb.models.node_groups import ( NodeGroup, ) from arsenalweb.views import ( get_authenticated_user, ) from arsenalweb.views.api.common import ( api_200, api_400, api_404, api_500, api_501, ) from arsenalweb.views.api.data_centers import ( find_data_center_by_name, create_data_center, ) from arsenalweb.views.api.hardware_profiles import ( get_hardware_profile, create_hardware_profile, ) from arsenalweb.views.api.ip_addresses import ( find_ip_addr_by_addr, create_ip_addr, update_ip_addr, ip_address_to_net_if, ) from arsenalweb.views.api.operating_systems import ( get_operating_system, create_operating_system, ) from arsenalweb.views.api.physical_devices import ( update_physical_device, ) from arsenalweb.views.api.ec2_instances import ( create_ec2_instance, find_ec2_instance_by_id, update_ec2_instance, ) from arsenalweb.views.api.network_interfaces import ( find_net_if_by_unique_id, create_net_if, update_net_if, net_ifs_to_node, ) from arsenalweb.views.api.hypervisor_vm_assignments import ( guest_vms_to_hypervisor, ) LOG = logging.getLogger(__name__) # Functions def find_node_by_name(node_name): '''Find a node by name.''' node = DBSession.query(Node) node = node.filter(Node.name == node_name) return node.one() def find_node_by_id(node_id): '''Find a node by id.''' LOG.debug('START find_node_by_id()') node = DBSession.query(Node) node = node.filter(Node.id == node_id) one_node = node.one() LOG.debug('RETURN find_node_by_id()') return one_node def find_node_by_unique_id(unique_id): '''Find a node by it's unique_id.''' LOG.debug('START find_node_by_unique_id()') LOG.debug('Searching for node unique_id={0}'.format(unique_id)) node = DBSession.query(Node) node = node.filter(Node.unique_id == unique_id) one_node = node.one() LOG.debug('RETURN find_node_by_unique_id()') return one_node def node_groups_to_nodes(node, node_groups, action, auth_user): '''Manage node group assignment/deassignments. Takes a list of node_group names and assigns/deassigns them to/from the node.''' resp = {node.name: []} try: for node_group_name in node_groups: LOG.debug('node_group_name: {0}'.format(node_group_name)) try: node_group = DBSession.query(NodeGroup) node_group = node_group.filter(NodeGroup.name == node_group_name) node_group = node_group.one() except Exception as ex: LOG.debug('Error querying DB: {0}'.format(ex)) raise resp[node.name].append(node_group.name) utcnow = datetime.utcnow() if action == 'PUT': node.node_groups.append(node_group) audit = NodeAudit(object_id=node.id, field='node_group_id', old_value='created', new_value=node_group.id, updated_by=auth_user['user_id'], created=utcnow) DBSession.add(audit) if action == 'DELETE': try: audit = NodeAudit(object_id=node.id, field='node_group_id', old_value=node_group.id, new_value='deleted', updated_by=auth_user['user_id'], created=utcnow) DBSession.add(audit) node.node_groups.remove(node_group) except (ValueError, AttributeError): DBSession.remove(audit) DBSession.add(node) DBSession.flush() except (NoResultFound, AttributeError): return api_404(msg='node_group not found') except MultipleResultsFound: msg = 'Bad request: node group is not unique: {0}'.format(node_group) return api_400(msg=msg) except Exception as ex: LOG.error('Error updating node_group: exception={0}'.format(ex)) return api_500() return api_200(results=resp) def process_network_interfaces(network_interfaces, user): '''Process all network interfaces of a node during register.''' try: net_if_list = [] LOG.debug('network interfaces: {0}'.format(json.dumps(network_interfaces, indent=2, sort_keys=True))) for interface in network_interfaces: LOG.debug('Working on interface: {0}'.format(interface)) ip_addr = None try: my_ip = interface['ip_address'] if my_ip: ip_addr = find_ip_addr_by_addr(my_ip) LOG.debug('IP Address found...') # There's nothing to update, if we ever do have something, it will go here. else: LOG.debug('This interface does not have an IP Address') except NoResultFound: LOG.debug('IP Address not found found, creating...') ip_addr = create_ip_addr(ip_address=my_ip, updated_by=user) # This interface doesn't have an IP key passed. except KeyError: pass try: net_if = find_net_if_by_unique_id(interface['unique_id']) LOG.debug('Interface found, updating...') if ip_addr: interface['ip_address_id'] = ip_addr.id try: # Remove this key if present, since update_net_if() doesn't # have an ip_address kwarg. del interface['ip_address'] except KeyError: pass updated_net_if = update_net_if(net_if, updated_by=user, **interface) net_if_list.append(updated_net_if) except NoResultFound: LOG.debug('Interface not found found, creating...') if ip_addr: interface['ip_address_id'] = ip_addr.id try: # Remove this key if present, since create_net_if() doesn't # have an ip_address kwarg. del interface['ip_address'] except KeyError: pass net_if = create_net_if(updated_by=user, **interface) net_if_list.append(net_if) return net_if_list except Exception as ex: LOG.error('Unable to determine network_interface! exception: {0}'.format(repr(ex))) raise def process_hardware_profile(payload, user): '''Find the hardware_profile or create if it doesn't exist. Returns hardware_profile_id''' try: name = payload['hardware_profile']['name'].rstrip() manufacturer = payload['hardware_profile']['manufacturer'].rstrip() model = payload['hardware_profile']['model'].rstrip() hardware_profile = get_hardware_profile(name) if not hardware_profile: hardware_profile = create_hardware_profile(name, manufacturer, model, user) LOG.debug('hardware_profile is: {0}'.format(hardware_profile.__dict__)) return hardware_profile.id except Exception as ex: LOG.error('Unable to determine hardware_profile manufacturer={0},model={1},' 'exception={2}'.format(manufacturer, model, ex)) raise def process_operating_system(payload, user): '''Find the operating_system or create if it doesn't exist. Returns operating_system_id.''' try: name = payload['operating_system']['name'].rstrip() variant = payload['operating_system']['variant'].rstrip() version_number = payload['operating_system']['version_number'].rstrip() architecture = payload['operating_system']['architecture'].rstrip() description = payload['operating_system']['description'].rstrip() operating_system = get_operating_system(name) if not operating_system: operating_system = create_operating_system(name, variant, version_number, architecture, description, user) LOG.debug('operating_system is: {0}'.format(operating_system.__dict__)) return operating_system.id except Exception as ex: LOG.error('Unable to determine operating_system name={0},variant={1},' 'version_number={2},architecture={3},description={4},' 'exception={5}'.format(name, variant, version_number, architecture, description, ex)) raise def process_ec2(payload, user): '''If present in the payload, Get the ec2_object or create if it doesn't exist. Returns ec2.id, or None if not present in the payload.''' try: ami_id = payload['ec2']['ami_id'].rstrip() hostname = payload['ec2']['hostname'].rstrip() instance_id = payload['ec2']['instance_id'].rstrip() instance_type = payload['ec2']['instance_type'].rstrip() availability_zone = payload['ec2']['availability_zone'].rstrip() profile = payload['ec2']['profile'].rstrip() reservation_id = payload['ec2']['reservation_id'].rstrip() security_groups = payload['ec2']['security_groups'].rstrip() ec2 = find_ec2_instance_by_id(instance_id) ec2 = update_ec2_instance(ec2, ami_id=ami_id, hostname=hostname, instance_id=instance_id, instance_type=instance_type, availability_zone=availability_zone, profile=profile, reservation_id=reservation_id, security_groups=security_groups, updated_by=user) except NoResultFound: ec2 = create_ec2_instance(ami_id=ami_id, hostname=hostname, instance_id=instance_id, instance_type=instance_type, availability_zone=availability_zone, profile=profile, reservation_id=reservation_id, security_groups=security_groups, updated_by=user) except (TypeError, KeyError, AttributeError): LOG.debug('ec2_instance data not present in payload.') return None except Exception as ex: LOG.error('Unable to determine ec2_instance! exception: {0}'.format(repr(ex))) raise LOG.debug('ec2_instance is: {0}'.format(ec2.__dict__)) return ec2.id def process_data_center(payload, user): '''Find the data_center or create if it doesn't exist. Returns data_center.id''' try: name = payload['data_center']['name'].rstrip() data_center = find_data_center_by_name(name) except NoResultFound: LOG.debug('data_center data not found, creating...') resp = create_data_center(name=name, updated_by=user) data_center = resp['results'][0] except (TypeError, KeyError): LOG.debug('data_center data not present in payload.') return None except Exception as ex: LOG.error('Unable to determine datacenter name: {0} ' 'exception: {1}'.format(name, repr(ex))) raise LOG.debug('data_center is: {0}'.format(data_center.__dict__)) return data_center.id def manage_guest_vm_assignments(guest_vms, hypervisor, user_id): '''Manage the assigning and deassinging of guests during a node registration.''' all_guests = [] for gvm in guest_vms: try: LOG.debug('Attempting to assign vm: {0}'.format(gvm['name'])) all_guests.append(find_node_by_unique_id(gvm['unique_id'])) except NoResultFound: LOG.debug('vm not found: {0}'.format(gvm['name'])) LOG.debug('ALL GUESTS: {0}'.format(all_guests)) guest_vms_to_hypervisor(all_guests, hypervisor, 'PUT', user_id) # Deassign guest_vms the node no longer has. deassign_guest_vms = [x for x in hypervisor.guest_vms if x not in all_guests] LOG.debug('DEASSIGN GUESTS: {0}'.format(deassign_guest_vms)) guest_vms_to_hypervisor(deassign_guest_vms, hypervisor, 'DELETE', user_id) def create_node(**kwargs): '''Create a new node.''' user_id = kwargs['user_id'] unique_id = kwargs['unique_id'] name = kwargs['name'] hardware_profile_id = kwargs['hardware_profile_id'] operating_system_id = kwargs['operating_system_id'] data_center_id = kwargs['data_center_id'] ec2_id = kwargs['ec2_id'] serial_number = kwargs['serial_number'] processor_count = kwargs['processor_count'] uptime = kwargs['uptime'] user_id = kwargs['user_id'] net_if_list = kwargs['net_if_list'] try: LOG.info('Creating new node name: {0} unique_id: {1}'.format(name, unique_id)) utcnow = datetime.utcnow() node = Node(unique_id=unique_id, name=name, hardware_profile_id=hardware_profile_id, operating_system_id=operating_system_id, data_center_id=data_center_id, status_id=2, ec2_id=ec2_id, serial_number=serial_number, processor_count=processor_count, uptime=uptime, updated_by=user_id, last_registered=utcnow, created=utcnow, updated=utcnow) DBSession.add(node) DBSession.flush() audit = NodeAudit(object_id=node.id, field='unique_id', old_value='created', new_value=node.unique_id, updated_by=user_id, created=utcnow) DBSession.add(audit) DBSession.flush() net_ifs_to_node(net_if_list, node, 'PUT', user_id) except Exception as ex: LOG.error('Error creating new node name: {0} unique_id: {1} ' 'exception: {2}'.format(name, unique_id, repr(ex))) raise return node def update_node(node, **kwargs): '''Update an existing node.''' user_id = kwargs['user_id'] unique_id = kwargs['unique_id'] name = kwargs['name'] hardware_profile_id = kwargs['hardware_profile_id'] operating_system_id = kwargs['operating_system_id'] data_center_id = kwargs['data_center_id'] ec2_id = kwargs['ec2_id'] serial_number = kwargs['serial_number'] processor_count = kwargs['processor_count'] uptime = kwargs['uptime'] user_id = kwargs['user_id'] net_if_list = kwargs['net_if_list'] try: LOG.info('Updating node: {0}'.format(unique_id)) utcnow = datetime.utcnow() for attribute in ['name', 'hardware_profile_id', 'operating_system_id', 'data_center_id', 'ec2_id', 'serial_number', 'processor_count', 'uptime']: if getattr(node, attribute) != locals()[attribute]: LOG.debug('Updating node {0}: {1}'.format(attribute, locals()[attribute])) # We don't want audit entries for uptime if attribute != 'uptime': # This will not set 'None' to a string. old_value = getattr(node, attribute, 'None') if not old_value: old_value = 'None' audit = NodeAudit(object_id=node.id, field=attribute, old_value=old_value, new_value=locals()[attribute], updated_by=user_id, created=utcnow) DBSession.add(audit) node.name = name node.hardware_profile_id = hardware_profile_id node.operating_system_id = operating_system_id node.data_center_id = data_center_id node.ec2_id = ec2_id node.serial_number = serial_number node.processor_count = processor_count node.uptime = uptime node.updated_by = user_id node.last_registered = utcnow net_ifs_to_node(net_if_list, node, 'PUT', user_id) # Deassign network_interfaces the node no longer has. deassign_net_ifs = [x for x in node.network_interfaces if x not in net_if_list] net_ifs_to_node(deassign_net_ifs, node, 'DELETE', user_id) # Manage guest_vm assignemnts try: manage_guest_vm_assignments(kwargs['guest_vms'], node, user_id) except KeyError: pass try: current_hwp = node.physical_device.hardware_profile.id if current_hwp != hardware_profile_id: LOG.debug('Updating physical_device.hardware_profile_id from: ' '{0} to: {1}'.format(current_hwp, hardware_profile_id)) update_physical_device(node.physical_device, hardware_profile_id=hardware_profile_id, updated_by=user_id) else: LOG.debug('physical_device.hardware_profile_id matches what ' 'is being reported by node registration.') except AttributeError: LOG.debug('No physical_device for node, not checking ' 'physical_device.hardware_profile_id for update.') DBSession.flush() except Exception as ex: LOG.error('Error updating node name: {0} unique_id: {1} ' 'exception: {2}'.format(name, unique_id, repr(ex))) raise return node def process_registration_payload(payload, user_id): '''Process the payload of a node registration and return a dictionary for updating or creating a node.''' LOG.debug('Processing registration payload...') try: processed = {} processed['user_id'] = user_id processed['unique_id'] = payload['unique_id'].lower().rstrip() processed['name'] = payload['name'].rstrip() processed['serial_number'] = payload['serial_number'].rstrip() processed['processor_count'] = int(payload['processor_count']) processed['uptime'] = payload['uptime'].rstrip() processed['hardware_profile_id'] = process_hardware_profile(payload, user_id) processed['operating_system_id'] = process_operating_system(payload, user_id) processed['data_center_id'] = process_data_center(payload, user_id) processed['ec2_id'] = process_ec2(payload, user_id) except KeyError as ex: LOG.error('Required data missing from playload: {0}'.format(repr(ex))) raise except (TypeError, ValueError) as ex: LOG.error('Incorrect data type for payload item: {0}'.format(repr(ex))) raise except Exception as ex: LOG.error('Unhandled data problem for payload item: {0}'.format(repr(ex))) raise try: processed['guest_vms'] = payload['guest_vms'] except KeyError: pass # Every host should have at least one IP address and network interface. processed['net_if_list'] = process_network_interfaces(payload['network_interfaces'], user_id) return processed @view_config(route_name='api_nodes', request_method='GET', request_param='schema=true', renderer='json') def api_node_schema(request): '''Schema document for nodes API''' LOG.debug('schema requested') node = { } return node @view_config(route_name='api_node_r', permission='node_delete', request_method='DELETE', renderer='json') @view_config(route_name='api_node_r', permission='node_write', request_method='PUT', renderer='json') def api_node_write_attrib(request): '''Process write requests for the /api/nodes/{id}/{resource} route.''' try: resource = request.matchdict['resource'] payload = request.json_body auth_user = get_authenticated_user(request) LOG.debug('Updating {0}'.format(request.url)) LOG.debug('resource type: {0}'.format(resource)) # First get the node, then figure out what to do to it. node = find_node_by_id(request.matchdict['id']) LOG.debug('node is: {0}'.format(node)) # List of resources allowed resources = [ 'node_groups', ] if resource in resources: try: actionable = payload[resource] if resource == 'node_groups': resp = node_groups_to_nodes(node, actionable, request.method, auth_user) except KeyError: msg = 'Missing required parameter: {0}'.format(resource) return api_400(msg=msg) except Exception as ex: LOG.error('Error updating nodes: {0} exception: {1}'.format(request.url, ex)) return api_500(msg=str(ex)) else: return api_501() return resp except Exception as ex: LOG.error('Error updating nodes: {0} exception: {1}'.format(request.url, ex)) return api_500(msg=str(ex)) @view_config(route_name='api_node', permission='node_write', request_method='PUT', renderer='json') def api_node_write_id(request): '''Process write requests for the /api/nodes/{id} route.''' try: auth_user = get_authenticated_user(request) node_id = request.matchdict['id'] payload = request.json_body params = '' for key, val in payload.items(): params += '{0}={1},'.format(key, val) LOG.info('Updating node_id: {0} params: {1}'.format(node_id, params.rstrip(','))) node = DBSession.query(Node) node = node.filter(Node.id == node_id) node = node.one() # FIXME: Do we want to limit anything here? Keys that don't exist will # be ignored, keys that can't be set with throw an error. Doesn't # feel right though to just accept what's put to the endpoint. for key, val in payload.items(): try: setattr(node, key, val.rstrip()) except AttributeError: setattr(node, key, int(val)) node.updated_by = auth_user['user_id'] DBSession.flush() except Exception as ex: LOG.error('Error writing to nodes API={0},exception={1}'.format(request.url, ex)) return api_500(msg=str(ex)) return node @view_config(route_name='api_register', permission='api_register', request_method='PUT', renderer='json') def api_node_register(request): '''Process registration requests for the /api/register route.''' try: LOG.info('Registering node') auth_user = get_authenticated_user(request) payload = request.json_body processed = process_registration_payload(payload, auth_user['user_id']) try: existing_node = find_node_by_unique_id(processed['unique_id']) node = update_node(existing_node, **processed) except NoResultFound: node = create_node(**processed) return api_200(results=node) except Exception as ex: msg = 'Error registering new node: {0} API: {1} exception: ' \ '{2}'.format(processed['name'], request.url, repr(ex)) LOG.error(msg) return api_500(msg=msg) @view_config(route_name='api_nodes', permission='node_write', request_method='PUT', renderer='json') def api_node_write(request): '''Process write requests for the /api/nodes route.''' try: auth_user = get_authenticated_user(request) payload = request.json_body # Manually created node via the client. try: node_name = payload['name'].rstrip() unique_id = payload['unique_id'].lower().rstrip() status_id = int(payload['status_id']) operating_system_id = int(payload['operating_system']['id']) hardware_profile_id = int(payload['hardware_profile']['id']) LOG.debug('Searching for node unique_id={0}'.format(unique_id)) node = DBSession.query(Node) node = node.filter(Node.unique_id == unique_id) node = node.one() LOG.info('Updating node name={0},unique_id={1}'.format(node_name, unique_id)) utcnow = datetime.utcnow() # FIXME: This should iterate over all updateable params, not be # hardcoded to name and status_id. if node.name != node_name: audit = NodeAudit(object_id=node.id, field='node_name', old_value=node.name, new_value=node_name, updated_by=auth_user['user_id'], created=utcnow) DBSession.add(audit) node.name = node_name if node.status_id != status_id: audit_status = NodeAudit(object_id=node.id, field='status_id', old_value=node.status_id, new_value=status_id, updated_by=auth_user['user_id'], created=utcnow) DBSession.add(audit_status) node.status_id = status_id node.updated_by = auth_user['user_id'] DBSession.flush() except NoResultFound: try: LOG.info('Manually creating new node name={0},unique_id={1}'.format(node_name, unique_id)) utcnow = datetime.utcnow() node = Node(name=node_name, unique_id=unique_id, status_id=status_id, operating_system_id=operating_system_id, hardware_profile_id=hardware_profile_id, updated_by=auth_user['user_id'], last_registered=utcnow, created=utcnow, updated=utcnow) DBSession.add(node) DBSession.flush() audit = NodeAudit(object_id=node.id, field='unique_id', old_value='created', new_value=node.unique_id, updated_by=auth_user['user_id'], created=utcnow) DBSession.add(audit) DBSession.flush() except Exception as ex: LOG.error('Error creating new node name={0}unique_id={1},status_id={2},' 'exception={3}'.format(node_name, unique_id, status_id, ex)) raise return api_200(results=node) except Exception as ex: LOG.error('Error writing to nodes ' 'API={0},exception={1}'.format(request.url, ex)) return api_500(msg=str(ex))
{ "repo_name": "CityGrid/arsenal", "path": "server/arsenalweb/views/api/nodes.py", "copies": "1", "size": "29928", "license": "apache-2.0", "hash": -8074374314148506000, "line_mean": 37.7166882277, "line_max": 105, "alpha_frac": 0.5367882919, "autogenerated": false, "ratio": 4.314878892733564, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5351667184633564, "avg_score": null, "num_lines": null }
'''Arsenal API OperatingSystems.''' # Copyright 2015 CityGrid Media, LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # import logging from datetime import datetime from pyramid.view import view_config from pyramid.response import Response from sqlalchemy.orm.exc import NoResultFound from arsenalweb.views import ( get_authenticated_user, ) from arsenalweb.views.api.common import ( api_500, ) from arsenalweb.models.common import ( DBSession, ) from arsenalweb.models.operating_systems import ( OperatingSystem, OperatingSystemAudit, ) LOG = logging.getLogger(__name__) # Common functions def get_operating_system(name): '''Get an operating_system from the database.''' try: query = DBSession.query(OperatingSystem) query = query.filter(OperatingSystem.name == name) operating_system = query.one() return operating_system except (NoResultFound, AttributeError): LOG.debug('operating_system not found name={0}'.format(name)) return None def create_operating_system(name, variant, version_number, architecture, description, user_id): '''Create a new operating_system.''' try: LOG.info('Creating new operating_system name={0},variant={1},version_number={2},' 'architecture={3},description={4}'.format(name, variant, version_number, architecture, description)) utcnow = datetime.utcnow() operating_system = OperatingSystem(name=name, variant=variant, version_number=version_number, architecture=architecture, description=description, updated_by=user_id, created=utcnow, updated=utcnow) DBSession.add(operating_system) DBSession.flush() audit = OperatingSystemAudit(object_id=operating_system.id, field='name', old_value='created', new_value=operating_system.name, updated_by=user_id, created=utcnow) DBSession.add(audit) DBSession.flush() return operating_system except Exception as ex: msg = 'Error creating new operating_system name={0},variant={1},version_number={2},' \ 'architecture={3},description={4},exception={5}'.format(name, variant, version_number, architecture, description, ex) LOG.error(msg) return api_500(msg=msg) def update_operating_system(operating_system, name, variant, version_number, architecture, description, user_id): '''Update an existing operating_system.''' try: LOG.info('Updating operating_system name={0},variant={1},version_number={2},' 'architecture={3},description={4}'.format(name, variant, version_number, architecture, description)) utcnow = datetime.utcnow() for attribute in ['name', 'variant', 'version_number', 'architecture', 'description']: if getattr(operating_system, attribute) != locals()[attribute]: LOG.debug('Updating operating system {0}: {1}'.format(attribute, locals()[attribute])) audit = OperatingSystemAudit(object_id=operating_system.id, field=attribute, old_value=getattr(operating_system, attribute), new_value=locals()[attribute], updated_by=user_id, created=utcnow) DBSession.add(audit) operating_system.name = name operating_system.variant = variant operating_system.version_number = version_number operating_system.architecture = architecture operating_system.description = description operating_system.updated_by = user_id DBSession.flush() return operating_system except Exception as ex: msg = 'Error updating operating_system name={0},variant={1},version_number={2},' \ 'architecture={3},description={4},exception={5}'.format(name, variant, version_number, architecture, description, ex) LOG.error(msg) return api_500(msg=msg) @view_config(route_name='api_operating_systems', request_method='GET', request_param='schema=true', renderer='json') def api_operating_systems_schema(request): '''Schema document for the operating_systems API.''' operating_system = { } return operating_system @view_config(route_name='api_operating_systems', permission='api_write', request_method='PUT', renderer='json') def api_operating_system_write(request): '''Process write requests for /api/operating_systems route.''' try: auth_user = get_authenticated_user(request) payload = request.json_body name = payload['name'].rstrip() variant = payload['variant'].rstrip() version_number = payload['version_number'].rstrip() architecture = payload['architecture'].rstrip() description = payload['description'].rstrip() operating_system = get_operating_system(name) if not operating_system: operating_system = create_operating_system(name, variant, version_number, architecture, description, auth_user['user_id']) else: operating_system = update_operating_system(operating_system, name, variant, version_number, architecture, description, auth_user['user_id']) return operating_system except Exception as ex: msg = 'Error writing to operating_systems API={0},' \ 'exception={1}'.format(request.url, ex) LOG.error(msg) return api_500(msg=msg)
{ "repo_name": "CityGrid/arsenal", "path": "server/arsenalweb/views/api/operating_systems.py", "copies": "1", "size": "8680", "license": "apache-2.0", "hash": 8603424127052589000, "line_mean": 41.7586206897, "line_max": 116, "alpha_frac": 0.4620967742, "autogenerated": false, "ratio": 5.794392523364486, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.6756489297564487, "avg_score": null, "num_lines": null }
'''Arsenal API physical_devices.''' # Copyright 2015 CityGrid Media, LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # import logging from datetime import datetime from pyramid.view import view_config from sqlalchemy.orm.exc import NoResultFound from sqlalchemy.exc import IntegrityError from arsenalweb.views import ( get_authenticated_user, ) from arsenalweb.views.api.common import ( api_200, api_400, api_404, api_500, api_501, collect_params, ) from arsenalweb.views.api.hardware_profiles import ( get_hardware_profile, ) from arsenalweb.views.api.physical_locations import ( find_physical_location_by_name, ) from arsenalweb.views.api.physical_racks import ( find_physical_rack_by_name_loc, ) from arsenalweb.views.api.physical_elevations import ( find_physical_elevation_by_elevation, ) from arsenalweb.models.common import ( DBSession, ) from arsenalweb.models.physical_devices import ( PhysicalDevice, PhysicalDeviceAudit, ) LOG = logging.getLogger(__name__) # Functions def find_physical_device_by_serial(serial_number): '''Find a physical_device by serial_number. Returns a physical_device object if found, raises NoResultFound otherwise.''' LOG.debug('Searching for physical_device by serial_number: {0}'.format(serial_number)) physical_device = DBSession.query(PhysicalDevice) physical_device = physical_device.filter(PhysicalDevice.serial_number == serial_number) return physical_device.one() def find_physical_device_by_id(physical_device_id): '''Find a physical_device by id.''' LOG.debug('Searching for physical_device by id: {0}'.format(physical_device_id)) physical_device = DBSession.query(PhysicalDevice) physical_device = physical_device.filter(PhysicalDevice.id == physical_device_id) return physical_device.one() def create_physical_device(serial_number=None, mac_address_1=None, physical_location_id=None, physical_rack_id=None, physical_elevation_id=None, updated_by=None, **kwargs): '''Create a new physical_device. Required params: hardware_profile_id: An integer representing the hardware_profile_id from the hardware_profiles table. mac_address_1: A string representing the MAC address of the first interface. physical_location_id : An integer representing the physical_location_id from the physical_locations table. physical_rack_id : An integer representing the physical_rack_id from the physical_racks table. physical_elevation_id: An integer representing the physical_elevation_id from the physical_elevations table. serial_number : A string that is the serial_number of the physical_device. updated_by : A string that is the user making the update. Optional kwargs: mac_address_2: A string representing the MAC address of the second interface. oob_ip_address: A string representing the out of band IP address. oob_mac_address: A string representing the out of band MAC address. ''' try: LOG.info('Creating new physical_device serial_number: {0}'.format(serial_number)) utcnow = datetime.utcnow() physical_device = PhysicalDevice(serial_number=serial_number, mac_address_1=mac_address_1, physical_location_id=physical_location_id, physical_rack_id=physical_rack_id, physical_elevation_id=physical_elevation_id, updated_by=updated_by, created=utcnow, updated=utcnow, **kwargs) DBSession.add(physical_device) DBSession.flush() audit = PhysicalDeviceAudit(object_id=physical_device.id, field='serial_number', old_value='created', new_value=physical_device.serial_number, updated_by=updated_by, created=utcnow) DBSession.add(audit) DBSession.flush() return api_200(results=physical_device) except IntegrityError: msg = 'Physical elevation is already occupied, move the existing ' \ 'physical_device first.' LOG.error(msg) raise Exception(msg) except Exception as ex: msg = 'Error creating new physical_device serial_number: {0} exception: ' \ '{1}'.format(serial_number, ex) LOG.error(msg) return api_500(msg=msg) def update_physical_device(physical_device, **kwargs): '''Update an existing physical_device. Required params: physical_device : A physical_device object. updated_by : A string that is the user making the update. Optional kwargs: hardware_profile_id: An integer representing the hardware_profile_id from the hardware_profiles table. mac_address_1: A string representing the MAC address of the first interface. mac_address_2: A string representing the MAC address of the second interface. oob_ip_address: A string representing the out of band IP address. oob_mac_address: A string representing the out of band MAC address. physical_location_id : An integer representing the physical_location_id from the physical_locations table. physical_rack_id : An integer representing the physical_rack_id from the physical_racks table. physical_elevation_id: An integer representing the physical_elevation_id from the physical_elevations table. ''' try: my_attribs = kwargs.copy() LOG.info('Updating physical_device: {0}'.format(physical_device.serial_number)) utcnow = datetime.utcnow() for attribute in my_attribs: if attribute == 'serial_number': LOG.debug('Skipping update to physical_device.serial_number') continue old_value = getattr(physical_device, attribute) new_value = my_attribs[attribute] if old_value != new_value and new_value: if not old_value: old_value = 'None' LOG.debug('Updating physical_device: {0} attribute: ' '{1} new_value: {2}'.format(physical_device.serial_number, attribute, new_value)) audit = PhysicalDeviceAudit(object_id=physical_device.id, field=attribute, old_value=old_value, new_value=new_value, updated_by=my_attribs['updated_by'], created=utcnow) DBSession.add(audit) setattr(physical_device, attribute, new_value) DBSession.flush() return api_200(results=physical_device) except IntegrityError: msg = 'Physical elevation is already occupied, move the existing ' \ 'physical_device first.' LOG.error(msg) raise Exception(msg) except Exception as ex: msg = 'Error updating physical_device serial_number: {0} updated_by: {1} exception: ' \ '{2}'.format(physical_device.serial_number, my_attribs['updated_by'], repr(ex)) LOG.error(msg) raise def convert_names_to_ids(params): '''Converts nice names to ids for creating/updating a physical_device.''' try: try: try: physical_location = params['physical_location']['name'] except TypeError: physical_location = params['physical_location'] physical_location = find_physical_location_by_name(physical_location) params['physical_location_id'] = physical_location.id LOG.debug('physical_location_id: {0}'.format(params['physical_location_id'])) del params['physical_location'] except NoResultFound: msg = 'physical_location not found: {0}'.format(params['physical_location']) LOG.error(msg) raise NoResultFound(msg) try: try: physical_rack_name = params['physical_rack']['name'] except TypeError: physical_rack_name = params['physical_rack'] physical_rack = find_physical_rack_by_name_loc(physical_rack_name, params['physical_location_id']) params['physical_rack_id'] = physical_rack.id del params['physical_rack'] except NoResultFound: msg = 'physical_rack not found: {0}'.format(params['physical_rack']) LOG.error(msg) raise NoResultFound(msg) try: try: physical_elevation_el = params['physical_elevation']['elevation'] except TypeError: physical_elevation_el = params['physical_elevation'] physical_elevation = find_physical_elevation_by_elevation(physical_elevation_el, params['physical_rack_id']) params['physical_elevation_id'] = physical_elevation.id del params['physical_elevation'] except NoResultFound: msg = 'physical_elevation not found: {0}'.format(params['physical_elevation']) LOG.error(msg) raise NoResultFound(msg) if params['hardware_profile']: try: hw_profile_name = params['hardware_profile']['name'] except TypeError: hw_profile_name = params['hardware_profile'] try: hardware_profile = get_hardware_profile(hw_profile_name) params['hardware_profile_id'] = hardware_profile.id del params['hardware_profile'] except AttributeError: msg = 'hardware_profile not found: {0}'.format(params['hardware_profile']) LOG.error(msg) raise NoResultFound(msg) except Exception as ex: LOG.error(repr(ex)) raise return params # Routes @view_config(route_name='api_physical_devices', request_method='GET', request_param='schema=true', renderer='json') def api_physical_devices_schema(request): '''Schema document for the physical_devices API.''' physical_devices = { } return physical_devices @view_config(route_name='api_physical_devices', permission='physical_device_write', request_method='PUT', renderer='json') def api_physical_devices_write(request): '''Process write requests for /api/physical_devices route.''' try: req_params = [ 'hardware_profile', 'mac_address_1', 'physical_elevation', 'physical_location', 'physical_rack', 'serial_number', ] opt_params = [ 'mac_address_2', 'oob_ip_address', 'oob_mac_address', ] params = collect_params(request, req_params, opt_params) try: params = convert_names_to_ids(params) except NoResultFound as ex: msg = 'Error writing to physical_devices API: {0}'.format(ex) LOG.error(msg) return api_404(msg=msg) try: physical_device = find_physical_device_by_serial(params['serial_number']) physical_device = update_physical_device(physical_device, **params) except NoResultFound: physical_device = create_physical_device(**params) return physical_device except Exception as ex: msg = 'Error writing to physical_devices API: {0} exception: {1}'.format(request.url, ex) LOG.error(msg) return api_500(msg=msg) @view_config(route_name='api_physical_device_r', permission='physical_device_delete', request_method='DELETE', renderer='json') @view_config(route_name='api_physical_device_r', permission='physical_device_write', request_method='PUT', renderer='json') def api_physical_device_write_attrib(request): '''Process write requests for the /api/physical_devices/{id}/{resource} route.''' resource = request.matchdict['resource'] payload = request.json_body auth_user = get_authenticated_user(request) LOG.debug('Updating {0}'.format(request.url)) # First get the physical_device, then figure out what to do to it. physical_device = find_physical_device_by_id(request.matchdict['id']) LOG.debug('physical_device is: {0}'.format(physical_device)) # List of resources allowed resources = [ 'nothing_yet', ] # There's nothing to do here yet. Maye add updates to existing # physical_devices? if resource in resources: try: actionable = payload[resource] except KeyError: msg = 'Missing required parameter: {0}'.format(resource) return api_400(msg=msg) except Exception as ex: LOG.error('Error updating physical_devices: {0} exception: {1}'.format(request.url, ex)) return api_500(msg=str(ex)) else: return api_501() return resp
{ "repo_name": "CityGrid/arsenal", "path": "server/arsenalweb/views/api/physical_devices.py", "copies": "1", "size": "14318", "license": "apache-2.0", "hash": -2471233858432600000, "line_mean": 38.1202185792, "line_max": 127, "alpha_frac": 0.5998742841, "autogenerated": false, "ratio": 4.4341901517497675, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5534064435849767, "avg_score": null, "num_lines": null }
'''Arsenal API physical_elevations.''' # Copyright 2015 CityGrid Media, LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # import logging from datetime import datetime from pyramid.view import view_config from sqlalchemy.orm.exc import NoResultFound from arsenalweb.views import ( get_authenticated_user, ) from arsenalweb.views.api.common import ( api_200, api_400, api_500, api_501, collect_params, ) from arsenalweb.views.api.physical_racks import ( find_physical_rack_by_name_loc, ) from arsenalweb.views.api.physical_locations import ( find_physical_location_by_name, ) from arsenalweb.models.common import ( DBSession, ) from arsenalweb.models.physical_elevations import ( PhysicalElevation, PhysicalElevationAudit, ) LOG = logging.getLogger(__name__) # Functions def find_physical_elevation_by_elevation(elevation, physical_rack_id): '''Find a physical_elevation by elevation and physical_rack_id. Returns a physical_elevation object if found, raises NoResultFound otherwise.''' LOG.debug('Searching for physical_elevation by elevation: {0} ' 'physical_rack_id: {1}'.format(elevation, physical_rack_id)) physical_elevation = DBSession.query(PhysicalElevation) physical_elevation = physical_elevation.filter(PhysicalElevation.elevation == elevation) physical_elevation = physical_elevation.filter(PhysicalElevation.physical_rack_id == physical_rack_id) return physical_elevation.one() def find_physical_elevation_by_id(physical_elevation_id): '''Find a physical_elevation by id.''' LOG.debug('Searching for physical_elevation by id: {0}'.format(physical_elevation_id)) physical_elevation = DBSession.query(PhysicalElevation) physical_elevation = physical_elevation.filter(PhysicalElevation.id == physical_elevation_id) return physical_elevation.one() def create_physical_elevation(elevation=None, physical_rack_id=None, updated_by=None, **kwargs): '''Create a new physical_elevation. Required params: elevation : A string that is the elevation of the rack. physical_rack_id: An integer that represents the id of the physical_rack the elevation resides in. updated_by: A string that is the user making the update. Optional kwargs: None yet. ''' try: LOG.info('Creating new physical_elevation name: {0} physical_rack_id: ' '{1}'.format(elevation, physical_rack_id)) utcnow = datetime.utcnow() physical_elevation = PhysicalElevation(elevation=elevation, physical_rack_id=physical_rack_id, updated_by=updated_by, created=utcnow, updated=utcnow, **kwargs) DBSession.add(physical_elevation) DBSession.flush() audit = PhysicalElevationAudit(object_id=physical_elevation.id, field='elevation', old_value='created', new_value=physical_elevation.elevation, updated_by=updated_by, created=utcnow) DBSession.add(audit) DBSession.flush() return api_200(results=physical_elevation) except Exception as ex: msg = 'Error creating new physical_elevation elevation: {0} exception: ' \ '{1}'.format(elevation, ex) LOG.error(msg) return api_500(msg=msg) def update_physical_elevation(physical_elevation, **kwargs): '''Update an existing physical_elevation. Required params: physical_elevation : A physical_elevation object. updated_by : A string that is the user making the update. Optional kwargs: physical_rack_id: An integer that represents the id of the physical_rack the elevation resides in. ''' try: LOG.info('Updating physical_elevation: {0}'.format(physical_elevation.elevation)) utcnow = datetime.utcnow() for attribute in kwargs: if attribute == 'elevation': LOG.debug('Skipping update to physical_elevation.elevation') continue old_value = getattr(physical_elevation, attribute) new_value = kwargs[attribute] if old_value != new_value and new_value: if not old_value: old_value = 'None' LOG.debug('Types old_value: {0} new_value: {1}'.format(type(old_value), type(new_value))) LOG.debug('Updating physical_elevation: {0} attribute: ' '{1} new_value: {2}'.format(physical_elevation.elevation, attribute, new_value)) audit = PhysicalElevationAudit(object_id=physical_elevation.id, field=attribute, old_value=old_value, new_value=new_value, updated_by=kwargs['updated_by'], created=utcnow) DBSession.add(audit) setattr(physical_elevation, attribute, new_value) DBSession.flush() return api_200(results=physical_elevation) except Exception as ex: msg = 'Error updating physical_elevation name: {0} updated_by: {1} exception: ' \ '{2}'.format(physical_elevation.elevation, my_attribs['updated_by'], repr(ex)) LOG.error(msg) raise # Routes @view_config(route_name='api_physical_elevations', request_method='GET', request_param='schema=true', renderer='json') def api_physical_elevations_schema(request): '''Schema document for the physical_elevations API.''' physical_elevation = { } return physical_elevation @view_config(route_name='api_physical_elevations', permission='physical_elevation_write', request_method='PUT', renderer='json') def api_physical_elevations_write(request): '''Process write requests for /api/physical_elevations route.''' try: req_params = [ 'elevation', 'physical_location', 'physical_rack', ] opt_params = [] params = collect_params(request, req_params, opt_params) try: physical_location = find_physical_location_by_name(params['physical_location']) del params['physical_location'] physical_rack = find_physical_rack_by_name_loc(params['physical_rack'], physical_location.id) params['physical_rack_id'] = physical_rack.id del params['physical_rack'] try: physical_el = find_physical_elevation_by_elevation(params['elevation'], params['physical_rack_id']) resp = update_physical_elevation(physical_el, **params) except NoResultFound: resp = create_physical_elevation(**params) except: raise return resp except Exception as ex: msg = 'Error writing to physical_racks API: {0} exception: {1}'.format(request.url, ex) LOG.error(msg) return api_500(msg=msg) @view_config(route_name='api_physical_elevation_r', permission='physical_elevation_delete', request_method='DELETE', renderer='json') @view_config(route_name='api_physical_elevation_r', permission='physical_elevation_write', request_method='PUT', renderer='json') def api_physical_elevation_write_attrib(request): '''Process write requests for the /api/physical_elevations/{id}/{resource} route.''' resource = request.matchdict['resource'] payload = request.json_body auth_user = get_authenticated_user(request) LOG.debug('Updating {0}'.format(request.url)) # First get the physical_elevation, then figure out what to do to it. physical_elevation = find_physical_elevation_by_id(request.matchdict['id']) LOG.debug('physical_elevation is: {0}'.format(physical_elevation)) # List of resources allowed resources = [ 'nothing_yet', ] # There's nothing to do here yet. Maye add updates to existing physical_elevation? if resource in resources: try: actionable = payload[resource] except KeyError: msg = 'Missing required parameter: {0}'.format(resource) return api_400(msg=msg) except Exception as ex: LOG.error('Error updating physical_elevations: {0} exception: {1}'.format(request.url, ex)) return api_500(msg=str(ex)) else: return api_501() return resp
{ "repo_name": "CityGrid/arsenal", "path": "server/arsenalweb/views/api/physical_elevations.py", "copies": "1", "size": "9810", "license": "apache-2.0", "hash": -5734323972257057000, "line_mean": 37.023255814, "line_max": 133, "alpha_frac": 0.5935779817, "autogenerated": false, "ratio": 4.450998185117967, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.0015303717628198448, "num_lines": 258 }
'''Arsenal API physical_locations.''' # Copyright 2015 CityGrid Media, LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # import logging from datetime import datetime from pyramid.view import view_config from sqlalchemy.orm.exc import NoResultFound from arsenalweb.views import ( get_authenticated_user, ) from arsenalweb.views.api.common import ( api_200, api_400, api_500, api_501, collect_params, ) from arsenalweb.models.common import ( DBSession, ) from arsenalweb.models.physical_locations import ( PhysicalLocation, PhysicalLocationAudit, ) LOG = logging.getLogger(__name__) # Functions def find_physical_location_by_name(name): '''Find a physical_location by name. Returns a physical_location object if found, raises NoResultFound otherwise.''' LOG.debug('Searching for physical_location by name: {0}'.format(name)) physical_location = DBSession.query(PhysicalLocation) physical_location = physical_location.filter(PhysicalLocation.name == name) return physical_location.one() def find_physical_location_by_id(physical_location_id): '''Find a physical_location by id.''' LOG.debug('Searching for physical_location by id: {0}'.format(physical_location_id)) physical_location = DBSession.query(PhysicalLocation) physical_location = physical_location.filter(PhysicalLocation.id == physical_location_id) return physical_location.one() def create_physical_location(name=None, updated_by=None, **kwargs): '''Create a new physical_location. Required params: name : A string that is the name of the physical_location. updated_by: A string that is the user making the update. Optional kwargs: provider : A string that is the physical_location provider. address_1 : A string that is the address line 1. address_2 : A string that is the address line 2. city : A string that is the address city. admin_area : A string that is the state/province. country : A string that is teh country. postal_code : A string that is the postal code. contact_name: A string that is the contat name of the data center. phone_number: A string that is the phone number of the data center. ''' try: LOG.info('Creating new physical_location name: {0}'.format(name)) utcnow = datetime.utcnow() physical_location = PhysicalLocation(name=name, updated_by=updated_by, created=utcnow, updated=utcnow, **kwargs) DBSession.add(physical_location) DBSession.flush() audit = PhysicalLocationAudit(object_id=physical_location.id, field='name', old_value='created', new_value=physical_location.name, updated_by=updated_by, created=utcnow) DBSession.add(audit) DBSession.flush() return api_200(results=physical_location) except Exception as ex: msg = 'Error creating new physical_location name: {0} exception: ' \ '{1}'.format(name, ex) LOG.error(msg) return api_500(msg=msg) def update_physical_location(physical_location, **kwargs): '''Update an existing physical_location. Required params: physical_location : A physical_location object. updated_by : A string that is the user making the update. Optional kwargs: provider : A string that is the physical_location provider. address_1 : A string that is the address line 1. address_2 : A string that is the address line 2. city : A string that is the address city. admin_area : A string that is the state/province. country : A string that is teh country. postal_code : A string that is the postal code. contact_name: A string that is the contat name of the data center. phone_number: A string that is the phone number of the data center. ''' try: # Convert everything that is defined to a string. my_attribs = kwargs.copy() for my_attr in my_attribs: if my_attribs.get(my_attr): my_attribs[my_attr] = str(my_attribs[my_attr]) LOG.info('Updating physical_location: {0}'.format(physical_location.name)) utcnow = datetime.utcnow() for attribute in my_attribs: if attribute == 'name': LOG.debug('Skipping update to physical_location.name') continue old_value = getattr(physical_location, attribute) new_value = my_attribs[attribute] if old_value != new_value and new_value: if not old_value: old_value = 'None' LOG.debug('Updating physical_location: {0} attribute: ' '{1} new_value: {2}'.format(physical_location.name, attribute, new_value)) audit = PhysicalLocationAudit(object_id=physical_location.id, field=attribute, old_value=old_value, new_value=new_value, updated_by=my_attribs['updated_by'], created=utcnow) DBSession.add(audit) setattr(physical_location, attribute, new_value) DBSession.flush() return api_200(results=physical_location) except Exception as ex: msg = 'Error updating physical_location name: {0} updated_by: {1} exception: ' \ '{2}'.format(physical_location.name, my_attribs['updated_by'], repr(ex)) LOG.error(msg) raise # Routes @view_config(route_name='api_physical_locations', request_method='GET', request_param='schema=true', renderer='json') def api_physical_locations_schema(request): '''Schema document for the physical_locations API.''' physical_location = { } return physical_location @view_config(route_name='api_physical_locations', permission='physical_location_write', request_method='PUT', renderer='json') def api_physical_locations_write(request): '''Process write requests for /api/physical_locations route.''' try: req_params = [ 'name', ] opt_params = [ 'provider', 'address_1', 'address_2', 'city', 'admin_area', 'country', 'postal_code', 'contact_name', 'phone_number', ] params = collect_params(request, req_params, opt_params) try: physical_location = find_physical_location_by_name(params['name']) resp = update_physical_location(physical_location, **params) except NoResultFound: resp = create_physical_location(**params) return resp except Exception as ex: msg = 'Error writing to physical_locations API: {0} exception: {1}'.format(request.url, ex) LOG.error(msg) return api_500(msg=msg) @view_config(route_name='api_physical_location_r', permission='physical_location_delete', request_method='DELETE', renderer='json') @view_config(route_name='api_physical_location_r', permission='physical_location_write', request_method='PUT', renderer='json') def api_physical_location_write_attrib(request): '''Process write requests for the /api/physical_locations/{id}/{resource} route.''' resource = request.matchdict['resource'] payload = request.json_body auth_user = get_authenticated_user(request) LOG.debug('Updating {0}'.format(request.url)) # First get the physical_location, then figure out what to do to it. physical_location = find_physical_location_by_id(request.matchdict['id']) LOG.debug('physical_location is: {0}'.format(physical_location)) # List of resources allowed resources = [ 'nothing_yet', ] # There's nothing to do here yet. Maye add updates to existing physical_location? if resource in resources: try: actionable = payload[resource] except KeyError: msg = 'Missing required parameter: {0}'.format(resource) return api_400(msg=msg) except Exception as ex: LOG.error('Error updating physical_locations: {0} exception: {1}'.format(request.url, ex)) return api_500(msg=str(ex)) else: return api_501() return resp
{ "repo_name": "CityGrid/arsenal", "path": "server/arsenalweb/views/api/physical_locations.py", "copies": "1", "size": "9526", "license": "apache-2.0", "hash": -565221042085662140, "line_mean": 35.6384615385, "line_max": 131, "alpha_frac": 0.6003569179, "autogenerated": false, "ratio": 4.3398633257403185, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.0008730856780674532, "num_lines": 260 }
'''Arsenal API physical_racks.''' # Copyright 2015 CityGrid Media, LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # import logging from datetime import datetime from pyramid.view import view_config from sqlalchemy.orm.exc import NoResultFound from arsenalweb.views import ( get_authenticated_user, ) from arsenalweb.views.api.common import ( api_200, api_400, api_500, api_501, collect_params, ) from arsenalweb.views.api.physical_locations import ( find_physical_location_by_name, ) from arsenalweb.models.common import ( DBSession, ) from arsenalweb.models.physical_racks import ( PhysicalRack, PhysicalRackAudit, ) LOG = logging.getLogger(__name__) # Functions def find_physical_rack_by_name_loc(name, physical_location_id): '''Find a physical_rack by name and physical_location_id. Returns a physical_rack object if found, raises NoResultFound otherwise.''' LOG.debug('Searching for physical_rack by name: {0} ' 'physical_location_id: {1}'.format(name, physical_location_id)) physical_rack = DBSession.query(PhysicalRack) physical_rack = physical_rack.filter(PhysicalRack.name == name) physical_rack = physical_rack.filter(PhysicalRack.physical_location_id == physical_location_id) return physical_rack.one() def find_physical_rack_by_id(physical_rack_id): '''Find a physical_rack by id.''' LOG.debug('Searching for physical_rack by id: {0}'.format(physical_rack_id)) physical_rack = DBSession.query(PhysicalRack) physical_rack = physical_rack.filter(PhysicalRack.id == physical_rack_id) return physical_rack.one() def create_physical_rack(name=None, physical_location_id=None, updated_by=None, **kwargs): '''Create a new physical_rack. Required params: name : A string that is the name of the datacenter. physical_location_id: An integer that represents the id of the physical_location the rack resides in. updated_by: A string that is the user making the update. Optional kwargs: None yet. ''' try: LOG.info('Creating new physical_rack name: {0}'.format(name)) utcnow = datetime.utcnow() physical_rack = PhysicalRack(name=name, physical_location_id=physical_location_id, updated_by=updated_by, created=utcnow, updated=utcnow, **kwargs) DBSession.add(physical_rack) DBSession.flush() audit = PhysicalRackAudit(object_id=physical_rack.id, field='name', old_value='created', new_value=physical_rack.name, updated_by=updated_by, created=utcnow) DBSession.add(audit) DBSession.flush() return api_200(results=physical_rack) except Exception as ex: msg = 'Error creating new physical_rack name: {0} exception: ' \ '{1}'.format(name, ex) LOG.error(msg) return api_500(msg=msg) def update_physical_rack(physical_rack, **kwargs): '''Update an existing physical_rack. Required params: physical_rack : A physical_rack object. updated_by : A string that is the user making the update. Optional kwargs: physical_location_id: An integer that represents the id of the physical_location the rack resides in. ''' try: # Convert everything that is defined to a string. my_attribs = kwargs.copy() for my_attr in my_attribs: if my_attribs.get(my_attr): my_attribs[my_attr] = str(my_attribs[my_attr]) LOG.info('Updating physical_rack: {0}'.format(physical_rack.name)) utcnow = datetime.utcnow() for attribute in my_attribs: if attribute == 'name': LOG.debug('Skipping update to physical_rack.name') continue old_value = getattr(physical_rack, attribute) new_value = my_attribs[attribute] if old_value != new_value and new_value: if not old_value: old_value = 'None' LOG.debug('Updating physical_rack: {0} attribute: ' '{1} new_value: {2}'.format(physical_rack.name, attribute, new_value)) audit = PhysicalRackAudit(object_id=physical_rack.id, field=attribute, old_value=old_value, new_value=new_value, updated_by=my_attribs['updated_by'], created=utcnow) DBSession.add(audit) setattr(physical_rack, attribute, new_value) DBSession.flush() return api_200(results=physical_rack) except Exception as ex: msg = 'Error updating physical_rack name: {0} updated_by: {1} exception: ' \ '{2}'.format(physical_rack.name, my_attribs['updated_by'], repr(ex)) LOG.error(msg) raise # Routes @view_config(route_name='api_physical_racks', request_method='GET', request_param='schema=true', renderer='json') def api_physical_racks_schema(request): '''Schema document for the physical_racks API.''' physical_rack = { } return physical_rack @view_config(route_name='api_physical_racks', permission='physical_rack_write', request_method='PUT', renderer='json') def api_physical_racks_write(request): '''Process write requests for /api/physical_racks route.''' try: req_params = [ 'name', 'physical_location', ] opt_params = [] params = collect_params(request, req_params, opt_params) try: physical_location = find_physical_location_by_name(params['physical_location']) params['physical_location_id'] = physical_location.id del params['physical_location'] try: physical_rack = find_physical_rack_by_name_loc(params['name'], params['physical_location_id']) resp = update_physical_rack(physical_rack, **params) except NoResultFound: resp = create_physical_rack(**params) except NoResultFound: msg = 'physical_location not found: {0} unable to create ' \ 'rack: {1}'.format(params['physical_location'], params['name']) LOG.warn(msg) raise NoResultFound(msg) return resp except Exception as ex: msg = 'Error writing to physical_racks API: {0} exception: {1}'.format(request.url, ex) LOG.error(msg) return api_500(msg=msg) @view_config(route_name='api_physical_rack_r', permission='physical_rack_delete', request_method='DELETE', renderer='json') @view_config(route_name='api_physical_rack_r', permission='physical_rack_write', request_method='PUT', renderer='json') def api_physical_rack_write_attrib(request): '''Process write requests for the /api/physical_racks/{id}/{resource} route.''' resource = request.matchdict['resource'] payload = request.json_body auth_user = get_authenticated_user(request) LOG.debug('Updating {0}'.format(request.url)) # First get the physical_rack, then figure out what to do to it. physical_rack = find_physical_rack_by_id(request.matchdict['id']) LOG.debug('physical_rack is: {0}'.format(physical_rack)) # List of resources allowed resources = [ 'nothing_yet', ] # There's nothing to do here yet. Maye add updates to existing physical_rack? if resource in resources: try: actionable = payload[resource] except KeyError: msg = 'Missing required parameter: {0}'.format(resource) return api_400(msg=msg) except Exception as ex: LOG.error('Error updating physical_racks: {0} exception: {1}'.format(request.url, ex)) return api_500(msg=str(ex)) else: return api_501() return resp
{ "repo_name": "CityGrid/arsenal", "path": "server/arsenalweb/views/api/physical_racks.py", "copies": "1", "size": "9123", "license": "apache-2.0", "hash": 8071032369362400000, "line_mean": 34.4980544747, "line_max": 123, "alpha_frac": 0.5875260331, "autogenerated": false, "ratio": 4.179111314704535, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.0009313262671377571, "num_lines": 257 }
'''Arsenal API Stale Node Reports.''' # Copyright 2015 CityGrid Media, LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # import logging from datetime import datetime from datetime import timedelta from pyramid.view import view_config from sqlalchemy.orm.exc import NoResultFound from arsenalweb.models.common import ( DBSession, ) from arsenalweb.models.nodes import ( Node, ) from arsenalweb.models.statuses import ( Status, ) from arsenalweb.views.api.common import ( api_200, ) LOG = logging.getLogger(__name__) @view_config(route_name='api_reports_stale_nodes', request_method='GET', renderer='json') def api_reports_stale_node_read(request): '''Process read requests for the /api/reports/stale_nodes route.''' hours_past = int(request.GET.get('hours_past', 4)) status = request.GET.get('status', 'inservice') statuses = status.split(',') try: LOG.info('Searching for nodes with last_registered grater than {0} ' 'hours in the following statuses: {1}...'.format(hours_past, statuses)) status_ids = [] for status in statuses: my_status = DBSession.query(Status) my_status = my_status.filter(Status.name == status) my_status = my_status.one() status_ids.append(my_status.id) threshold = datetime.now() - timedelta(hours=hours_past) node = DBSession.query(Node) node = node.filter(Node.last_registered <= threshold) node = node.filter(Node.status_id.in_(status_ids)) nodes = node.all() total = node.count() except NoResultFound: nodes = [] LOG.info('Found {0} nodes with last_registered grater than {1} ' 'hours in the following statuses: {2}.'.format(total, hours_past, statuses)) LOG.debug('Nodes: {0}'.format(nodes)) return api_200(results=nodes, total=total, result_count=total)
{ "repo_name": "CityGrid/arsenal", "path": "server/arsenalweb/views/api/reports/stale_nodes.py", "copies": "1", "size": "2600", "license": "apache-2.0", "hash": 7674413253310664000, "line_mean": 35.6197183099, "line_max": 89, "alpha_frac": 0.6307692308, "autogenerated": false, "ratio": 3.969465648854962, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5100234879654961, "avg_score": null, "num_lines": null }
'''Arsenal API Statuses.''' # Copyright 2015 CityGrid Media, LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # import logging from datetime import datetime from pyramid.view import view_config from sqlalchemy.orm.exc import NoResultFound from sqlalchemy.orm.exc import MultipleResultsFound from arsenalweb.models.common import ( DBSession, ) from arsenalweb.models.nodes import ( NodeAudit, ) from arsenalweb.models.statuses import ( Status, StatusAudit, ) from arsenalweb.views import ( get_authenticated_user, ) from arsenalweb.views.api.common import ( api_200, api_400, api_404, api_500, api_501, ) from arsenalweb.views.api.nodes import ( find_node_by_id, ) from arsenalweb.views.api.data_centers import ( find_data_center_by_id, ) LOG = logging.getLogger(__name__) def find_status_by_name(status_name): '''Find a status by name.''' status = DBSession.query(Status) status = status.filter(Status.name == status_name) return status.one() def find_status_by_id(status_id): '''Find a status by id.''' status = DBSession.query(Status) status = status.filter(Status.id == status_id) return status.one() def create_status(name, description, user_id): '''Create a new status.''' try: LOG.info('Creating new status name={0},description={1}'.format(name, description)) utcnow = datetime.utcnow() status = Status(name=name, description=description, updated_by=user_id, created=utcnow, updated=utcnow) DBSession.add(status) DBSession.flush() status_audit = StatusAudit(object_id=status.id, field='name', old_value='created', new_value=status.id, updated_by=user_id, created=utcnow) DBSession.add(status_audit) DBSession.flush() except Exception, ex: msg = 'Error creating status name={0},description={1},' \ 'exception={2}'.format(name, description, ex) LOG.error(msg) return api_500(msg=msg) return status def assign_status(status, actionables, resource, user): '''Assign actionable_ids to a status.''' LOG.debug('START assign_status()') resp = {status.name: []} try: utcnow = datetime.utcnow() with DBSession.no_autoflush: for actionable_id in actionables: if resource == 'nodes': my_obj = find_node_by_id(actionable_id) elif resource == 'data_centers': my_obj = find_data_center_by_id(actionable_id) resp[status.name].append(my_obj.name) orig_status_id = my_obj.status_id LOG.debug('START assign_status() update status_id') my_obj.status_id = status.id LOG.debug('END assign_status() update status_id') if orig_status_id != status.id: LOG.debug('START assign_status() create audit') node_audit = NodeAudit(object_id=my_obj.id, field='status_id', old_value=orig_status_id, new_value=status.id, updated_by=user, created=utcnow) DBSession.add(node_audit) LOG.debug('END assign_status() create audit') LOG.debug('START assign_status() session add') DBSession.add(my_obj) LOG.debug('END assign_status() session add') LOG.debug('START assign_status() session flush') DBSession.flush() LOG.debug('END assign_status() session flush') except (NoResultFound, AttributeError): return api_404(msg='status not found') except MultipleResultsFound: msg = 'Bad request: id is not unique: {0}'.format(actionable_id) return api_400(msg=msg) except Exception as ex: msg = 'Error updating status: exception={0}'.format(ex) LOG.error(msg) return api_500(msg=msg) LOG.debug('RETURN assign_status()') return api_200(results=resp) @view_config(route_name='api_statuses', request_method='GET', request_param='schema=true', renderer='json') def api_statuses_schema(request): '''Schema document for the statuses API.''' status = { } return status # api_register permission is so that kaboom can update status. @view_config(route_name='api_status_r', permission='api_register', request_method='PUT', renderer='json') def api_status_write_attrib(request): '''Process write requests for the /api/statuses/{id}/{resource} route.''' LOG.debug('START api_status_write_attrib()') try: resource = request.matchdict['resource'] payload = request.json_body auth_user = get_authenticated_user(request) LOG.debug('Updating {0}'.format(request.url)) # First get the status, then figure out what to do to it. status = find_status_by_id(request.matchdict['id']) LOG.debug('status is: {0}'.format(status)) # List of resources allowed resources = [ 'nodes', 'data_centers', ] if resource in resources: try: actionable = payload[resource] resp = assign_status(status, actionable, resource, auth_user['user_id']) except KeyError: msg = 'Missing required parameter: {0}'.format(resource) return api_400(msg=msg) except Exception as ex: msg = 'Error updating status={0},exception={1}'.format(request.url, ex) LOG.error(msg) return api_500(msg=msg) else: return api_501() LOG.debug('RETURN api_status_write_attrib()') return resp except Exception as ex: msg = 'Error updating status={0},exception={1}'.format(request.url, ex) LOG.error(msg) return api_500(msg=msg) @view_config(route_name='api_statuses', permission='api_write', request_method='PUT', renderer='json') def api_status_write(request): '''Process write requests for /api/statuses route.''' try: auth_user = get_authenticated_user(request) payload = request.json_body name = payload['name'].rstrip() description = payload['description'].rstrip() LOG.debug('Searching for statuses name={0},description={1}'.format(name, description)) try: status = DBSession.query(Status) status = status.filter(Status.name == name) status = status.one() try: LOG.info('Updating name={0},description={1}'.format(name, description)) status.name = name status.description = description status.updated_by = auth_user['user_id'] DBSession.flush() except Exception, ex: msg = 'Error updating status name={0},description={1},' \ 'exception={2}'.format(name, description, ex) LOG.error(msg) return api_500(msg=msg) except NoResultFound: status = create_status(name, description, auth_user['user_id']) return api_200(results=status) except Exception, ex: msg = 'Error writing to statuses API={0},exception={1}'.format(request.url, ex) LOG.error(msg) return api_500(msg=msg)
{ "repo_name": "CityGrid/arsenal", "path": "server/arsenalweb/views/api/statuses.py", "copies": "1", "size": "8546", "license": "apache-2.0", "hash": 2013887788802997500, "line_mean": 33.4596774194, "line_max": 107, "alpha_frac": 0.5655277323, "autogenerated": false, "ratio": 4.245404868355688, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.0009402012146851469, "num_lines": 248 }
'''Arsenal API Tags.''' # Copyright 2015 CityGrid Media, LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # import logging from datetime import datetime from pyramid.view import view_config from pyramid.response import Response from sqlalchemy.orm.exc import NoResultFound from sqlalchemy.orm.exc import MultipleResultsFound from sqlalchemy.exc import DatabaseError from arsenalweb.models.common import ( DBSession, ) from arsenalweb.models.data_centers import ( DataCenter, DataCenterAudit, ) from arsenalweb.models.nodes import ( NodeAudit, ) from arsenalweb.models.node_groups import ( NodeGroup, NodeGroupAudit, ) from arsenalweb.models.physical_devices import ( PhysicalDevice, PhysicalDeviceAudit, ) from arsenalweb.models.tags import ( Tag, TagAudit, ) from arsenalweb.views import ( get_authenticated_user, ) from arsenalweb.views.api.common import ( api_200, api_400, api_403, api_404, api_409, api_500, api_501, underscore_to_camel, validate_tag_perm, ) from arsenalweb.views.api.data_centers import ( find_data_center_by_id, ) from arsenalweb.views.api.nodes import ( find_node_by_id, ) from arsenalweb.views.api.node_groups import ( find_node_group_by_id, ) from arsenalweb.views.api.physical_devices import ( find_physical_device_by_id, ) LOG = logging.getLogger(__name__) # Functions def find_tag_by_name(name, value): '''Search for an existing tag by name and value.''' LOG.debug('Searching for tag name: {0} value: {1}'.format(name, value)) try: tag = DBSession.query(Tag) tag = tag.filter(Tag.name == name) tag = tag.filter(Tag.value == value) one = tag.one() except DatabaseError: tag = DBSession.query(Tag) tag = tag.filter(Tag.name == name) tag = tag.filter(Tag.value == str(value)) one = tag.one() return one def find_tag_by_id(tag_id): '''Search for an existing tag by id.''' LOG.debug('Searching for tag id: {0}'.format(tag_id)) tag = DBSession.query(Tag) tag = tag.filter(Tag.id == tag_id) return tag.one() def create_tag(name, value, user): '''Create a new tag.''' try: LOG.info('Creating new tag name: {0} value: {1}'.format(name, value)) utcnow = datetime.utcnow() tag = Tag(name=name, value=value, updated_by=user, created=utcnow, updated=utcnow) DBSession.add(tag) DBSession.flush() tag_audit = TagAudit(object_id=tag.id, field='tag_id', old_value='created', new_value='{0}={1}'.format(tag.name, tag.value), updated_by=user, created=utcnow) DBSession.add(tag_audit) DBSession.flush() return api_200(results=tag) except Exception as ex: msg = 'Error creating new tag name: {0} value: {1},' \ 'exception: {2}'.format(name, value, ex) LOG.error(msg) return api_500(msg=msg) def manage_tags(tag, tagable_type, tagables, action, user): '''Manage tag assignment/deassignments to a list of id's. Takes a list of ids and assigns them to the tag. Assigning a tag to a node also removes any other tag(s) with the same key. tag : A Tag object. tagable_type: The type of object you are tagging. One of nodes, node_groups or data_centers. tagables: A list of node, node_group, data_center, or physical_device id's to assign/deassign the tag to/from. action : A string representing the action to perform. One of either 'PUT' or 'DELETE'. ''' valid_types = [ 'nodes', 'node_groups', 'data_centers', 'physical_devices', ] if tagable_type not in valid_types: msg = 'Invalid tagable type: {0}'.format(tagable_type) LOG.error(msg) raise NotImplementedError(msg) find_by_id = globals()['find_{0}_by_id'.format(tagable_type[:-1])] create_audit = globals()['{0}Audit'.format(underscore_to_camel(tagable_type[:-1]))] LOG.debug('Find by id function: {0}'.format(find_by_id)) try: tag_kv = '{0}={1}'.format(tag.name, tag.value) resp = {tag_kv: []} for tagable_id in tagables: tagable = find_by_id(tagable_id) try: resp[tag_kv].append(tagable.name) except AttributeError: LOG.debug('This object has no name, using serial_number instead.') resp[tag_kv].append(tagable.serial_number) current_tags_list = [my_tag.id for my_tag in tagable.tags] current_tags_remove = [my_tag.id for my_tag in tagable.tags if my_tag.name == tag.name and my_tag.value != tag.value] utcnow = datetime.utcnow() if action == 'PUT': if tag.id not in current_tags_list: my_audit = create_audit(object_id=tagable.id, field='tag_id', old_value='assigned', new_value=tag.id, updated_by=user, created=utcnow) DBSession.add(my_audit) my_subtype = getattr(tag, tagable_type) my_subtype.append(tagable) # Ensure only one tag key is present on a tagable object. for remove_id in current_tags_remove: remove_tag = find_tag_by_id(remove_id) LOG.debug('De-assigning tag from {0} for uniqueness. name: ' '{1} value: {2}'.format(tagable_type, remove_tag.name, remove_tag.value)) my_subtype = getattr(remove_tag, tagable_type) my_subtype.remove(tagable) my_audit = create_audit(object_id=tagable.id, field='tag_id', old_value=remove_tag.id, new_value='de-assigned', updated_by=user, created=utcnow) DBSession.add(remove_tag) DBSession.add(my_audit) if action == 'DELETE': try: my_subtype = getattr(tag, tagable_type) my_subtype.remove(tagable) my_audit = create_audit(object_id=tagable.id, field='tag_id', old_value=tag.id, new_value='de-assigned', updated_by=user, created=utcnow) DBSession.add(my_audit) except ValueError: pass DBSession.add(tag) DBSession.flush() except (NoResultFound, AttributeError): return api_404(msg='node not found') except MultipleResultsFound: msg = 'Bad request: {0}_id is not unique: {1}'.format(tagable_type, tagable_id) return api_400(msg=msg) except Exception as ex: LOG.error('Error updating node: exception={0}'.format(ex)) return api_500() return api_200(results=resp) # Routes @view_config(route_name='api_tags', request_method='GET', request_param='schema=true', renderer='json') def api_tag_schema(request): '''Schema document for tags API''' tag = { } return tag @view_config(route_name='api_tags', permission='tag_write', request_method='PUT', renderer='json') def api_tags_write(request): '''Process write requests for the /api/tags route.''' try: auth_user = get_authenticated_user(request) payload = request.json_body tag_name = payload['name'].rstrip() tag_value = payload['value'].rstrip() try: tag_value = int(tag_value) except ValueError: pass LOG.info('Searching for tag name={0}'.format(tag_name)) try: tag = find_tag_by_name(tag_name, tag_value) # Since there are no fields to update other than the two that # constitue a unqiue tag we return a 409 when an update would # have otherwise happened and handle it in client/UI. return api_409() except NoResultFound: if validate_tag_perm(request, auth_user, tag_name): tag = create_tag(tag_name, tag_value, auth_user['user_id']) else: return api_403() return tag except Exception as ex: msg = 'Error writing to tags API={0},exception={1}'.format(request.url, ex) LOG.error(msg) return api_500(msg=msg) @view_config(route_name='api_tag_r', permission='tag_delete', request_method='DELETE', renderer='json') @view_config(route_name='api_tag_r', permission='tag_write', request_method='PUT', renderer='json') def api_tag_write_attrib(request): '''Process write requests for the /api/tags/{id}/{resource} route.''' try: resource = request.matchdict['resource'] payload = request.json_body auth_user = get_authenticated_user(request) LOG.debug('Processing update for route: {0}'.format(request.url)) # First get the tag, then figure out what to do to it. tag = find_tag_by_id(request.matchdict['id']) LOG.debug('tag is: {0}'.format(tag)) # List of resources allowed resources = [ 'data_centers', 'node_groups', 'nodes', 'physical_devices', ] if resource in resources: try: if validate_tag_perm(request, auth_user, tag.name): resp = manage_tags(tag, resource, payload[resource], request.method, auth_user['user_id']) else: return api_403() except KeyError as ex: msg = 'Missing required parameter: {0} execption: ' \ '{1}'.format(resource, repr(ex)) LOG.debug(msg) return api_400(msg=msg) except Exception as ex: LOG.error('Error updating tags: {0} exception: {1}'.format(request.url, ex)) return api_500(msg=str(ex)) else: return api_501() return resp except Exception as ex: LOG.error('Error updating tags: {0} exception: {1}'.format(request.url, ex)) return api_500(msg=str(ex))
{ "repo_name": "CityGrid/arsenal", "path": "server/arsenalweb/views/api/tags.py", "copies": "1", "size": "11747", "license": "apache-2.0", "hash": -6757348908973448000, "line_mean": 34.9235474006, "line_max": 103, "alpha_frac": 0.5421809824, "autogenerated": false, "ratio": 4.066112841813776, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5108293824213777, "avg_score": null, "num_lines": null }
'''Arsenal API testing.''' # Copyright 2015 CityGrid Media, LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # import logging import json from pyramid.view import view_config from arsenalweb.models.common import ( DBSession, ) from arsenalweb.views import ( get_authenticated_user, ) from arsenalweb.views.api.common import ( api_200, api_400, api_404, api_500, api_501, collect_params, ) from arsenalweb.views.api.hardware_profiles import ( get_hardware_profile, create_hardware_profile, ) from arsenalweb.views.api.operating_systems import ( get_operating_system, create_operating_system, ) from arsenalweb.views.api.tags import ( manage_tags, ) LOG = logging.getLogger(__name__) @view_config(route_name='api_testing', request_method='GET', renderer='json') @view_config(route_name='api_testing', request_method='PUT', renderer='json') def api_node_schema(request): '''An endpoint for quick tests''' # my_ip = '10.255.251.24' # query = DBSession.query(NetworkInterface) # query = query.join(IpAddress) # query = query.filter(IpAddress.ip_address == my_ip) # resp = query.all() # LOG.debug('RESP IS: {0}'.format(resp)) # return resp return []
{ "repo_name": "CityGrid/arsenal", "path": "server/arsenalweb/views/api/testing.py", "copies": "1", "size": "1764", "license": "apache-2.0", "hash": -4126081280555981300, "line_mean": 28.4, "line_max": 77, "alpha_frac": 0.6989795918, "autogenerated": false, "ratio": 3.4186046511627906, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.46175842429627906, "avg_score": null, "num_lines": null }
'''Arsenal audit routes singleton object types.''' # Copyright 2015 CityGrid Media, LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # import logging from pyramid.view import view_config from arsenalweb.views import ( _api_get, get_authenticated_user, site_layout, ) LOG = logging.getLogger(__name__) @view_config(route_name='data_center_audit', permission='view', renderer='arsenalweb:templates/singleton_audit.pt') @view_config(route_name='hardware_profile_audit', permission='view', renderer='arsenalweb:templates/singleton_audit.pt') @view_config(route_name='ip_address_audit', permission='view', renderer='arsenalweb:templates/singleton_audit.pt') @view_config(route_name='network_interface_audit', permission='view', renderer='arsenalweb:templates/singleton_audit.pt') @view_config(route_name='node_audit', permission='view', renderer='arsenalweb:templates/singleton_audit.pt') @view_config(route_name='node_group_audit', permission='view', renderer='arsenalweb:templates/singleton_audit.pt') @view_config(route_name='operating_system_audit', permission='view', renderer='arsenalweb:templates/singleton_audit.pt') @view_config(route_name='physical_device_audit', permission='view', renderer='arsenalweb:templates/singleton_audit.pt') @view_config(route_name='physical_elevation_audit', permission='view', renderer='arsenalweb:templates/singleton_audit.pt') @view_config(route_name='physical_location_audit', permission='view', renderer='arsenalweb:templates/singleton_audit.pt') @view_config(route_name='physical_rack_audit', permission='view', renderer='arsenalweb:templates/singleton_audit.pt') @view_config(route_name='status_audit', permission='view', renderer='arsenalweb:templates/singleton_audit.pt') @view_config(route_name='tag_audit', permission='view', renderer='arsenalweb:templates/singleton_audit.pt') def view_singleton_audit(request): '''Handle all audit routes for object types that are singletons (non-list, non-dict).''' meta = { 'data_center_audit': { 'page_type': 'Data Center', 'object_type': 'data_centers', }, 'hardware_profile_audit': { 'page_type': 'Hardware Profile', 'object_type': 'hardware_profiles', }, 'ip_address_audit': { 'page_type': 'IpAddress', 'object_type': 'ip_addresses', }, 'network_interface_audit': { 'page_type': 'NetworkInterface', 'object_type': 'network_interfaces', }, 'node_audit': { 'page_type': 'Node', 'object_type': 'nodes', }, 'node_group_audit': { 'page_type': 'Node Group', 'object_type': 'node_groups', }, 'operating_system_audit': { 'page_type': 'Operating System', 'object_type': 'operating_systems', }, 'physical_device_audit': { 'page_type': 'Physical Devices', 'object_type': 'physical_devices', }, 'physical_elevation_audit': { 'page_type': 'Physical Elevations', 'object_type': 'physical_elevations', }, 'physical_location_audit': { 'page_type': 'Physical Locations', 'object_type': 'physical_locations', }, 'physical_rack_audit': { 'page_type': 'Physical Racks', 'object_type': 'physical_racks', }, 'status_audit': { 'page_type': 'Status', 'object_type': 'statuses', }, 'tag_audit': { 'page_type': 'Tag', 'object_type': 'tags', }, } params = meta[request.matched_route.name] auth_user = get_authenticated_user(request) page_title = '{0}_audit'.format(params['object_type']) uri = '/api/{0}_audit/{1}'.format(params['object_type'], request.matchdict['id']) object_audit = _api_get(request, uri) return { 'au': auth_user, 'layout': site_layout('audit'), 'object_audit': object_audit['results'], 'page_title_name': page_title, 'params': params, }
{ "repo_name": "CityGrid/arsenal", "path": "server/arsenalweb/views/singleton_audit.py", "copies": "1", "size": "4654", "license": "apache-2.0", "hash": 8719510976555855000, "line_mean": 40.5535714286, "line_max": 122, "alpha_frac": 0.6334336055, "autogenerated": false, "ratio": 3.7172523961661343, "config_test": true, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.4850686001666134, "avg_score": null, "num_lines": null }
'''Arsenal Authorization class.''' # # Copyright 2015 CityGrid Media, LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # import os import logging import getpass import ast import requests try: import urllib3 urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning) except (ImportError, AttributeError): pass LOG = logging.getLogger(__name__) # requests is chatty logging.getLogger("requests").setLevel(logging.WARNING) try: requests.packages.urllib3.disable_warnings() except AttributeError: pass def check_root(): '''Check and see if we're running as root. Returns True or False.''' if not os.geteuid() == 0: LOG.error('This command must be run as root.') return False return True class Authorization(object): '''The Arsenal Authorization class. Usage:: >>> from arsenalclient.authorization import Authorization >>> params = { ... 'cookie_file': '/home/abandt/.arsenal_cookie.txt', ... 'user_login': 'abandt', ... } >>> auth = Authorization(**params) Required Args: cookie_file: A string that is the path to the cookie file to use. This should map to a file in the homedir of the user. user_login : A string that is the user's login name. Optional Args: api_host : A string that is the name of the Arsenal server. Default value is 'arsenal'. api_protocol : A string that is the protocol version to use. Valid values are 'https' (default) or 'http'. user_password: A string that is the user's password. verify_ssl : Whether or not to verify the ssl connection to the Arsenal server. Defaults to True. ''' def __init__(self, api_host='arsenal', api_protocol='https', verify_ssl=True, **kwargs ): self.session = requests.session() self.cookies = None self.api_protocol = api_protocol self.api_host = api_host self.cookie_file = kwargs.get('cookie_file') self.user_login = kwargs.get('user_login') self.user_password = kwargs.get('user_password') self.verify_ssl = verify_ssl def get_cookie_auth(self): '''Gets cookies from cookie file or authenticates if no cookie file is present. Returns: A dict of all cookies if successful, raises an exception otherwise. ''' try: self.read_cookie() if not self.cookies: self.authenticate() else: self.cookies = ast.literal_eval(self.cookies) except Exception, ex: LOG.error('Failed to evaluate cookies: {0}'.format(repr(ex))) raise def read_cookie(self): '''Reads cookies from cookie file. Returns: A dict of all cookies if cookie_file is present, None otherwise. ''' LOG.debug('Checking for cookie file: {0}'.format(self.cookie_file)) if os.path.isfile(self.cookie_file): LOG.debug('Cookie file found: {0}'.format(self.cookie_file)) with open(self.cookie_file, 'r') as contents: self.cookies = contents.read() else: LOG.debug('Cookie file does not exist: {0}'.format(self.cookie_file)) def write_cookie(self, cookies): '''Writes cookies to cookie file. Returns: True if successful, False otherwise. ''' LOG.info('Writing cookie file: {0}'.format(self.cookie_file)) try: cookie_dict = dict(cookies) with open(self.cookie_file, "w") as cookie_file: cookie_file.write(str(cookie_dict)) os.chmod(self.cookie_file, 0600) except Exception as ex: LOG.error('Unable to write cookie: ' '{0}'.format(self.cookie_file)) LOG.error('Exception: {0}'.format(repr(ex))) raise def authenticate(self): '''Prompts for user password and authenticates against the API. Writes response cookies to file for later use. Returns: A dict of all cookies if successful, None otherwise. ''' if self.user_login == 'read_only': LOG.error('Write access denied for read_only user.') return None else: LOG.info('Authenticating login: {0}'.format(self.user_login)) # Kaboom password is exposed on dev systems where others have root, # thus insecurable. This may change in the future. if self.user_login == 'kaboom': password = 'password' elif getattr(self, 'user_password'): password = self.user_password else: password = getpass.getpass('password: ') try: payload = { 'form.submitted': True, 'api.client': True, 'return_url': '/api', 'login': self.user_login, 'password': password } resp = self.session.post(self.api_protocol + '://' + self.api_host + '/login', data=payload, verify=self.verify_ssl) resp.raise_for_status() LOG.debug('Authentication successful for user: {0}'.format(self.user_login)) self.cookies = self.session.cookies.get_dict() LOG.debug('Cookies are: {0}'.format(self.cookies)) try: self.write_cookie(self.cookies) except Exception, ex: LOG.error('Exception: {0}'.format(repr(ex))) raise except Exception, ex: LOG.error('Exception: {0}'.format(repr(ex))) LOG.error('Authentication failed') raise
{ "repo_name": "CityGrid/arsenal", "path": "client/arsenalclient/authorization.py", "copies": "1", "size": "6734", "license": "apache-2.0", "hash": 8484785641132507000, "line_mean": 33.3571428571, "line_max": 92, "alpha_frac": 0.5555390555, "autogenerated": false, "ratio": 4.498329993319973, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.0008505908483611069, "num_lines": 196 }
'''Arsenal client common command line helper functions. These functions support the functions that are called directly by args.func() to invoke the appropriate action. ''' # # Copyright 2015 CityGrid Media, LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # from __future__ import print_function import sys import logging import json import re import yaml LOG = logging.getLogger(__name__) def _check_tags(obj, set_tags): '''Check for tags that will be changed or removed.''' resp = '' try: tags = [tag for tag in set_tags.split(',')] # No tags except AttributeError: return resp LOG.debug('Taggable object is: {0}'.format(obj)) for tag in tags: LOG.debug('Working on tag: {0}'.format(tag)) key, val = tag.split('=') try: LOG.debug('name is: {0}'.format(obj['name'])) except KeyError: LOG.debug('serial_number is: {0}'.format(obj['serial_number'])) LOG.debug('tags are: {0}'.format(obj['tags'])) for obj_tag in obj['tags']: if key == obj_tag['name']: resp += ' Existing tag found: {0}={1} value will be updated ' \ 'to: {2}\n'.format(obj_tag['name'], obj_tag['value'], val) return resp.rstrip() def check_resp(resp): '''Check the http response code and exit non-zero if it's not a 200.''' LOG.debug('Checking status of http response: {0}'.format(json.dumps(resp, sort_keys=True, indent=2))) if resp['http_status']['code'] != 200: sys.exit(1) def gen_help(help_type): '''Generate the list of searchable terms for help''' terms = { 'data_centers_search': [ 'id', 'name', 'status', ], 'ip_addresses_search': [ 'id', 'ip_address', ], 'network_interfaces_search': [ 'id', 'name', 'unique_id', 'bond_master', 'ip_address_id', 'port_description', 'port_number', 'port_switch', 'port_vlan', ], 'nodes_search': [ 'id', 'name', 'unique_id', 'status_id', 'status', 'hardware_profile_id', 'hardware_profile', 'operating_system_id', 'operating_system', 'uptime', 'node_groups', 'created', 'updated', 'updated_by', ], 'node_groups_search': [ 'id', 'name', 'node_group_owner', 'description', 'notes_url', ], 'physical_devices_search': [ 'id', 'serial_number', 'physical_elevation', 'physical_location', 'physical_rack', 'hardware_profile', 'oob_ip_address', 'oob_mac_address', ], 'physical_elevations_search': [ 'id', 'elevation', 'physical_rack.name', ], 'physical_locations_search': [ 'id', 'name', 'provider', 'address_1', 'address_2', 'city', 'admin_area', 'country', 'postal_code', 'contact_name', 'phone_number', ], 'physical_racks_search': [ 'id', 'name', 'physical_location', ], 'statuses_search': [ 'id', 'name', 'description', ], 'tags_search': [ 'id', 'name', 'value', ], 'hypervisor_vm_assignments_search': [ 'parent_id', 'child_id', ], } try: my_help = '[ {0} ]'.format(', '.join(sorted(terms[help_type]))) return my_help except KeyError: LOG.error('No help terms defined for help type: {0}'.format(help_type)) raise def ask_yes_no(question, answer_yes=None, default='no'): '''Ask a yes/no question via raw_input() and return their answer. "question" is a string that is presented to the user. "default" is the presumed answer if the user just hits <Enter>. It must be "yes" (the default), "no" or None (meaning an answer is required of the user). The "answer" return value is True for "yes" or False for "no". ''' if answer_yes: sys.stdout.write(question + ' Forced yes\n') return True valid = { 'yes': True, 'y': True, 'ye': True, 'no': False, 'n': False } if default is None: prompt = ' [y/n] ' elif default == 'yes': prompt = ' [Y/n] ' elif default == 'no': prompt = ' [y/N] ' else: raise ValueError("invalid default answer: '%s'" % default) while True: sys.stdout.write(question + prompt) choice = raw_input().lower() if default is not None and choice == '': return valid[default] elif choice in valid: return valid[choice] else: sys.stdout.write("Please respond with 'yes' or 'no' " "(or 'y' or 'n').\n") def update_object_fields(args, obj_type, object_result, fields): '''Update object fields from CLI.''' LOG.debug('update_object_fields() input: {0}'.format(object_result)) object_result.update((key.replace(obj_type + '_', ''), getattr(args, key)) for key in fields if getattr(args, key, None)) LOG.debug('update_object_fields() output: {0}'.format(object_result)) return object_result def print_results(args, results, default_key='name', skip_keys=None): '''Print results to the terminal in a yaml style output. Defaults to printing name and id first, but can be overridden Params: args : arsenal.client args namespace object. results : Dictionary of results to print. default_key: The key to use when no specific fields are asked for. skip_keys : List of keys to print first. Defaults to name, id. ''' if args.json: print(json.dumps(results, indent=2, sort_keys=True)) return True if not skip_keys: skip_keys = [ 'name', 'id', ] if args.fields: for res in results: dump = yaml.safe_dump(res, default_flow_style=False) for index, item in enumerate(skip_keys): leader = ' ' if index == 0: leader = '- ' print('{0}{1}: {2}'.format(leader, item, res[item])) for line in dump.splitlines(): skip = line.split(':')[0] if skip in skip_keys: continue print(' {0}'.format(line)) print('') # Default to displaying just the default_key else: for res in results: # Special overrides go here. if default_key == 'tag': print('{0}={1}'.format(res['name'], res['value'])) else: print(res[default_key]) if args.audit_history: for audit in res['audit_history']: print('{0:>23} - updated_by: {1:<15} field: {2:<20} old_value: {3:<14} ' 'new_value: {4:<14}'.format(audit['created'], audit['updated_by'], audit['field'], audit['old_value'], audit['new_value'],)) def parse_cli_args(search=None, fields=None, exact_get=None, exclude=None): '''Parses comma separated argument values passed from the CLI and turns them into a dictionary of parameters for the search() function. Args: search (str): The key=value search terms. Multiple values separated by comma (,). Multiple keys sparated by comma (,). fields (str): The specific fields to return. Multiple values separated by comma (,). exact_get (str): Whether to search for terms exactly or use wildcard matching. exclude (str): The key=value search terms to explicitly exclude. Multiple values separated by comma (,). Multiple keys sparated by comma (,). Returns: A dict of params to be passed to the <object_type>.search() function ''' regex = re.compile(r'([^=]+)=([^=]+)(?:,|$)') matches = regex.findall(search) data = {} for match in matches: data[match[0]] = match[1] if exclude: ex_matches = regex.findall(exclude) for match in ex_matches: data['ex_{0}'.format(match[0])] = match[1] data['exact_get'] = exact_get if fields: data['fields'] = fields LOG.debug('Search data is: {0}'.format(json.dumps(data, indent=4, sort_keys=True))) return data
{ "repo_name": "CityGrid/arsenal", "path": "client/arsenalclient/cli/common.py", "copies": "1", "size": "9907", "license": "apache-2.0", "hash": 1944338588494474500, "line_mean": 30.7532051282, "line_max": 92, "alpha_frac": 0.5025739376, "autogenerated": false, "ratio": 4.224733475479744, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.0008676364830186021, "num_lines": 312 }
'''Arsenal client data_center command line helpers. These functions are called directly by args.func() to invoke the appropriate action. They also handle output formatting to the commmand line. ''' # # Copyright 2015 CityGrid Media, LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # from __future__ import print_function import logging from arsenalclient.cli.common import ( ask_yes_no, check_resp, parse_cli_args, print_results, ) from arsenalclient.exceptions import NoResultFound LOG = logging.getLogger(__name__) UPDATE_FIELDS = [ 'data_center_status', ] TAG_FIELDS = [ 'set_tags', 'del_tags', ] def search_data_centers(args, client): '''Search for data_centers and perform optional assignment actions.''' LOG.debug('action_command is: {0}'.format(args.action_command)) LOG.debug('object_type is: {0}'.format(args.object_type)) resp = None action_fields = UPDATE_FIELDS + TAG_FIELDS search_fields = args.fields if any(getattr(args, key) for key in UPDATE_FIELDS): search_fields = 'all' params = parse_cli_args(args.search, search_fields, args.exact_get, args.exclude) resp = client.data_centers.search(params) if not resp.get('results'): return resp results = resp['results'] if args.audit_history: results = client.data_centers.get_audit_history(results) if not any(getattr(args, key) for key in action_fields): print_results(args, results) else: r_names = [] for data_center in results: r_names.append('name={0},id={1}'.format(data_center['name'], data_center['id'])) msg = 'We are ready to update the following data_center: \n ' \ '{0}\nContinue?'.format('\n '.join(r_names)) if args.data_center_status and ask_yes_no(msg, args.answer_yes): resp = client.statuses.assign(args.data_center_status, 'data_centers', results) if args.set_tags and ask_yes_no(msg, args.answer_yes): tags = [tag for tag in args.set_tags.split(',')] for tag in tags: name, value = tag.split('=') resp = client.tags.assign(name, value, 'data_centers', results) if args.del_tags and ask_yes_no(msg, args.answer_yes): tags = [tag for tag in args.del_tags.split(',')] for tag in tags: name, value = tag.split('=') resp = client.tags.deassign(name, value, 'data_centers', results) if resp: check_resp(resp) LOG.debug('Complete.') def create_data_center(args, client): '''Create a new data_center.''' LOG.info('Checking if data_center name exists: {0}'.format(args.data_center_name)) data_center = { 'name': args.data_center_name, 'status': args.data_center_status, } try: result = client.data_centers.get_by_name(args.data_center_name) if ask_yes_no('Entry already exists for data_center name: {0}\n Would you ' \ 'like to update it?'.format(result['name']), args.answer_yes): resp = client.data_centers.update(data_center) except NoResultFound: resp = client.data_centers.create(data_center) check_resp(resp) def delete_data_center(args, client): '''Delete an existing data_center.''' LOG.debug('action_command is: {0}'.format(args.action_command)) LOG.debug('object_type is: {0}'.format(args.object_type)) try: params = { 'name': args.data_center_name, 'exact_get': True, } resp = client.data_centers.search(params) results = resp['results'] r_names = [] for data_centers in results: r_names.append(data_centers['name']) msg = 'We are ready to delete the following {0}: ' \ '\n{1}\n Continue?'.format(args.object_type, '\n '.join(r_names)) if ask_yes_no(msg, args.answer_yes): for datacenter in results: resp = client.data_centers.delete(datacenter) check_resp(resp) except NoResultFound: LOG.info('data_center not found, nothing to do.')
{ "repo_name": "CityGrid/arsenal", "path": "client/arsenalclient/cli/data_center.py", "copies": "1", "size": "4769", "license": "apache-2.0", "hash": 6053498102539625000, "line_mean": 30.582781457, "line_max": 91, "alpha_frac": 0.6173201929, "autogenerated": false, "ratio": 3.72869429241595, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9841591687541336, "avg_score": 0.0008845595549227698, "num_lines": 151 }
'''Arsenal client DataCenters class.''' import logging from arsenalclient.interface.arsenal_interface import ArsenalInterface LOG = logging.getLogger(__name__) class DataCenters(ArsenalInterface): '''The arsenal client DataCenters class.''' def __init__(self, **kwargs): super(DataCenters, self).__init__(**kwargs) self.uri = '/api/data_centers' # Overridden methods def search(self, params=None): '''Search for data_centers. Usage: >>> params = { ... 'name': 'my_data_center', ... 'exact_get': True, ... } >>> DataCenters.search(params) Args: params (dict): a dictionary of url parameters for the request. Returns: A json response from ArsenalInterface.check_response_codes(). ''' return super(DataCenters, self).search(params) def create(self, params): '''Create a new data_center. Args: params (dict): A dictionary with the following attributes: name : The name of the data_center you wish to create. Usage: >>> params = { ... 'name': 'my_data_center1', ... } >>> DataCenters.create(params) <Response [200]> ''' return super(DataCenters, self).create(params) def update(self, params): '''There is nothing to update with data_centers. Use Statuses.assign() to set the status of a data_center.''' pass def delete(self, params): '''Delete a data_center object from the server. Args: params: A data_center dictionary to delete. Must contain the data_center id, and name. Usage: >>> params = { ... 'id': 1, ... 'name': 'my_data_center', ... } >>> DataCenters.delete(params) ''' return super(DataCenters, self).delete(params) def get_audit_history(self, results): '''Get the audit history for data_centers.''' return super(DataCenters, self).get_audit_history(results) def get_by_name(self, name): '''Get a single data_center by it's name. Args: name (str): A string representing the data_center name you wish to find. ''' return super(DataCenters, self).get_by_name(name) # Custom methods # TBD
{ "repo_name": "CityGrid/arsenal", "path": "client/arsenalclient/interface/data_centers.py", "copies": "1", "size": "2395", "license": "apache-2.0", "hash": 2869841411564283000, "line_mean": 24.752688172, "line_max": 84, "alpha_frac": 0.5670146138, "autogenerated": false, "ratio": 4.108061749571184, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5175076363371184, "avg_score": null, "num_lines": null }
'''Arsenal client data_centers command line parser''' # # Copyright 2015 CityGrid Media, LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # from arsenalclient.cli.common import gen_help from arsenalclient.cli.data_center import ( search_data_centers, create_data_center, delete_data_center, ) def parser_data_centers(top_parser, otsp): '''Add the data_centers CLI parser.''' ### data_centers object_type parser (dcotp) dc_help = ('Perform actions on the data_centers object_type. Use the \n' 'search action to perform assignment actions such as tagging.\n\n') dcotp = otsp.add_parser('data_centers', description=dc_help, help=dc_help, parents=[top_parser]) # data_centers action sub-parser (dcasp) dcasp = dcotp.add_subparsers(title='Available actions', dest='action_command') # data_centers search subcommand (dcssc) dcssc = dcasp.add_parser('search', help='Search for data_center objects and optionally ' \ 'act upon the results.', parents=[top_parser]) dcssc.add_argument('--fields', '-f', dest='fields', help='Comma separated list of fields to display, or \'all\' for all fields.', default=None) dcssc.add_argument('--exact', action='store_true', dest='exact_get', default=None, help='Exact match search terms.') dcssc.add_argument('--exclude', dest='exclude', default=None, help='Comma separated list of key=value pairs to exclude.') dcssc.add_argument('-a', '--audit-history', action='store_true', default=None, help='Show audit history for search results.') # data_centers update action argument group (dcuaag) dcuaag = dcssc.add_argument_group('Update Actions') dcuaag.add_argument('--status', dest='data_center_status', help='status to assign to the search results.') # data_centers assignment action argument group (dcaag) dcaag = dcssc.add_argument_group('Assignment Actions') dcaag.add_argument('--tag', dest='set_tags', help='Comma separated list of key=value pairs to tag to ' \ 'the search results.') dcaag.add_argument('--del_tag', dest='del_tags', help='Comma separated list of key=value pairs to un-tag from the ' \ 'search results.') dcssc.add_argument('search', default=None, metavar='search_terms', help='Comma separated list of key=value pairs to search ' \ 'for.\n {0}'.format(gen_help('data_centers_search'))) dcssc.set_defaults(func=search_data_centers) # data_centers create subcommand (dccsc) dccsc = dcasp.add_parser('create', help='Create data_center objects.', parents=[top_parser]) # required data_center create argument group (rdccag) rdccag = dccsc.add_argument_group('required arguments') rdccag.add_argument('--name', '-n', required=True, dest='data_center_name', help='data_center_name to create.') rdccag.add_argument('--status', '-s', dest='data_center_status', help='data_center_status to set the new data_center to. ' \ 'If not specified will be set to setup.') rdccag.set_defaults(func=create_data_center) # data_centers delete subcommand (dcdsc) dcdsc = dcasp.add_parser('delete', help='Delete data_center objects.', parents=[top_parser]) # required data_center delete argument group (rdcdag) rdcdag = dcdsc.add_argument_group('required arguments') rdcdag.add_argument('--name', '-n', required=True, dest='data_center_name', help='data_center_name to delete.') dcdsc.set_defaults(func=delete_data_center) return top_parser, otsp
{ "repo_name": "CityGrid/arsenal", "path": "client/arsenalclient/parser/data_centers.py", "copies": "1", "size": "5126", "license": "apache-2.0", "hash": 5291552701263042000, "line_mean": 41.7166666667, "line_max": 100, "alpha_frac": 0.5487709715, "autogenerated": false, "ratio": 4.415159345391904, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5463930316891903, "avg_score": null, "num_lines": null }
'''Arsenal client interface''' # # Copyright 2015 CityGrid Media, LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # import logging import json from abc import ABCMeta from abc import abstractmethod import requests from arsenalclient.exceptions import NoResultFound from arsenalclient.authorization import Authorization LOG = logging.getLogger(__name__) logging.VERBOSE = 11 logging.addLevelName(logging.VERBOSE, "VERBOSE") def verbose(self, message, *args, **kws): '''Set custom logging level for more logging information than info but less than debug.''' if self.isEnabledFor(logging.VERBOSE): # pylint: disable=W0212 self._log(logging.VERBOSE, message, args, **kws) logging.Logger.verbose = verbose class ArsenalInterface(object): '''The arsenal client interface. This is the abstract base class that all the interface clasees are based on. It handles Authorization and http calls to the API, as well as implements the default abstract methods that must be overrideen by the child classes. ''' __metaclass__ = ABCMeta def __init__(self, **kwargs): self.uri = None self.session = requests.session() self.cookies = None self.settings = kwargs['settings'] self.authorization = Authorization(api_host=self.settings.api_host, api_protocol=self.settings.api_protocol, cookie_file=self.settings.cookie_file, user_login=self.settings.user_login, user_password=self.settings.user_password, verify_ssl=self.settings.verify_ssl) @staticmethod def check_response_codes(resp, log_success=True): '''Checks the response codes and logs appropriate messaging for the client. Args: resp: A response object from the requests package. Returns: Json from response if successful, json formatted response code otherwise. ''' try: results = resp.json() if resp.status_code == 200: if log_success: LOG.info('Command successful.') else: LOG.warn('{0}: {1}'.format(results['http_status']['code'], results['http_status']['message'])) LOG.debug('Returning json...') return results except ValueError: LOG.debug('Json decode failed, falling back to manual json response...') my_resp = { 'http_status': { 'code': resp.status_code, 'message': resp.reason, } } LOG.warn('{0}: {1}'.format(resp.status_code, resp.reason)) return my_resp def api_conn(self, uri, data=None, method='get', log_success=True): ''' Manages http requests to the API. Usage: >>> data = { ... 'unique_id': '12345' >>> } >>> api_conn('/api/nodes', data) <{json object}> >>> api_conn('/api/invalid', data) <Response 404> >>> api_conn('/api/nodes/1') <{json object}> >>> api_conn('/api/nodes', data, 'put') <{json object}> >>> api_conn('/api/nodes', data, 'delete') <{json object}> Args: data (dict): A dict of paramters to send with the http request. method (str): The http method to use. Valid choices are: delete get put Returns: check_response_codes() ''' headers = {'content-type': 'application/json'} api_url = '{0}://{1}{2}'.format(self.settings.api_protocol, self.settings.api_host, uri) try: if method == 'put': self.authorization.get_cookie_auth() LOG.verbose('PUT API call to endpoint: {0}'.format(api_url)) LOG.verbose('PUT params: \n{0}'.format(json.dumps(data, indent=2, sort_keys=True))) resp = self.session.put(api_url, verify=self.settings.verify_ssl, cookies=self.authorization.cookies, headers=headers, json=data) # re-auth if our cookie is invalid/expired if resp.status_code == 401: LOG.debug('Recieved 401 from api, re-authenticating...') self.authorization.authenticate() resp = self.session.put(api_url, verify=self.settings.verify_ssl, cookies=self.authorization.cookies, headers=headers, json=data) return self.check_response_codes(resp) elif method == 'delete': self.authorization.get_cookie_auth() LOG.verbose('DELETE API call to endpoint: {0}'.format(api_url)) LOG.verbose('DELETE params: \n{0}'.format(json.dumps(data, indent=2, sort_keys=True,))) resp = self.session.delete(api_url, verify=self.settings.verify_ssl, cookies=self.authorization.cookies, headers=headers, json=data) # re-auth if our cookie is invalid/expired if resp.status_code == 401: LOG.debug('Recieved 401 from api, re-authenticating...') self.authorization.authenticate() resp = self.session.delete(api_url, verify=self.settings.verify_ssl, cookies=self.authorization.cookies, headers=headers, json=data) return self.check_response_codes(resp) else: LOG.verbose('GET API call to endpoint: {0}'.format(api_url)) LOG.verbose('GET params: \n{0}'.format(json.dumps(data, indent=2, sort_keys=True,))) resp = self.session.get(api_url, verify=self.settings.verify_ssl, params=data) return self.check_response_codes(resp, log_success=log_success) except requests.exceptions.ConnectionError: LOG.error('Unable to connect to server: {0}'.format(self.settings.api_host)) raise @abstractmethod def search(self, params=None): '''Search for objects in the API. Args: params (dict): a dictionary of url parameters for the request. Returns: A json response from check_response_codes((). ''' LOG.verbose('Searching for {0}...'.format(self.uri.split('/')[-1])) resp = self.api_conn(self.uri, params, log_success=False) LOG.debug('Results are: {0}'.format(json.dumps(resp, indent=2, sort_keys=True))) if not resp['results']: LOG.info('No results found for search.') return resp @abstractmethod def create(self, params): '''Create a resource.''' LOG.info('Creating {0}...'.format(self.uri.split('/')[-1])) resp = self.api_conn(self.uri, params, method='put', log_success=False) return resp @abstractmethod def update(self, params): '''Update a resource.''' LOG.info('Updating {0}...'.format(self.uri.split('/')[-1])) resp = self.api_conn(self.uri, params, method='put', log_success=False) return resp @abstractmethod def delete(self, params): '''Delete a resource.''' resource_uri = '{0}/{1}'.format(self.uri, params['id']) LOG.info('Deleting {0}...'.format(self.uri.split('/')[-1])) resp = self.api_conn(resource_uri, method='delete') return resp @abstractmethod def get_audit_history(self, results): '''Retrieve audit history for a list of search results. Returns an updated list with audit history attached.''' audit_base_uri = self.uri + '_audit' resp = [] for obj in results: my_audit = self.api_conn('{0}/{1}'.format(audit_base_uri, obj['id']), log_success=False) obj['audit_history'] = my_audit['results'] resp.append(obj) return resp @abstractmethod def get_by_name(self, name): '''Retrieve a unique resource by name. Returns an single resource if one is found, raised NoResultFound if no result, raises a RuntimeError otherwise.''' LOG.verbose('Searching for single {0} by name...'.format(self.uri.split('/')[-1])) params = { 'name': name, 'exact_get': True, } resp = self.api_conn(self.uri, params, log_success=False) LOG.debug('Results are: {0}'.format(resp)) try: resource = resp['results'][0] except IndexError: msg = 'No result found: {0}'.format(name) LOG.warn(msg) raise NoResultFound(msg) if len(resp['results']) > 1: msg = 'More than one result found: {0}'.format(name) LOG.warn(msg) raise RuntimeError(msg) return resource
{ "repo_name": "CityGrid/arsenal", "path": "client/arsenalclient/interface/arsenal_interface.py", "copies": "1", "size": "10982", "license": "apache-2.0", "hash": -7728949540241081000, "line_mean": 36.3537414966, "line_max": 90, "alpha_frac": 0.4999089419, "autogenerated": false, "ratio": 4.8442876047640056, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.0007424048013745876, "num_lines": 294 }
'''Arsenal client ip_address command line helpers. These functions are called directly by args.func() to invoke the appropriate action. They also handle output formatting to the commmand line. ''' # # Copyright 2015 CityGrid Media, LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # from __future__ import print_function import logging from arsenalclient.cli.common import ( check_resp, print_results, ) LOG = logging.getLogger(__name__) def search_ip_addresses(args, client): '''Search for ip_addresses.''' LOG.debug('action_command is: {0}'.format(args.action_command)) LOG.debug('object_type is: {0}'.format(args.object_type)) # Manual updates not allowed from the client. update_fields = [] search_fields = args.fields if any(getattr(args, key) for key in update_fields): search_fields = 'all' resp = None resp = client.object_search(args.object_type, args.search, fields=search_fields, exact_get=args.exact_get, exclude=args.exclude) if not resp.get('results'): return resp results = resp['results'] if args.audit_history: results = client.get_audit_history(results, 'ip_addresses') if not any(getattr(args, key) for key in update_fields): print_results(args, results, skip_keys=['ip_address', 'id'], default_key='ip_address') else: # no direct updates allowed. pass if resp: check_resp(resp) LOG.debug('Complete.')
{ "repo_name": "CityGrid/arsenal", "path": "client/arsenalclient/cli/ip_address.py", "copies": "1", "size": "2103", "license": "apache-2.0", "hash": 5321466039210395000, "line_mean": 30.8636363636, "line_max": 94, "alpha_frac": 0.6514503091, "autogenerated": false, "ratio": 3.9754253308128544, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.0001594896331738437, "num_lines": 66 }
'''Arsenal client ip_addresses command line parser''' # # Copyright 2015 CityGrid Media, LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # from arsenalclient.cli.common import gen_help from arsenalclient.cli.ip_address import ( search_ip_addresses, ) def parser_ip_addresses(top_parser, otsp): '''Add the ip_addresses CLI parser.''' ### ip_addresses object_type parser (iaotp) ia_help = ('Perform actions on the ip_addresses object_type.\n' 'Currently only searching is supported.\n\n') iaotp = otsp.add_parser('ip_addresses', description=ia_help, help=ia_help, parents=[top_parser]) # ip_addresses action sub-parser (iaasp) iaasp = iaotp.add_subparsers(title='Actions', dest='action_command') # ip_addresses search subcommand (iassc) iassc = iaasp.add_parser('search', help='Search for ip_address objects.', parents=[top_parser]) iassc.add_argument('--fields', '-f', dest='fields', help='Comma separated list of fields to display, or \'all\' for all fields.', default=None) iassc.add_argument('--exact', action='store_true', dest='exact_get', default=None, help='Exact match search terms.') iassc.add_argument('--exclude', dest='exclude', default=None, help='Comma separated list of key=value pairs to exclude.') iassc.add_argument('-a', '--audit-history', action='store_true', default=None, help='Show audit history for search results.') iassc.add_argument('search', default=None, metavar='search_terms', help='Comma separated list of key=value pairs to search ' \ 'for.\n {0}'.format(gen_help('ip_addresses_search'))) iassc.set_defaults(func=search_ip_addresses) return top_parser, otsp
{ "repo_name": "CityGrid/arsenal", "path": "client/arsenalclient/parser/ip_addresses.py", "copies": "1", "size": "2807", "license": "apache-2.0", "hash": 1748188771795819500, "line_mean": 40.8955223881, "line_max": 100, "alpha_frac": 0.5557534735, "autogenerated": false, "ratio": 4.399686520376176, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.0015273110097060317, "num_lines": 67 }
'''Arsenal client network_interface command line helpers. These functions are called directly by args.func() to invoke the appropriate action. They also handle output formatting to the commmand line. ''' # # Copyright 2015 CityGrid Media, LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # from __future__ import print_function import logging from arsenalclient.cli.common import ( check_resp, print_results, ) LOG = logging.getLogger(__name__) def search_network_interfaces(args, client): '''Search for network_interfaces.''' LOG.debug('action_command is: {0}'.format(args.action_command)) LOG.debug('object_type is: {0}'.format(args.object_type)) # Manual updates not allowed from the client. update_fields = [] search_fields = args.fields if any(getattr(args, key) for key in update_fields): search_fields = 'all' resp = None resp = client.object_search(args.object_type, args.search, fields=search_fields, exact_get=args.exact_get, exclude=args.exclude) if not resp.get('results'): return resp results = resp['results'] if args.audit_history: results = client.get_audit_history(results, 'network_interfaces') if not any(getattr(args, key) for key in update_fields): print_results(args, results, skip_keys=['unique_id', 'id'], default_key='unique_id') else: # no direct updates allowed. pass if resp: check_resp(resp) LOG.debug('Complete.')
{ "repo_name": "CityGrid/arsenal", "path": "client/arsenalclient/cli/network_interface.py", "copies": "1", "size": "2127", "license": "apache-2.0", "hash": 1832593069079260000, "line_mean": 30.7462686567, "line_max": 92, "alpha_frac": 0.654913023, "autogenerated": false, "ratio": 4.020793950850662, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.00016048788316482107, "num_lines": 67 }
'''Arsenal client network_interfaces command line parser''' # # Copyright 2015 CityGrid Media, LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # from arsenalclient.cli.common import gen_help from arsenalclient.cli.network_interface import ( search_network_interfaces, ) def parser_network_interfaces(top_parser, otsp): '''Add the network_interfaces CLI parser.''' ### network_interfaces object_type parser (niotp) ni_help = ('Perform actions on the network_interfaces object_type.\n' 'Currently only searching is supported.\n\n') niotp = otsp.add_parser('network_interfaces', description=ni_help, help=ni_help, parents=[top_parser]) # network_interfaces action sub-parser (niasp) niasp = niotp.add_subparsers(title='Actions', dest='action_command') # network_interfaces search subcommand (nissc) nissc = niasp.add_parser('search', help='Search for network_interface objects.', parents=[top_parser]) nissc.add_argument('--fields', '-f', dest='fields', help='Comma separated list of fields to display, or \'all\' for all fields.', default=None) nissc.add_argument('--exact', action='store_true', dest='exact_get', default=None, help='Exact match search terms.') nissc.add_argument('--exclude', dest='exclude', default=None, help='Comma separated list of key=value pairs to exclude.') nissc.add_argument('-a', '--audit-history', action='store_true', default=None, help='Show audit history for search results.') nissc.add_argument('search', default=None, metavar='search_terms', help='Comma separated list of key=value pairs to search ' \ 'for.\n {0}'.format(gen_help('network_interfaces_search'))) nissc.set_defaults(func=search_network_interfaces) return top_parser, otsp
{ "repo_name": "CityGrid/arsenal", "path": "client/arsenalclient/parser/network_interfaces.py", "copies": "1", "size": "2887", "license": "apache-2.0", "hash": -1828501700801208300, "line_mean": 42.0895522388, "line_max": 100, "alpha_frac": 0.568063734, "autogenerated": false, "ratio": 4.525078369905956, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5593142103905957, "avg_score": null, "num_lines": null }
'''Arsenal client node command line helpers. These functions are called directly by args.func() to invoke the appropriate action. They also handle output formatting to the commmand line. ''' # # Copyright 2015 CityGrid Media, LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # from __future__ import print_function import logging import json from arsenalclient.cli.common import ( _check_tags, ask_yes_no, check_resp, parse_cli_args, print_results, ) from arsenalclient.authorization import check_root from arsenalclient.version import __version__ LOG = logging.getLogger(__name__) def _get_node_sort_order(node): '''Return a tuple for sorting nodes via datacenter first, then node.''' try: sort_res = (node['name'].split('.')[1], node['name'].split('.')[0]) except IndexError: sort_res = () return sort_res def register(args, client): '''Collect all the data about a node and register it with the server''' client.nodes.register() def enc(args, client): '''Run the External Node Classifier for puppet and return yaml.''' LOG.debug('Triggering node enc.') resp = client.nodes.enc(name=args.name, param_sources=args.inspect) check_resp(resp) results = resp['results'][0] print('---') if results['classes']: print('classes:') for my_class in results['classes']: print('- {0}'.format(my_class)) else: print('classes: null') print('parameters:') for param in results['parameters']: if args.inspect: print(' {0}: {1} # [{2}]'.format(param, results['parameters'][param], results['param_sources'][param])) else: print(' {0}: {1}'.format(param, results['parameters'][param])) print('...') def unique_id(args, client): '''Collect the unique_id of the current node and output it to the command line.''' if check_root(): client.nodes.arsenal_facts.resolve() uid = client.nodes.get_unique_id() if args.json: res = {'unique_id': uid} print(json.dumps(res, indent=4, sort_keys=True)) else: print(uid) def _format_msg(results, tags=None): '''Format the message to be passed to ask_yes_no().''' r_names = [] for node in results: resp = _check_tags(node, tags) if resp: r_names.append('{0}: {1}\n{2}'.format(node['name'], node['unique_id'], resp)) else: r_names.append('{0}: {1}'.format(node['name'], node['unique_id'])) msg = 'We are ready to update the following nodes: ' \ '\n {0}\nContinue?'.format('\n '.join(r_names)) return msg def process_actions(args, client, results): '''Process change actions for node search results.''' resp = None if args.set_tags: msg = _format_msg(results, args.set_tags) if ask_yes_no(msg, args.answer_yes): tags = [tag for tag in args.set_tags.split(',')] for tag in tags: name, value = tag.split('=') resp = client.tags.assign(name, value, 'nodes', results) if args.del_tags: msg = _format_msg(results, args.del_tags) if ask_yes_no(msg, args.answer_yes): tags = [tag for tag in args.del_tags.split(',')] for tag in tags: name, value = tag.split('=') resp = client.tags.deassign(name, value, 'nodes', results) if args.set_status: msg = _format_msg(results) if ask_yes_no(msg, args.answer_yes): resp = client.statuses.assign(args.set_status, 'nodes', results) if args.set_node_groups: msg = _format_msg(results) if ask_yes_no(msg, args.answer_yes): for node_group_name in args.set_node_groups.split(','): resp = client.node_groups.assign(node_group_name, results) if args.del_node_groups: msg = _format_msg(results) if ask_yes_no(msg, args.answer_yes): for node_group_name in args.del_node_groups.split(','): resp = client.node_groups.deassign(node_group_name, results) if args.del_all_node_groups: msg = _format_msg(results) if ask_yes_no(msg, args.answer_yes): resp = client.node_groups.deassign_all(results) return resp def search_nodes(args, client): '''Search for nodes and perform optional assignment actions.''' LOG.debug('action_command is: {0}'.format(args.action_command)) LOG.debug('object_type is: {0}'.format(args.object_type)) resp = None # If we are adding or deleting tags, we need existing tags for comparison. if args.set_tags or args.del_tags: if args.fields: args.fields += ',tags' else: args.fields = 'tags' params = parse_cli_args(args.search, args.fields, args.exact_get, args.exclude) resp = client.nodes.search(params) if not resp.get('results'): return resp results = resp['results'] # Allows for multiple actions to be performed at once. if not any((args.set_tags, args.del_tags, args.set_status, args.set_node_groups, args.del_node_groups, args.del_all_node_groups,)): skip_keys = [ 'name', 'id', 'unique_id', ] if args.audit_history: results = client.nodes.get_audit_history(results) sort_res = sorted(results, key=_get_node_sort_order) print_results(args, sort_res, skip_keys=skip_keys) else: resp = process_actions(args, client, results) if resp: check_resp(resp) LOG.debug('Complete.') def create_node(args, client): '''Create a new node manually in lieu of using the register function. Checks if the node exists (by checking unique_id) first so it can ask if you want to update the existing entry. Can only update the name, status_id, operating_system, or hardware_profile of an existing node. ''' LOG.info('Checking if unique_id exists: unique_id={0}'.format(args.unique_id)) params = { 'unique_id': args.unique_id, 'exact_get': True, } resp = client.nodes.search(params) results = resp['results'] node = { 'unique_id': args.unique_id, 'name': args.node_name, 'status_id': args.status_id, 'operating_system': { 'id': args.operating_system_id, }, 'hardware_profile': { 'id': args.hardware_profile_id, }, } if results: if ask_yes_no('Entry already exists for unique_id: {0}: {1}\n Would you ' \ 'like to update it?'.format(results[0]['name'], results[0]['unique_id']), args.answer_yes): resp = client.nodes.update(node) else: resp = client.nodes.create(node) check_resp(resp) def delete_nodes(args, client): '''Delete existing nodes. Requires a node name, id or unique_id. Since we enforce exact_get, only passing a name would ever possibly yeild more than one result.''' LOG.debug('action_command is: {0}'.format(args.action_command)) LOG.debug('object_type is: {0}'.format(args.object_type)) search = { 'exact_get': True, } if args.node_id: search['id'] = args.node_id if args.node_name: search['name'] = args.node_name if args.unique_id: search['unique_id'] = args.unique_id resp = client.nodes.search(search) results = resp['results'] if results: r_names = [] for node in results: r_names.append('{0}: {1}'.format(node['name'], node['unique_id'])) msg = 'We are ready to delete the following {0}: ' \ '\n{1}\n Continue?'.format(args.object_type, '\n '.join(r_names)) if ask_yes_no(msg, args.answer_yes): for node in results: resp = client.nodes.delete(node) check_resp(resp)
{ "repo_name": "CityGrid/arsenal", "path": "client/arsenalclient/cli/node.py", "copies": "1", "size": "8848", "license": "apache-2.0", "hash": 5048392682679556000, "line_mean": 30.1549295775, "line_max": 95, "alpha_frac": 0.5774186257, "autogenerated": false, "ratio": 3.8039552880481513, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.48813739137481515, "avg_score": null, "num_lines": null }
'''Arsenal client node_group command line helpers. These functions are called directly by args.func() to invoke the appropriate action. They also handle output formatting to the commmand line. ''' # # Copyright 2015 CityGrid Media, LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # from __future__ import print_function import logging from arsenalclient.cli.common import ( ask_yes_no, check_resp, parse_cli_args, print_results, update_object_fields, ) from arsenalclient.exceptions import NoResultFound LOG = logging.getLogger(__name__) def search_node_groups(args, client): '''Search for node_groups and perform optional assignment actions.''' LOG.debug('action_command is: {0}'.format(args.action_command)) LOG.debug('object_type is: {0}'.format(args.object_type)) resp = None update_fields = [ 'node_group_owner', 'node_group_description', 'node_group_notes_url', ] tag_fields = [ 'set_tags', 'del_tags', ] action_fields = update_fields + tag_fields search_fields = args.fields if any(getattr(args, key) for key in update_fields): search_fields = 'all' params = parse_cli_args(args.search, search_fields, args.exact_get, args.exclude) resp = client.node_groups.search(params) if not resp.get('results'): return resp results = resp['results'] if args.audit_history: results = client.node_groups.get_audit_history(results) if not any(getattr(args, key) for key in action_fields): print_results(args, results) else: r_names = [] for node_group in results: r_names.append('name={0},id={1}'.format(node_group['name'], node_group['id'])) msg = 'We are ready to update the following node_groups: \n ' \ '{0}\nContinue?'.format('\n '.join(r_names)) if any(getattr(args, key) for key in update_fields) and ask_yes_no(msg, args.answer_yes): for node_group in results: ng_update = update_object_fields(args, 'node_group', node_group, update_fields) client.node_groups.update(ng_update) if args.set_tags and ask_yes_no(msg, args.answer_yes): tags = [tag for tag in args.set_tags.split(',')] for tag in tags: name, value = tag.split('=') resp = client.tags.assign(name, value, 'node_groups', results) if args.del_tags and ask_yes_no(msg, args.answer_yes): tags = [tag for tag in args.del_tags.split(',')] for tag in tags: name, value = tag.split('=') resp = client.tags.deassign(name, value, 'node_groups', results) if resp: check_resp(resp) LOG.debug('Complete.') def create_node_group(args, client): '''Create a new node_group.''' LOG.info('Checking if node_group name exists: {0}'.format(args.node_group_name)) node_group = { 'name': args.node_group_name, 'owner': args.node_group_owner, 'description': args.node_group_description, 'notes_url': args.node_group_notes_url, } try: result = client.node_groups.get_by_name(args.node_group_name) if ask_yes_no('Entry already exists for node_group name: {0}\n Would you ' \ 'like to update it?'.format(result['name']), args.answer_yes): resp = client.node_groups.update(node_group) except NoResultFound: resp = client.node_groups.create(node_group) check_resp(resp) def delete_node_group(args, client): '''Delete an existing node_group.''' LOG.debug('action_command is: {0}'.format(args.action_command)) LOG.debug('object_type is: {0}'.format(args.object_type)) try: result = client.node_groups.get_by_name(args.node_group_name) msg = 'We are ready to delete the following {0}: ' \ '\n{1}\n Continue?'.format(args.object_type, result['name']) if ask_yes_no(msg, args.answer_yes): resp = client.node_groups.delete(result) check_resp(resp) except NoResultFound: pass
{ "repo_name": "CityGrid/arsenal", "path": "client/arsenalclient/cli/node_group.py", "copies": "1", "size": "4899", "license": "apache-2.0", "hash": -2002702253426868500, "line_mean": 31.66, "line_max": 97, "alpha_frac": 0.600122474, "autogenerated": false, "ratio": 3.791795665634675, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.4891918139634675, "avg_score": null, "num_lines": null }
'''Arsenal client NodeGroups class.''' import logging from arsenalclient.interface.arsenal_interface import ArsenalInterface LOG = logging.getLogger(__name__) class NodeGroups(ArsenalInterface): '''The arsenal client NodeGroups class.''' def __init__(self, **kwargs): super(NodeGroups, self).__init__(**kwargs) self.uri = '/api/node_groups' # Overridden methods def search(self, params=None): '''Search for node_groups. Usage: >>> params = { ... 'name': 'my_node_group', ... 'exact_get': True, ... } >>> NodeGroups.search(params) Args: params (dict): a dictionary of url parameters for the request. Returns: A json response from ArsenalInterface.check_response_codes(). ''' return super(NodeGroups, self).search(params=params) def create(self, params): '''Create a new node_group. Args: params (dict): A dictionary with the following attributes: name : The name of the node_group you wish to create. owner : The email address of the owner of the node group. description: A text description of the members of this node_group. notes_url : A url to documentation relevant to the node_group. Usage: >>> params = { ... 'name': 'my_node_group', ... 'owner': 'email@mycompany.com', ... 'description': 'The nodegroup for all the magical servers', ... 'notes_url': 'https://somurl.somedomain.com/', ... } >>> NodeGroups.create(params) <Response [200]> ''' return super(NodeGroups, self).create(params) def update(self, params): '''Update a node_group. Args: params (dict): A dictionary of url parameters for the request. Usage: Only these params are updatable from this action. >>> params = { ... 'name': 'my_node_group', ... 'owner': 'email@mycompany.com', ... 'description': 'The nodegroup for all the magical servers', ... 'notes_url': 'https://somurl.somedomain.com/', ... } >>> NodeGroups.update(params) Returns: A json response from ArsenalInterface.check_response_codes(). ''' return super(NodeGroups, self).update(params) def delete(self, params): '''Delete a node_group object from the server. Args: params: A node_group dictionary to delete. Must contain the node_group id, and name. Usage: >>> params = { ... 'id': 1, ... 'name': 'my_node_group', ... } >>> NodeGroups.delete(params) ''' return super(NodeGroups, self).delete(params) def get_audit_history(self, results): '''Get the audit history for node_groups.''' return super(NodeGroups, self).get_audit_history(results) def get_by_name(self, name): '''Get a single node_group by it's name. Args: name (str): A string representing the node_group name you wish to find. ''' return super(NodeGroups, self).get_by_name(name) # Custom methods def _manage_assignments(self, node_group, nodes, api_method): '''Assign or de-assign a node_group to/from a list of node dictionaries.''' node_names = [] node_ids = [] msg = 'Assigning' if api_method == 'delete': msg = 'De-assigning' for node in nodes: node_names.append(node['name']) node_ids.append(node['id']) LOG.info('{0} node_group: {1}'.format(msg, node_group['name'])) for node in node_names: LOG.info(' node: {0}'.format(node)) data = { 'nodes': node_ids } return self.api_conn('/api/node_groups/{0}/nodes'.format(node_group['id']), data, method=api_method) def assign(self, name, nodes): '''Assign a node_group to one or more nodes. Args: name (str) : The name of the node_group to assign to the node search results. nodes (list): The list of node dicts from the search results to assign to the node_group. Usage: >>> NodeGroups.node_groups.assign('node_group1', <search results>) <json> ''' try: node_group = self.get_by_name(name) return self._manage_assignments(node_group, nodes, 'put') except IndexError: pass def deassign(self, name, nodes): '''De-assign a node_group from one or more nodes. Args: name (str) : The name of the node_group to de-assign from the node search results. nodes (list): The list of node dicts from the search results to de-assign from the node_group. Usage: >>> NodeGroups.deassign('node_group1', <search results>) <json> ''' try: node_group = self.get_by_name(name) return self._manage_assignments(node_group, nodes, 'delete') except IndexError: pass def deassign_all(self, nodes): '''De-assign ALL node_groups from one or more nodes. Args: nodes (list): The list of node dicts from the search results to de-assign from all node_groups. Usage: >>> NodeGroups.deassign_all(<search results>) <json> ''' node_ids = [] for node in nodes: LOG.info('Removing all node_groups from node: {0}'.format(node['name'])) node_ids.append(node['id']) data = {'node_ids': node_ids} try: resp = self.api_conn('/api/bulk/node_groups/deassign', data, method='delete') except Exception as ex: LOG.error('Command failed: {0}'.format(repr(ex))) raise return resp
{ "repo_name": "CityGrid/arsenal", "path": "client/arsenalclient/interface/node_groups.py", "copies": "1", "size": "6171", "license": "apache-2.0", "hash": -4951871726355318000, "line_mean": 27.7023255814, "line_max": 91, "alpha_frac": 0.5404310485, "autogenerated": false, "ratio": 4.197959183673469, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5238390232173469, "avg_score": null, "num_lines": null }
'''Arsenal client node_groups command line parser''' # # Copyright 2015 CityGrid Media, LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # from arsenalclient.cli.common import gen_help from arsenalclient.cli.node_group import ( search_node_groups, create_node_group, delete_node_group, ) def parser_node_groups(top_parser, otsp): '''Add the node_groups CLI parser.''' ### node_groups object_type parser (ngotp) ng_help = ('Perform actions on the node_groups object_type. Use the \n' 'search action to perform assignment actions such as tagging.\n\n') ngotp = otsp.add_parser('node_groups', description=ng_help, help=ng_help, parents=[top_parser]) # node_groups action sub-parser (ngasp) ngasp = ngotp.add_subparsers(title='Available actions', dest='action_command') # node_groups search subcommand (ngssc) ngssc = ngasp.add_parser('search', help='Search for node_group objects and optionally ' \ 'act upon the results.', parents=[top_parser]) ngssc.add_argument('--fields', '-f', dest='fields', help='Comma separated list of fields to display, or \'all\' for all fields.', default=None) ngssc.add_argument('--exact', action='store_true', dest='exact_get', default=None, help='Exact match search terms.') ngssc.add_argument('--exclude', dest='exclude', default=None, help='Comma separated list of key=value pairs to exclude.') ngssc.add_argument('-a', '--audit-history', action='store_true', default=None, help='Show audit history for search results.') # node_groups update action argument group (anguag) anguag = ngssc.add_argument_group('Update Actions') anguag.add_argument('--description', '-d', dest='node_group_description', help='Update node_group_description.') anguag.add_argument('--owner', '-o', dest='node_group_owner', help='Update node_group_owner.') anguag.add_argument('--notes-url', '-u', dest='node_group_notes_url', help='Update node_group_notes_url.') # node_groups assignment action argument group (angsag) angsag = ngssc.add_argument_group('Assignment Actions') angsag.add_argument('--tag', dest='set_tags', help='Comma separated list of key=value pairs to tag to the node_group.') angsag.add_argument('--del_tag', dest='del_tags', help='Comma separated list of key=value pairs to un-tag from the ' \ 'search results.') ngssc.add_argument('search', default=None, metavar='search_terms', help='Comma separated list of key=value pairs to search ' \ 'for.\n {0}'.format(gen_help('node_groups_search'))) ngssc.set_defaults(func=search_node_groups) # node_groups create subcommand (ngcsc) ngcsc = ngasp.add_parser('create', help='Create node_group objects.', parents=[top_parser]) # required node_group create argument group (rngcag) rngcag = ngcsc.add_argument_group('required arguments') rngcag.add_argument('--name', '-n', required=True, dest='node_group_name', help='node_group_name to create.') rngcag.add_argument('--description', '-d', required=True, dest='node_group_description', help='node_group_description to assign.') rngcag.add_argument('--owner', '-o', required=True, dest='node_group_owner', help='node_group_owner to assign.') rngcag.add_argument('--notes-url', '-u', dest='node_group_notes_url', default=None, help='node_group_notes_url to assign.') rngcag.set_defaults(func=create_node_group) # node_groups delete subcommand (ngdsc) ngdsc = ngasp.add_parser('delete', help='Delete node_group objects.', parents=[top_parser]) # required node_group delete argument group (rngdag) rngdag = ngdsc.add_argument_group('required arguments') rngdag.add_argument('--name', '-n', required=True, dest='node_group_name', help='node_group_name to delete.') ngdsc.set_defaults(func=delete_node_group) return top_parser, otsp
{ "repo_name": "CityGrid/arsenal", "path": "client/arsenalclient/parser/node_groups.py", "copies": "1", "size": "5738", "license": "apache-2.0", "hash": -4243693504866415600, "line_mean": 42.4696969697, "line_max": 100, "alpha_frac": 0.5355524573, "autogenerated": false, "ratio": 4.434312210200927, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.0012022641100289003, "num_lines": 132 }
'''Arsenal client Nodes class.''' import os import re import subprocess import logging from arsenalclient.authorization import check_root from arsenalclient.interface.arsenal_interface import ArsenalInterface from arsenalclient.arsenal_facts import ArsenalFacts LOG = logging.getLogger(__name__) class Nodes(ArsenalInterface): '''The arsenal client Nodes class.''' def __init__(self, **kwargs): super(Nodes, self).__init__(**kwargs) self.uri = '/api/nodes' self.arsenal_facts = ArsenalFacts() # Overridden methods def search(self, params=None): '''Search for nodes. Usage: >>> params = { ... 'name': 'fopp-cbl.*(inf1|lab1)', ... 'status': 'inservice', ... } >>> Nodes.search(params) Args: params (dict): a dictionary of url parameters for the request. Returns: A json response from ArsenalInterface.check_response_codes(). ''' return super(Nodes, self).search(params=params) def create(self, params): '''Create a node. Args: params (dict): A dictionary of url parameters for the request. The following keys are required: unique_id name status_id Usage: >>> params = { ... 'unique_id': 'abc123', ... 'name': 'hostname1.example.com', ... 'status_id': 2, ... 'operating_system': { ... 'id': 1, ... }, ... 'hardware_profile': { ... 'id': 1, ... }, ... } >>> Nodes.create(params) Returns: A json response from ArsenalInterface.check_response_codes(). ''' return super(Nodes, self).create(params) def update(self, params): '''Update a node. Args: params (dict): A dictionary of url parameters for the request. Usage: Only the params in the example are updatable from this action. >>> params = { ... 'unique_id': 'abc123', ... 'name': 'hostname1.example.com', ... 'status_id': 4, ... 'operating_system': { ... 'id': 1, ... }, ... 'hardware_profile': { ... 'id': 1, ... }, ... } >>> Nodes.update(params) Returns: A json response from ArsenalInterface.check_response_codes(). ''' return super(Nodes, self).update(params) def delete(self, params): '''Delete a node object from the server. Args: params: A node dictionary to delete. Must contain the node id, unique_id, and name. Usage: >>> params = { ... 'id': 56, ... 'unique_id': 'abc123', ... 'name': 'hostname1.example.com', ... } >>> Nodes.delete(params) ''' return super(Nodes, self).delete(params) def get_audit_history(self, results): '''Get the audit history for nodes.''' return super(Nodes, self).get_audit_history(results) def get_by_name(self, name): '''Get a single node by it's name. Args: name (str): A string representing the node name you wish to find. ''' return super(Nodes, self).get_by_name(name) # Custom methods def register(self): '''Collect all the data about a node and register it with the server. ''' LOG.debug('Triggering node registration...') if check_root(): LOG.debug('Overriding login for node registration to: kaboom') self.authorization.user_login = 'kaboom' my_cookie = '/root/.{0}_kaboom_cookie'.format(self.settings.api_host) LOG.debug('Overriding setting for user kaboom: ' 'cookie_file={0}'.format(my_cookie)) self.authorization.cookie_file = my_cookie node = self.collect() LOG.info('Registering node name: {0} unique_id: {1}'.format(node['name'], node['unique_id'])) resp = self.api_conn('/api/register', node, method='put') return resp def collect(self): '''Collect all data about a node for registering with the server.''' LOG.debug('Collecting data for node.') resp = {} resp['network_interfaces'] = [] resp['data_center'] = {} resp['guest_vms'] = [] resp['ec2'] = None self.arsenal_facts.resolve() facts = self.arsenal_facts.facts resp['name'] = facts['networking']['fqdn'] unique_id = self.get_unique_id() resp['unique_id'] = unique_id resp['hardware_profile'] = self.get_hardware_profile() resp['operating_system'] = self.get_operating_system() resp['data_center']['name'] = facts['data_center']['name'] if facts['ec2']['instance_id']: LOG.debug('This is an Ec2 instance.') resp['ec2'] = facts['ec2'] resp['uptime'] = facts['uptime'] if facts['hardware']['serial_number']: resp['serial_number'] = facts['hardware']['serial_number'] if facts['processors']['count']: resp['processor_count'] = facts['processors']['count'] for net_if in facts['networking']['interfaces']: my_attribs = facts['networking']['interfaces'][net_if] # Use the node's unqiue_id prefixed with the interface name if it # doesn't have a mac address of it's own (bond, sit, veth, etc.). if not 'unique_id' in my_attribs: uid = '{0}_{1}'.format(net_if, unique_id) my_attribs['unique_id'] = uid # Set the bond IP on it's slaves too. else: my_master = my_attribs.get('bond_master') if my_master: try: my_ip = facts['networking']['interfaces'][my_master]['ip_address'] my_attribs['ip_address'] = my_ip except KeyError: pass my_attribs['name'] = net_if resp['network_interfaces'].append(my_attribs) if facts['guest_vms']: resp['guest_vms'] = facts['guest_vms'] return resp def get_hardware_profile(self): '''Collect all the information about the node's hardware_profile. Required for node registration.''' resp = { 'manufacturer': 'Unknown', 'model': 'Unknown', 'name': 'Unknown', } self.arsenal_facts.resolve() facts = self.arsenal_facts.facts try: resp['manufacturer'] = facts['hardware']['manufacturer'] resp['model'] = facts['hardware']['product_name'] resp['name'] = facts['hardware']['name'] except KeyError: LOG.error('Unable to determine hardware_profile.') return resp def get_operating_system(self): '''Collect all the information about the node's operating_system. Required for node registration.''' resp = { 'name': 'Unknown', 'variant': 'Unknown', 'version_number': 'Unknown', 'architecture': 'Unknown', 'description': 'Unknown', } self.arsenal_facts.resolve() facts = self.arsenal_facts.facts try: resp['name'] = facts['os']['name'] resp['variant'] = facts['os']['variant'] resp['version_number'] = facts['os']['version_number'] resp['architecture'] = facts['os']['architecture'] resp['description'] = facts['os']['description'] except KeyError: LOG.error('Unable to determine operating_system.') return resp @staticmethod def get_uuid_from_dmidecode(): '''Gets the uuid of a node from dmidecode if available. Returns a string if found, None otherwise. Also skips known bad output from dmidecode that is not unique.''' bogus_uuids = [ '03000200-0400-0500-0006-000700080009', 'Not Settable', ] unique_id = None file_null = open(os.devnull, 'w') proc = subprocess.Popen(['/usr/sbin/dmidecode', '-s', 'system-uuid'], stdout=subprocess.PIPE, stderr=file_null) proc.wait() uuid = proc.stdout.readlines() if uuid: strip_uuid = uuid[-1].rstrip() if strip_uuid in bogus_uuids: LOG.warn('unique_id from dmidecode is known bad: {0}'.format(strip_uuid)) else: unique_id = strip_uuid else: # Support older versions of dmidecode proc = subprocess.Popen(['/usr/sbin/dmidecode', '-t', '1'], stdout=subprocess.PIPE) proc.wait() dmidecode_out = proc.stdout.readlines() xen_match = "\tUUID: " for line in dmidecode_out: if re.match(xen_match, line): strip_uuid = line[7:].rstrip() if strip_uuid in bogus_uuids: LOG.warn('unique_id from dmidecode is known bad: {0}'.format(strip_uuid)) else: unique_id = strip_uuid return unique_id def get_unique_id(self): '''Determines the unique_id of a node and returns it as a string.''' if not check_root(): return None LOG.debug('Determining unique_id...') facts = self.arsenal_facts.facts unique_id = facts['networking']['mac_address'] if facts['os']['kernel'] == 'Linux' or facts['os']['kernel'] == 'FreeBSD': if facts['ec2']['instance_id']: unique_id = facts['ec2']['instance_id'] LOG.debug('unique_id is from ec2 instance_id: {0}'.format(unique_id)) elif facts['hardware']['name'] == 'Red Hat KVM': LOG.debug('unique_id is from mac address: {0}'.format(unique_id)) elif os.path.isfile('/usr/sbin/dmidecode'): unique_id = self.get_uuid_from_dmidecode() if unique_id: LOG.debug('unique_id is from dmidecode: {0}'.format(unique_id)) else: unique_id = facts['networking']['mac_address'] LOG.debug('unique_id is from mac address: {0}'.format(unique_id)) else: LOG.debug('unique_id is from mac address: {0}'.format(unique_id)) else: LOG.debug('unique_id is from mac address: {0}'.format(unique_id)) return unique_id def enc(self, name, param_sources=None): '''Run the puppet node enc. Returns a dict. Args: name : The fqdn of the node (required) param_sources: A boolean that controls whether or not to return data about what level of the hierarchy each variable comes from. Defaults to False. ''' LOG.verbose('Running puppet ENC for node name: {0}'.format(name)) data = { 'name': name, } if param_sources: data['param_sources'] = True resp = self.api_conn('/api/enc', data, log_success=False) return resp
{ "repo_name": "CityGrid/arsenal", "path": "client/arsenalclient/interface/nodes.py", "copies": "1", "size": "11602", "license": "apache-2.0", "hash": -3541024768666615300, "line_mean": 31.6816901408, "line_max": 97, "alpha_frac": 0.5200827444, "autogenerated": false, "ratio": 4.245151847786316, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5265234592186316, "avg_score": null, "num_lines": null }
'''Arsenal client nodes command line parser''' # # Copyright 2015 CityGrid Media, LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # from arsenalclient.cli.common import gen_help from arsenalclient.cli.node import ( enc, search_nodes, create_node, delete_nodes, ) def parser_nodes(top_parser, otsp): '''Add the nodes CLI parser.''' ### nodes object_type parser (notp) n_help = ('Perform actions on the nodes object_type. Use the search \n' 'action to perform assignment actions such as tagging, \n' 'assigning node_groups, and setting status.\n\n') notp = otsp.add_parser('nodes', description=n_help, help=n_help, parents=[top_parser]) # nodes action sub-parser (nasp) nasp = notp.add_subparsers(title='Actions', dest='action_command') # nodes enc subcommand (nesc) nesc = nasp.add_parser('enc', help='Run the puppet ENC.', parents=[top_parser]) nesc.add_argument('--name', '-n', dest='name', help='The fqdn of the node to search for.', required=True, default=None) nesc.add_argument('--inspect', dest='inspect', action='store_true', default=None, help='Print what level of the hierarchy the variable ' \ 'comes from in brackets after each variable.') nesc.set_defaults(func=enc) # nodes search subcommand (nssc) nssc = nasp.add_parser('search', help='Search for node objects and optionally act upon the results.', parents=[top_parser]) nssc.add_argument('--fields', '-f', dest='fields', help='Comma separated list of fields to display, or \'all\' for all fields.', default=None) nssc.add_argument('--exact', action='store_true', dest='exact_get', default=None, help='Exact match search terms.') nssc.add_argument('--exclude', dest='exclude', default=None, help='Comma separated list of key=value pairs to exclude.') nssc.add_argument('-a', '--audit-history', action='store_true', default=None, help='Show audit history for search results.') # nodes assignment action argument group (ansqg) ansag = nssc.add_argument_group('Assignment Actions') ansag.add_argument('--status', dest='set_status', help='status to assign to the search results.') ansag.add_argument('--tag', dest='set_tags', help='Comma separated list of key=value pairs to tag to the search results.') ansag.add_argument('--del_tag', dest='del_tags', help='Comma separated list of key=value pairs to un-tag from ' \ 'the search results.') ansag.add_argument('--node_groups', dest='set_node_groups', help='Comma separated list of node_groups to assign to the search results.') ansag.add_argument('--del_node_groups', dest='del_node_groups', help='Comma separated list of node_groups to de-assign from the ' \ 'search results.') ansag.add_argument('--del_all_node_groups', dest='del_all_node_groups', action='store_true', help='De-assign ALL node_groups from the search results.') nssc.add_argument('search', default=None, metavar='search_terms', help='Comma separated list of key=value pairs to search ' \ 'for.\n {0}'.format(gen_help('nodes_search'))) nssc.set_defaults(func=search_nodes) # nodes create subcommand (ncsc) ncsc = nasp.add_parser('create', description='Create node objects.', help='Create node objects.', parents=[top_parser]) # nodes required argument group (rncag) rncag = ncsc.add_argument_group('required arguments') ncsc.add_argument('--hardware_profile_id', '-hp', dest='hardware_profile_id', help='hardware_profile_id to assign.', default=1,) ncsc.add_argument('--operating_system_id', '-os', dest='operating_system_id', help='operating_system_id to assign.', default=1,) rncag.add_argument('--name', '-n', required=True, dest='node_name', help='node_name to create') rncag.add_argument('--unique_id', '-u', required=True, dest='unique_id', help='unique_id to assign.') rncag.add_argument('--status_id', '-s', required=True, dest='status_id', help='status_id to assign.') rncag.set_defaults(func=create_node) # nodes delete subcommand (ndsc) ndsc = nasp.add_parser('delete', help='Delete node objects. At least one of name, unique_id, ' \ 'or id is required', parents=[top_parser]) ndsc.add_argument('--name', '-n', dest='node_name', help='node_name to delete.') ndsc.add_argument('--unique_id', '-u', dest='unique_id', help='unique_id to delete.') ndsc.add_argument('--id', '-i', dest='node_id', help='node id to delete.') ndsc.set_defaults(func=delete_nodes) return top_parser, otsp
{ "repo_name": "CityGrid/arsenal", "path": "client/arsenalclient/parser/nodes.py", "copies": "1", "size": "6854", "license": "apache-2.0", "hash": -5170428775422378000, "line_mean": 41.5714285714, "line_max": 100, "alpha_frac": 0.5068573096, "autogenerated": false, "ratio": 4.584615384615384, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5591472694215384, "avg_score": null, "num_lines": null }
'''Arsenal client physical_device command line helpers. These functions are called directly by args.func() to invoke the appropriate action. They also handle output formatting to the commmand line. ''' # # Copyright 2015 CityGrid Media, LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # from __future__ import print_function import logging import sys import csv import json from arsenalclient.cli.common import ( _check_tags, ask_yes_no, check_resp, parse_cli_args, print_results, update_object_fields, ) from arsenalclient.exceptions import NoResultFound LOG = logging.getLogger(__name__) UPDATE_FIELDS = [ 'hardware_profile', 'mac_address_1', 'mac_address_2', 'oob_ip_address', 'oob_mac_address', 'physical_elevation', 'physical_location', 'physical_rack', ] TAG_FIELDS = [ 'set_tags', 'del_tags', ] def _format_msg(results, tags=None): '''Format the message to be passed to ask_yes_no().''' r_names = [] for res in results: resp = _check_tags(res, tags) if resp: r_names.append('{0}\n{1}'.format(res['serial_number'], resp)) else: r_names.append('{0}'.format(res['serial_number'])) msg = 'We are ready to update the following physical_devices: ' \ '\n {0}\nContinue?'.format('\n '.join(r_names)) return msg def process_actions(args, client, results): '''Process change actions for physical_devices search results.''' resp = None if args.set_tags: msg = _format_msg(results, args.set_tags) if ask_yes_no(msg, args.answer_yes): tags = [tag for tag in args.set_tags.split(',')] for tag in tags: name, value = tag.split('=') resp = client.tags.assign(name, value, 'physical_devices', results) if args.del_tags: msg = _format_msg(results, args.del_tags) if ask_yes_no(msg, args.answer_yes): tags = [tag for tag in args.del_tags.split(',')] for tag in tags: name, value = tag.split('=') resp = client.tags.deassign(name, value, 'physical_devices', results) if any(getattr(args, key) for key in UPDATE_FIELDS): msg = _format_msg(results) if ask_yes_no(msg, args.answer_yes): for physical_device in results: pd_update = update_object_fields(args, 'physical_device', physical_device, UPDATE_FIELDS) client.physical_devices.update(pd_update) return resp def search_physical_devices(args, client): '''Search for physical_devices and perform optional assignment actions.''' LOG.debug('action_command is: {0}'.format(args.action_command)) LOG.debug('object_type is: {0}'.format(args.object_type)) resp = None action_fields = UPDATE_FIELDS + TAG_FIELDS search_fields = args.fields # If we are adding or deleting tags, we need existing tags for comparison. if args.set_tags or args.del_tags: if search_fields: search_fields += ',tags' else: search_fields = 'tags' if any(getattr(args, key) for key in UPDATE_FIELDS): search_fields = 'all' params = parse_cli_args(args.search, search_fields, args.exact_get, args.exclude) resp = client.physical_devices.search(params) if not resp.get('results'): return resp results = resp['results'] # Allows for multiple actions to be performed at once. if not any(getattr(args, key) for key in action_fields): if args.audit_history: results = client.physical_devices.get_audit_history(results) print_results(args, results, default_key='serial_number', skip_keys=['serial_number', 'id']) else: resp = process_actions(args, client, results) if resp: check_resp(resp) LOG.debug('Complete.') def tag_physical_device_import(client, set_tags, results): '''Tag a physical device that is newly created by the import tool with any tags that were provided in the csv file.''' tags = [tag for tag in set_tags.split('|')] for tag in tags: name, value = tag.split('=') resp = client.tags.assign(name, value, 'physical_devices', results) LOG.debug('Tag response: {0}'.format(resp)) def create_physical_device(args, client, device=None): '''Create a new physical_device.''' try: serial_number = device['serial_number'] import_tool = True except TypeError: import_tool = False serial_number = args.serial_number device = { 'hardware_profile': args.hardware_profile, 'mac_address_1': args.mac_address_1, 'mac_address_2': args.mac_address_2, 'oob_ip_address': args.oob_ip_address, 'oob_mac_address': args.oob_mac_address, 'physical_elevation': args.physical_elevation, 'physical_location': args.physical_location, 'physical_rack': args.physical_rack, 'serial_number': args.serial_number, } LOG.info('Checking if physical_device serial_number exists: {0}'.format(serial_number)) try: resp = client.physical_devices.get_by_serial_number(serial_number) if ask_yes_no('Entry already exists for physical_device name: {0}\n Would you ' \ 'like to update it?'.format(resp['serial_number']), args.answer_yes): resp = client.physical_devices.update(device) LOG.debug('Update response is: {0}'.format(resp)) if import_tool: try: set_tags = device['tags'] tag_physical_device_import(client, set_tags, resp['results']) except KeyError: pass return resp else: return check_resp(resp) except NoResultFound: resp = client.physical_devices.create(device) LOG.debug('Create response is: {0}'.format(resp)) if import_tool: try: set_tags = device['tags'] tag_physical_device_import(client, set_tags, resp['results']) except KeyError: pass return resp else: return check_resp(resp) def delete_physical_device(args, client): '''Delete an existing physical_device.''' LOG.debug('action_command is: {0}'.format(args.action_command)) LOG.debug('object_type is: {0}'.format(args.object_type)) try: results = client.physical_devices.get_by_serial_number(args.physical_device_serial_number) msg = 'We are ready to delete the following {0}: ' \ '\n{1}\n Continue?'.format(args.object_type, results['serial_number']) if ask_yes_no(msg, args.answer_yes): resp = client.physical_devices.delete(results) check_resp(resp) except NoResultFound: LOG.info('Nothing to do.') def import_physical_device(args, client): '''Import physical_devices from a csv file.''' LOG.info('Beginning physical_device import from file: {0}'.format(args.physical_device_import)) LOG.debug('action_command is: {0}'.format(args.action_command)) LOG.debug('object_type is: {0}'.format(args.object_type)) failures = [] overall_exit = 0 try: with open(args.physical_device_import) as csv_file: field_names = [ 'serial_number', 'physical_location', 'physical_rack', 'physical_elevation', 'mac_address_1', 'mac_address_2', 'hardware_profile', 'oob_ip_address', 'oob_mac_address', 'tags', ] device_import = csv.DictReader(csv_file, delimiter=',', fieldnames=field_names) for count, row in enumerate(device_import): if row['serial_number'].startswith('#'): continue LOG.info('Processing row: {0}...'.format(count)) row = check_null_fields(row, field_names) LOG.debug(json.dumps(row, indent=4, sort_keys=True)) resp = create_physical_device(args, client, device=row) LOG.debug(json.dumps(resp, indent=4, sort_keys=True)) if not resp: continue if resp['http_status']['code'] != 200: resp['http_status']['row'] = row resp['http_status']['row_number'] = count failures.append(resp['http_status']) if failures: overall_exit = 1 LOG.error('The following rows were unable to be processed:') for fail in failures: LOG.error(' Row: {0} Data: {1} Error: {2}'.format(fail['row_number'], fail['row'], fail['message'],)) LOG.info('physical_device import complete') sys.exit(overall_exit) except IOError as ex: LOG.error(ex) def export_check_optional(param): '''Checks if an optional param exists or not during export. Sets to empty string if not, otherwise returns the param as-is.''' if not param or param == 'None': return '' return param def export_physical_device(args, client): '''Export physical_devices to standard out or a csv file.''' LOG.info('Beginning physical_device export...') params = parse_cli_args(args.search, 'all') if 'physical_location.name' not in params: LOG.error('physical_location.name search parameter is required') sys.exit(1) resp = client.physical_devices.search(params) if not resp['results']: return LOG.info('Found {0} device(s).'.format(resp['meta']['total'])) LOG.debug(json.dumps(resp, indent=4, sort_keys=True)) all_results = [] for result in resp['results']: my_device = [ result['serial_number'], result['physical_location']['name'], result['physical_rack']['name'], str(result['physical_elevation']['elevation']), result['mac_address_1'], export_check_optional(result['mac_address_2']), export_check_optional(result['hardware_profile']['name']), result['oob_ip_address'], result['oob_mac_address'], ] joined_tags = '' for tag in result['tags']: joined_tags += '{0}={1}|'.format(tag['name'], tag['value']) joined_tags = joined_tags.rstrip('|') if joined_tags: my_device.append(joined_tags) line = ','.join(my_device) if args.export_csv: all_results.append(line) else: print(line) if all_results: LOG.info('Writing results to csv: {0}'.format(args.export_csv)) with open(args.export_csv, 'w') as the_file: for result in all_results: the_file.write('{0}\n'.format(result)) def check_null_fields(row, field_names): '''Checks for keys will null values and removes them. This allows the API to return appropriate errors for keys that require a value.''' for key in field_names: if not row[key]: del row[key] return row
{ "repo_name": "CityGrid/arsenal", "path": "client/arsenalclient/cli/physical_device.py", "copies": "1", "size": "12176", "license": "apache-2.0", "hash": -3821003417314332700, "line_mean": 33.106442577, "line_max": 100, "alpha_frac": 0.5767904074, "autogenerated": false, "ratio": 4.054612054612055, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.001123949956271023, "num_lines": 357 }
'''Arsenal client PhysicalDevices class.''' import logging from arsenalclient.exceptions import NoResultFound from arsenalclient.interface.arsenal_interface import ArsenalInterface LOG = logging.getLogger(__name__) class PhysicalDevices(ArsenalInterface): '''The arsenal client PhysicalDevices class.''' def __init__(self, **kwargs): super(PhysicalDevices, self).__init__(**kwargs) self.uri = '/api/physical_devices' # Overridden methods def search(self, params=None): '''Search for physical_devices. Usage: >>> params = { ... 'serial_number': 'AA11BB22CC34', ... 'exact_get': True, ... } >>> PhysicalDevices.search(params) Args: params (dict): a dictionary of url parameters for the request. Returns: A json response from ArsenalInterface.check_response_codes(). ''' return super(PhysicalDevices, self).search(params) def create(self, params): '''Create a new physical_device. Args: params (dict): A dictionary with the following attributes: serial_number : The serial_number of the physical_device you wish to create. Usage: >>> params = { ... 'serial_number': 'AA11BB22CC34', ... } >>> PhysicalDevices.create(params) <Response [200]> ''' return super(PhysicalDevices, self).create(params) def update(self, params): '''Update a physical_device. Args: params (dict): A dictionary of url parameters for the request. Usage: Only the params in the example are updatable from this action. >>> params = { ... 'serial_number': 'AA11BB22CC34', ... 'physical_elevation': 7, ... 'physical_location': 'SCIF 4', ... 'physical_rack': 'R200', ... 'hardware_profile': 'HP ProLiant DL360 Gen9', ... 'oob_ip_address': '10.0.0.1', ... 'oob_mac_address': 'aa:bb:cc:11:22:33', ... } >>> PhysicalDevices.update(params) Returns: A json response from ArsenalInterface.check_response_codes(). ''' return super(PhysicalDevices, self).update(params) def delete(self, params): '''Delete a physical_device object from the server. Args: params: A physical_device dictionary to delete. Must contain the physical_device id, and name. Usage: >>> params = { ... 'id': 1, ... 'serial_number': 'AA11BB22CC34', ... } >>> PhysicalDevices.delete(params) ''' return super(PhysicalDevices, self).delete(params) def get_audit_history(self, results): '''Get the audit history for physical_devices.''' return super(PhysicalDevices, self).get_audit_history(results) def get_by_name(self, name): '''Get a single physical_device by it's name. This is not possible as physical_devices don't have a name. Use PhysicalDevices.get_by_serial_number() instead. ''' pass # Custom methods def get_by_serial_number(self, serial_number): '''Get a single physical_device from the server based on it's serial_number.''' LOG.debug('Searching for physical_device serial_number: {0}'.format(serial_number)) data = { 'serial_number': serial_number, 'exact_get': True, } resp = self.api_conn('/api/physical_devices', data, log_success=False) LOG.debug('Results are: {0}'.format(resp)) try: resource = resp['results'][0] except IndexError: msg = 'Physical Device not found: {0}'.format(serial_number) LOG.info(msg) raise NoResultFound(msg) if len(resp['results']) > 1: msg = 'More than one result found: {0}'.format(serial_number) LOG.error(msg) raise RuntimeError(msg) return resource
{ "repo_name": "CityGrid/arsenal", "path": "client/arsenalclient/interface/physical_devices.py", "copies": "1", "size": "4086", "license": "apache-2.0", "hash": -1589771902121644500, "line_mean": 28.8248175182, "line_max": 91, "alpha_frac": 0.5746451297, "autogenerated": false, "ratio": 4.152439024390244, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5227084154090244, "avg_score": null, "num_lines": null }
'''Arsenal client physical_devices command line parser''' # # Copyright 2015 CityGrid Media, LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # from arsenalclient.cli.common import gen_help from arsenalclient.cli.physical_device import ( search_physical_devices, create_physical_device, delete_physical_device, import_physical_device, export_physical_device, ) def parser_physical_devices(top_parser, otsp): '''Add the physical_devices CLI parser.''' ### physical_devices object_type parser (otp) my_help = ('Perform actions on the physical_devices object_type. Use the \n' 'search action to perform assignment actions such as tagging.\n\n') otp = otsp.add_parser('physical_devices', description=my_help, help=my_help, parents=[top_parser]) # physical_devices action sub-parser (asp) asp = otp.add_subparsers(title='Available actions', dest='action_command') # physical_devices search subcommand (ssc) ssc = asp.add_parser('search', help='Search for physical_device objects and optionally ' \ 'act upon the results.', parents=[top_parser]) ssc.add_argument('--fields', '-f', dest='fields', help='Comma separated list of fields to display, or \'all\' for all fields.', default=None) ssc.add_argument('--exact', action='store_true', dest='exact_get', default=None, help='Exact match search terms.') ssc.add_argument('--exclude', dest='exclude', default=None, help='Comma separated list of key=value pairs to exclude.') ssc.add_argument('-a', '--audit-history', action='store_true', default=None, help='Show audit history for search results.') # physical_devices update action argument group (uaag) uaag = ssc.add_argument_group('Update Actions') uaag.add_argument('-e', '--elevation', dest='physical_elevation', help='Update physical_device elevation. Changing this ' \ 'also requires location and rack to be specified.') uaag.add_argument('-H', '--hardware-profile', help='Update physical_device hardware_profile.') uaag.add_argument('-i', '--oob-ip-address', help='Update physical_device oob_ip_address.') uaag.add_argument('-l', '--location', dest='physical_location', help='Update physical_device location. Changing this ' \ 'also requires rack and elevation to be specified.') uaag.add_argument('-m', '--oob-mac-address', help='Update physical_device oob_mac_address.') uaag.add_argument('-m1', '--mac-address-1', help='Update the mac address of the first network ' \ 'interface of the physical_device.') uaag.add_argument('-m2', '--mac-address-2', help='Update the mac address of the first network ' \ 'interface of the physical_device.') uaag.add_argument('-r', '--rack', dest='physical_rack', help='Update physical_device rack. Changing this ' \ 'also requires location and elevation to be specified.') # physical_devices assignment action argument group (aag) aag = ssc.add_argument_group('Assignment Actions') aag.add_argument('--tag', dest='set_tags', help='Comma separated list of key=value pairs to tag to ' \ 'the search results.') aag.add_argument('--del_tag', dest='del_tags', help='Comma separated list of key=value pairs to un-tag from the ' \ 'search results.') ssc.add_argument('search', default=None, metavar='search_terms', help='Comma separated list of key=value pairs to search ' \ 'for.\n {0}'.format(gen_help('physical_devices_search'))) ssc.set_defaults(func=search_physical_devices) # physical_devices create subcommand (csc) csc = asp.add_parser('create', help='Create physical_device objects.', parents=[top_parser]) # required physical_device create argument group (rcag) rcag = csc.add_argument_group('required arguments') rcag.add_argument('-s', '--serial-number', required=True, help='physical device serial number to create.') rcag.add_argument('-e', '--elevation', dest='physical_elevation', required=True, help='The physical device elevation number.') rcag.add_argument('-H', '--hardware-profile', help='The physical device hardware profile name.') rcag.add_argument('-i', '--oob-ip-address', help='The physical device out of band ip address.') rcag.add_argument('-l', '--location', dest='physical_location', required=True, help='The physical device location name.') rcag.add_argument('-m', '--oob-mac-address', help='The physical device out of band mac address.') rcag.add_argument('-m1', '--mac-address-1', help='The mac address of the first network ' \ 'interface of the physical_device.') rcag.add_argument('-m2', '--mac-address-2', help='The mac address of the first network ' \ 'interface of the physical_device.') rcag.add_argument('-r', '--rack', dest='physical_rack', required=True, help='The physical device rack name.') rcag.set_defaults(func=create_physical_device) # physical_devices delete subcommand (dsc) dsc = asp.add_parser('delete', help='Delete physical_device objects.', parents=[top_parser]) # required physical_device delete argument group (rdag) rdag = dsc.add_argument_group('required arguments') rdag.add_argument('-s', '--serial-number', required=True, dest='physical_device_serial_number', help='physical_device_serial_number to delete.') dsc.set_defaults(func=delete_physical_device) # physical_devices import subcommand (isc) isc = asp.add_parser('import', help='Import physical_device objects from a csv.', parents=[top_parser]) # required physical_device import argument group (risc) risc = isc.add_argument_group('required arguments') risc.add_argument('-c', '--csv', required=True, dest='physical_device_import', help='Full filesystem path to the csv file to import ' 'physical devices from.') isc.set_defaults(func=import_physical_device) # physical_devices export subcommand (esc) esc = asp.add_parser('export', help='Export physical_device objects to stdout or a csv.', parents=[top_parser]) esc.add_argument('search', default=None, metavar='search_terms', help='Comma separated list of key=value pairs to search ' \ 'for.\n {0}'.format(gen_help('physical_devices_search'))) # required physical_device export argument group (resc) resc = esc.add_argument_group('required arguments') resc.add_argument('-c', '--csv', dest='export_csv', help='Full filesystem path to the csv file to export ' 'physical devices to. If unspecified it will print to ' 'standard out') esc.set_defaults(func=export_physical_device) return top_parser, otsp
{ "repo_name": "CityGrid/arsenal", "path": "client/arsenalclient/parser/physical_devices.py", "copies": "1", "size": "9444", "license": "apache-2.0", "hash": -8187935576948143000, "line_mean": 42.3211009174, "line_max": 98, "alpha_frac": 0.527742482, "autogenerated": false, "ratio": 4.806106870229008, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.0014387178188473688, "num_lines": 218 }
'''Arsenal client physical_elevation command line helpers. These functions are called directly by args.func() to invoke the appropriate action. They also handle output formatting to the commmand line. ''' # # Copyright 2015 CityGrid Media, LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # from __future__ import print_function import logging from arsenalclient.cli.common import ( _check_tags, ask_yes_no, check_resp, parse_cli_args, print_results, update_object_fields, ) from arsenalclient.exceptions import NoResultFound LOG = logging.getLogger(__name__) UPDATE_FIELDS = [ 'physical_location', 'physical_rack', ] def _format_msg(results, tags=None): '''Format the message to be passed to ask_yes_no().''' r_names = [] for res in results: resp = _check_tags(res, tags) if resp: r_names.append('{0}\n{1}'.format(res['name'], resp)) else: r_names.append('{0}'.format(res['name'])) msg = 'We are ready to update the following physical_elevations: ' \ '\n {0}\nContinue?'.format('\n '.join(r_names)) return msg def process_actions(args, client, results): '''Process change actions for physical_elevations search results.''' resp = None if any(getattr(args, key) for key in UPDATE_FIELDS): msg = _format_msg(results) if ask_yes_no(msg, args.answer_yes): for physical_elevation in results: pd_update = update_object_fields(args, 'physical_elevation', physical_elevation, UPDATE_FIELDS) client.physical_elevations.update(pd_update) return resp def search_physical_elevations(args, client): '''Search for physical_elevations and perform optional assignment actions.''' LOG.debug('action_command is: {0}'.format(args.action_command)) LOG.debug('object_type is: {0}'.format(args.object_type)) resp = None action_fields = UPDATE_FIELDS search_fields = args.fields if any(getattr(args, key) for key in UPDATE_FIELDS): search_fields = 'all' params = parse_cli_args(args.search, search_fields, args.exact_get, args.exclude) resp = client.physical_elevations.search(params) if not resp.get('results'): return resp results = resp['results'] # Allows for multiple actions to be performed at once. if not any(getattr(args, key) for key in action_fields): if args.audit_history: results = client.physical_elevations.get_audit_history(results) print_results(args, results, default_key='elevation', skip_keys=['elevation', 'id']) else: resp = process_actions(args, client, results) if resp: check_resp(resp) LOG.debug('Complete.') def create_physical_elevation(args, client): '''Create a new physical_elevation.''' LOG.info('Checking if physical_elevation name exists: {0}'.format(args.physical_elevation)) device = { 'elevation': args.physical_elevation, 'physical_location': args.physical_location, 'physical_rack': args.physical_rack, } try: resp = client.physical_elevations.get_by_loc_rack_el(args.physical_location, args.physical_rack, args.physical_elevation) if ask_yes_no('Entry already exists for physical_elevation name: {0}\n Would you ' \ 'like to update it?'.format(resp['name']), args.answer_yes): resp = client.physical_elevations.update(device) check_resp(resp) except NoResultFound: resp = client.physical_elevations.create(device) check_resp(resp) def delete_physical_elevation(args, client): '''Delete an existing physical_elevation.''' LOG.debug('action_command is: {0}'.format(args.action_command)) LOG.debug('object_type is: {0}'.format(args.object_type)) results = client.physical_elevations.get_by_name(args.physical_elevation_name) if results: r_names = [] for physical_elevations in results: r_names.append(physical_elevations['name']) msg = 'We are ready to delete the following {0}: ' \ '\n{1}\n Continue?'.format(args.object_type, '\n '.join(r_names)) if ask_yes_no(msg, args.answer_yes): for physical_elevation in results: resp = client.physical_elevations.delete(physical_elevation) check_resp(resp)
{ "repo_name": "CityGrid/arsenal", "path": "client/arsenalclient/cli/physical_elevation.py", "copies": "1", "size": "5293", "license": "apache-2.0", "hash": 151336408412449180, "line_mean": 31.472392638, "line_max": 95, "alpha_frac": 0.614018515, "autogenerated": false, "ratio": 4.074672825250192, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5188691340250192, "avg_score": null, "num_lines": null }
'''Arsenal client PhysicalElevations class.''' import logging from arsenalclient.interface.arsenal_interface import ArsenalInterface from arsenalclient.exceptions import NoResultFound LOG = logging.getLogger(__name__) class PhysicalElevations(ArsenalInterface): '''The arsenal client PhysicalElevations class.''' def __init__(self, **kwargs): super(PhysicalElevations, self).__init__(**kwargs) self.uri = '/api/physical_elevations' # Overridden methods def search(self, params=None): '''Search for physical_elevations. Usage: >>> params = { ... 'elevation': 2, ... 'physical_location': 'TEST DC SCIF 1', ... 'exact_get': True, ... } >>> PhysicalElevations.search(params) Args: params (dict): a dictionary of url parameters for the request. Returns: A json response from ArsenalInterface.check_response_codes(). ''' return super(PhysicalElevations, self).search(params) def create(self, params): '''Create a new physical_elevation. Args: params (dict): A dictionary with the following attributes: elevation : The number of the physical_elevation you wish to create. physical_rack : The name of the physical_rack the physical_elevation you wish to create will be in. physical_location : The name of the physical_location the physical_elevation you wish to create will be in. Usage: >>> params = { ... 'elevation': 10, ... 'physical_location': 'TEST DC SCIF 1', ... 'physical_rack': 'R500', ... } >>> PhysicalElevations.create(params) <Response [200]> ''' return super(PhysicalElevations, self).create(params) def update(self, params): '''Update a physical_elevation. Args: params (dict): A dictionary of url parameters for the request. Usage: Only the params in the example are updatable from this action. >>> params = { ... 'elevation': 12, ... 'physical_location': 'TEST DC SCIF 1', ... 'physical_rack': 'R501', ... } >>> PhysicalElevations.update(params) Returns: A json response from ArsenalInterface.check_response_codes(). ''' return super(PhysicalElevations, self).update(params) def delete(self, params): '''Delete a physical_elevation object from the server. Args: params: A physical_elevation dictionary to delete. Must contain the physical_elevation id, and name. Usage: >>> params = { ... 'id': 100, ... 'elevation': 12, ... 'physical_location': 'TEST DC SCIF 1', ... 'physical_rack': 'R501', ... } >>> PhysicalElevations.delete(params) ''' return super(PhysicalElevations, self).delete(params) def get_audit_history(self, results): '''Get the audit history for physical_elevations.''' return super(PhysicalElevations, self).get_audit_history(results) def get_by_name(self, name): '''Get a single physical_elevation by it's name. This is not possible as physical_elevations are not unique by name alone. Use PhysicalElevations.get_by_loc_rack_el() instead. ''' pass # Custom methods def get_by_loc_rack_el(self, location, rack, elevation): '''Get a single physical_elevation by it's elevation, location and rack.''' LOG.debug('Searching for physical_elevation by location: {0} ' 'rack: {1} elevation: {2}'.format(location, rack, elevation)) data = { 'physical_location': location, 'physical_rack': rack, 'elevation': elevation, } resp = self.api_conn('/api/physical_elevations', data, log_success=False) LOG.debug('Results are: {0}'.format(resp)) try: resource = resp['results'][0] except IndexError: msg = 'Physical Elevation not found, location: {0} rack: {1} ' \ 'elevation: {2}'.format(location, rack, elevation) LOG.info(msg) raise NoResultFound(msg) if len(resp['results']) > 1: msg = 'More than one result found, location: {0} rack: {1} ' \ 'elevation: {2}'.format(location, rack, elevation) LOG.error(msg) raise RuntimeError(msg) return resource
{ "repo_name": "CityGrid/arsenal", "path": "client/arsenalclient/interface/physical_elevations.py", "copies": "1", "size": "4647", "license": "apache-2.0", "hash": -2430379858394731000, "line_mean": 30.612244898, "line_max": 83, "alpha_frac": 0.5769313536, "autogenerated": false, "ratio": 4.178956834532374, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5255888188132374, "avg_score": null, "num_lines": null }
'''Arsenal client physical_elevations command line parser''' # # Copyright 2015 CityGrid Media, LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # from arsenalclient.cli.common import gen_help from arsenalclient.cli.physical_elevation import ( search_physical_elevations, create_physical_elevation, delete_physical_elevation, ) def parser_physical_elevations(top_parser, otsp): '''Add the physical_elevations CLI parser.''' ### physical_elevations object_type parser (otp) my_help = 'Perform actions on the physical_elevations object_type.\n\n' otp = otsp.add_parser('physical_elevations', description=my_help, help=my_help, parents=[top_parser]) # physical_elevations action sub-parser (asp) asp = otp.add_subparsers(title='Available actions', dest='action_command') # physical_elevations search subcommand (ssc) ssc = asp.add_parser('search', help='Search for physical_elevation objects and optionally ' \ 'act upon the results.', parents=[top_parser]) ssc.add_argument('--fields', '-f', dest='fields', help='Comma separated list of fields to display, or \'all\' for all fields.', default=None) ssc.add_argument('--exact', action='store_true', dest='exact_get', default=None, help='Exact match search terms.') ssc.add_argument('--exclude', dest='exclude', default=None, help='Comma separated list of key=value pairs to exclude.') ssc.add_argument('-a', '--audit-history', action='store_true', default=None, help='Show audit history for search results.') # physical_elevations update action argument group (uaag) uaag = ssc.add_argument_group('Update Actions') uaag.add_argument('-l', '--location', dest='physical_location', help='Update physical_elevation location. Must also ' \ 'specify rack.') uaag.add_argument('-r', '--rack', dest='physical_rack', help='Update physical_elevation location. Must also ' \ 'specify location.') ssc.add_argument('search', default=None, metavar='search_terms', help='Comma separated list of key=value pairs to search ' \ 'for.\n {0}'.format(gen_help('physical_elevations_search'))) ssc.set_defaults(func=search_physical_elevations) # physical_elevations create subcommand (csc) csc = asp.add_parser('create', help='Create physical_elevation objects.', parents=[top_parser]) # required physical_elevation create argument group (rcag) rcag = csc.add_argument_group('required arguments') rcag.add_argument('-e', '--elevation', dest='physical_elevation', required=True, help='The physical rack elevation name.') rcag.add_argument('-l', '--location', dest='physical_location', required=True, help='The physical rack location name.') rcag.add_argument('-r', '--rack', dest='physical_rack', required=True, help='The physical rack name.') rcag.set_defaults(func=create_physical_elevation) # physical_elevations delete subcommand (dsc) dsc = asp.add_parser('delete', help='Delete physical_elevation objects.', parents=[top_parser]) # required physical_elevation delete argument group (rdag) rdag = dsc.add_argument_group('required arguments') rdag.add_argument('-e', '--elevation', dest='physical_elevation', required=True, help='The physical rack elevation name to delete.') rdag.add_argument('-l', '--location', dest='physical_location', required=True, help='The physical rack location name to delete.') rdag.add_argument('-r', '--rack', dest='physical_rack', required=True, help='The physical rack name to delete.') dsc.set_defaults(func=delete_physical_elevation) return top_parser, otsp
{ "repo_name": "CityGrid/arsenal", "path": "client/arsenalclient/parser/physical_elevations.py", "copies": "1", "size": "5485", "license": "apache-2.0", "hash": -7804064074968614000, "line_mean": 39.9328358209, "line_max": 98, "alpha_frac": 0.5371011851, "autogenerated": false, "ratio": 4.78204010462075, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.581914128972075, "avg_score": null, "num_lines": null }
'''Arsenal client physical_location command line helpers. These functions are called directly by args.func() to invoke the appropriate action. They also handle output formatting to the commmand line. ''' # # Copyright 2015 CityGrid Media, LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # from __future__ import print_function import logging from arsenalclient.cli.common import ( _check_tags, ask_yes_no, check_resp, parse_cli_args, print_results, update_object_fields, ) from arsenalclient.exceptions import NoResultFound LOG = logging.getLogger(__name__) UPDATE_FIELDS = [ 'physical_location_address_1', 'physical_location_address_2', 'physical_location_admin_area', 'physical_location_city', 'physical_location_contact_name', 'physical_location_country', 'physical_location_phone_number', 'physical_location_postal_code', 'physical_location_provider', ] TAG_FIELDS = [ 'set_tags', 'del_tags', ] def _format_msg(results, tags=None): '''Format the message to be passed to ask_yes_no().''' r_names = [] for loc in results: resp = _check_tags(loc, tags) if resp: r_names.append('{0}: {1}\n{2}'.format(loc['name'], loc['id'], resp)) else: r_names.append('{0}: {1}'.format(loc['name'], loc['id'])) msg = 'We are ready to update the following physical_locations: ' \ '\n {0}\nContinue?'.format('\n '.join(r_names)) return msg def process_actions(args, client, results): '''Process change actions for physical_locations search results.''' resp = None if args.set_tags: msg = _format_msg(results, args.set_tags) if ask_yes_no(msg, args.answer_yes): tags = [tag for tag in args.set_tags.split(',')] for tag in tags: name, value = tag.split('=') resp = client.tags.assign(name, value, 'physical_locations', results) if args.del_tags: msg = _format_msg(results, args.del_tags) if ask_yes_no(msg, args.answer_yes): tags = [tag for tag in args.del_tags.split(',')] for tag in tags: name, value = tag.split('=') resp = client.tags.deassign(name, value, 'physical_locations', results) if any(getattr(args, key) for key in UPDATE_FIELDS): msg = _format_msg(results) if ask_yes_no(msg, args.answer_yes): for physical_location in results: pl_update = update_object_fields(args, 'physical_location', physical_location, UPDATE_FIELDS) client.physical_locations.update(pl_update) return resp def search_physical_locations(args, client): '''Search for physical_locations and perform optional assignment actions.''' LOG.debug('action_command is: {0}'.format(args.action_command)) LOG.debug('object_type is: {0}'.format(args.object_type)) resp = None action_fields = UPDATE_FIELDS + TAG_FIELDS search_fields = args.fields # If we are adding or deleting tags, we need existing tags for comparison. if args.set_tags or args.del_tags: if args.fields: args.fields += ',tags' else: args.fields = 'tags' if any(getattr(args, key) for key in UPDATE_FIELDS): search_fields = 'all' params = parse_cli_args(args.search, search_fields, args.exact_get, args.exclude) resp = client.physical_locations.search(params) if not resp.get('results'): return resp results = resp['results'] # Allows for multiple actions to be performed at once. if not any(getattr(args, key) for key in action_fields): if args.audit_history: results = client.physical_locations.get_audit_history(results) print_results(args, results) else: resp = process_actions(args, client, results) if resp: check_resp(resp) LOG.debug('Complete.') def create_physical_location(args, client): '''Create a new physical_location.''' location = { 'name': args.physical_location_name, 'address_1': args.physical_location_address_1, 'address_2': args.physical_location_address_2, 'city': args.physical_location_city, 'admin_area': args.physical_location_admin_area, 'contact_name': args.physical_location_contact_name, 'country': args.physical_location_country, 'phone_number': args.physical_location_phone_number, 'postal_code': args.physical_location_postal_code, 'provider': args.physical_location_provider, } LOG.info('Checking if physical_location name exists: {0}'.format(args.physical_location_name)) try: resp = client.physical_locations.get_by_name(args.physical_location_name) if ask_yes_no('Entry already exists for physical_location name: {0}\n Would you ' \ 'like to update it?'.format(resp['name']), args.answer_yes): resp = client.physical_locations.update(location) check_resp(resp) except NoResultFound: resp = client.physical_locations.create(location) check_resp(resp) def delete_physical_location(args, client): '''Delete an existing physical_location.''' LOG.debug('action_command is: {0}'.format(args.action_command)) LOG.debug('object_type is: {0}'.format(args.object_type)) results = client.physical_locations.get_by_name(args.physical_location_name) if results: msg = 'We are ready to delete the following {0}: ' \ '\n{1}\n Continue?'.format(args.object_type, results['name']) if ask_yes_no(msg, args.answer_yes): resp = client.physical_locations.delete(results) check_resp(resp)
{ "repo_name": "CityGrid/arsenal", "path": "client/arsenalclient/cli/physical_location.py", "copies": "1", "size": "6607", "license": "apache-2.0", "hash": 7080894601636082000, "line_mean": 32.538071066, "line_max": 98, "alpha_frac": 0.6125321629, "autogenerated": false, "ratio": 3.9468339307048983, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5059366093604898, "avg_score": null, "num_lines": null }
'''Arsenal client PhysicalLocations class.''' import logging from arsenalclient.interface.arsenal_interface import ArsenalInterface LOG = logging.getLogger(__name__) class PhysicalLocations(ArsenalInterface): '''The arsenal client PhysicalLocations class.''' def __init__(self, **kwargs): super(PhysicalLocations, self).__init__(**kwargs) self.uri = '/api/physical_locations' # Overridden methods def search(self, params=None): '''Search for physical_locations. Usage: >>> params = { ... 'name': 'my_physical_location', ... 'exact_get': True, ... } >>> PhysicalLocations.search(params) Args: params (dict): a dictionary of url parameters for the request. Returns: A json response from ArsenalInterface.check_response_codes(). ''' return super(PhysicalLocations, self).search(params) def create(self, params): '''Create a new physical_location. Args: params (dict): A dictionary with the following attributes: name : The name of the physical_location you wish to create. Usage: >>> params = { ... 'name': 'my_physical_location1', ... } >>> PhysicalLocations.create(params) <Response [200]> ''' return super(PhysicalLocations, self).create(params) def update(self, params): '''Update a physical_location. Args: params (dict): A dictionary of url parameters for the request. Usage: Only the params in the example are updatable from this action. >>> params = { ... 'name': 'SCIF 1', ... 'address_1': '1234 Anywhere Street', ... 'address_2': '2nd floor', ... 'admin_area': 'NV', ... 'city': 'Las Vegas', ... 'contact_name': 'Joe Manager', ... 'country': 'USA', ... 'phone_number': '310 555-1212', ... 'postal_code': '91100', ... 'provider': 'Switch', ... } >>> PhysicalLocations.update(params) Returns: A json response from ArsenalInterface.check_response_codes(). ''' return super(PhysicalLocations, self).update(params) def delete(self, params): '''Delete a physical_location object from the server. Args: params: A physical_location dictionary to delete. Must contain the physical_location id, and name. Usage: >>> params = { ... 'id': 1, ... 'name': 'my_physical_location', ... } >>> PhysicalLocations.delete(params) ''' return super(PhysicalLocations, self).delete(params) def get_audit_history(self, results): '''Get the audit history for physical_locations.''' return super(PhysicalLocations, self).get_audit_history(results) def get_by_name(self, name): '''Get a single physical_location by it's name. Args: name (str): A string representing the physical_location name you wish to find. ''' return super(PhysicalLocations, self).get_by_name(name) # Custom methods # TBD
{ "repo_name": "CityGrid/arsenal", "path": "client/arsenalclient/interface/physical_locations.py", "copies": "1", "size": "3284", "license": "apache-2.0", "hash": -4711640525385563000, "line_mean": 27.0683760684, "line_max": 90, "alpha_frac": 0.5624238733, "autogenerated": false, "ratio": 4.309711286089239, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5372135159389239, "avg_score": null, "num_lines": null }
'''Arsenal client physical_locations command line parser''' # # Copyright 2015 CityGrid Media, LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # from arsenalclient.cli.common import gen_help from arsenalclient.cli.physical_location import ( search_physical_locations, create_physical_location, delete_physical_location, ) def parser_physical_locations(top_parser, otsp): '''Add the physical_locations CLI parser.''' ### physical_locations object_type parser (otp) my_help = ('Perform actions on the physical_locations object_type. Use the \n' 'search action to perform assignment actions such as tagging (TBD).\n\n') otp = otsp.add_parser('physical_locations', description=my_help, help=my_help, parents=[top_parser]) # physical_locations action sub-parser (asp) asp = otp.add_subparsers(title='Available actions', dest='action_command') # physical_locations search subcommand (ssc) ssc = asp.add_parser('search', help='Search for physical_location objects and optionally ' \ 'act upon the results.', parents=[top_parser]) ssc.add_argument('--fields', '-f', dest='fields', help='Comma separated list of fields to display, or \'all\' for all fields.', default=None) ssc.add_argument('--exact', action='store_true', dest='exact_get', default=None, help='Exact match search terms.') ssc.add_argument('--exclude', dest='exclude', default=None, help='Comma separated list of key=value pairs to exclude.') ssc.add_argument('-a', '--audit-history', action='store_true', default=None, help='Show audit history for search results.') # physical_locations update action argument group (uaag) uaag = ssc.add_argument_group('Update Actions') uaag.add_argument('--name', '-n', dest='physical_location_name', help='physical_location_name to create.') uaag.add_argument('-a1', '--address-1', dest='physical_location_address_1', help='Update physical_location address 1.') uaag.add_argument('-a2', '--address-2', dest='physical_location_address_2', help='Update physical_location address 2.') uaag.add_argument('-c', '--city', dest='physical_location_city', help='Update physical_location city.') uaag.add_argument('-s', '--state', dest='physical_location_admin_area', help='Update physical_location state.') uaag.add_argument('-t', '--contact-name', dest='physical_location_contact_name', help='Update physical_location contact name.') uaag.add_argument('-C', '--country', dest='physical_location_country', help='Update physical_location country.') uaag.add_argument('-P', '--phone-number', dest='physical_location_phone_number', help='Update physical_location contact phone number.') uaag.add_argument('-p', '--postal-code', dest='physical_location_postal_code', help='Update physical_location postal code.') uaag.add_argument('-r', '--provider', dest='physical_location_provider', help='Update physical_location provider.') # physical_locations assignment action argument group (aag) aag = ssc.add_argument_group('Assignment Actions') aag.add_argument('--tag', dest='set_tags', help='Comma separated list of key=value pairs to tag to ' \ 'the search results.') aag.add_argument('--del_tag', dest='del_tags', help='Comma separated list of key=value pairs to un-tag from the ' \ 'search results.') ssc.add_argument('search', default=None, metavar='search_terms', help='Comma separated list of key=value pairs to search ' \ 'for.\n {0}'.format(gen_help('physical_locations_search'))) ssc.set_defaults(func=search_physical_locations) # physical_locations create subcommand (csc) csc = asp.add_parser('create', help='Create physical_location objects.', parents=[top_parser]) # required physical_location create argument group (rcag) rcag = csc.add_argument_group('required arguments') rcag.add_argument('--name', '-n', required=True, dest='physical_location_name', help='physical_location_name to create.') rcag.add_argument('-a1', '--address-1', dest='physical_location_address_1', help='Update physical_location address 1.') rcag.add_argument('-a2', '--address-2', dest='physical_location_address_2', help='Update physical_location address 2.') rcag.add_argument('-c', '--city', dest='physical_location_city', help='Update physical_location city.') rcag.add_argument('-s', '--state', dest='physical_location_admin_area', help='Update physical_location state.') rcag.add_argument('-t', '--contact-name', dest='physical_location_contact_name', help='Update physical_location contact name.') rcag.add_argument('-C', '--country', dest='physical_location_country', help='Update physical_location country.') rcag.add_argument('-P', '--phone-number', dest='physical_location_phone_number', help='Update physical_location contact phone number.') rcag.add_argument('-p', '--postal-code', dest='physical_location_postal_code', help='Update physical_location postal code.') rcag.add_argument('-r', '--provider', dest='physical_location_provider', help='Update physical_location provider.') rcag.set_defaults(func=create_physical_location) # physical_locations delete subcommand (dsc) dsc = asp.add_parser('delete', help='Delete physical_location objects.', parents=[top_parser]) # required physical_location delete argument group (rdag) rdag = dsc.add_argument_group('required arguments') rdag.add_argument('--name', '-n', required=True, dest='physical_location_name', help='physical_location_name to delete.') dsc.set_defaults(func=delete_physical_location) return top_parser, otsp
{ "repo_name": "CityGrid/arsenal", "path": "client/arsenalclient/parser/physical_locations.py", "copies": "1", "size": "8292", "license": "apache-2.0", "hash": 6258486483178088000, "line_mean": 42.873015873, "line_max": 98, "alpha_frac": 0.5267727931, "autogenerated": false, "ratio": 4.846288720046756, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5873061513146756, "avg_score": null, "num_lines": null }
'''Arsenal client physical_rack command line helpers. These functions are called directly by args.func() to invoke the appropriate action. They also handle output formatting to the commmand line. ''' # # Copyright 2015 CityGrid Media, LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # from __future__ import print_function import logging from arsenalclient.cli.common import ( _check_tags, ask_yes_no, check_resp, parse_cli_args, print_results, update_object_fields, ) from arsenalclient.exceptions import NoResultFound LOG = logging.getLogger(__name__) UPDATE_FIELDS = [ 'physical_location', ] TAG_FIELDS = [ 'set_tags', 'del_tags', ] def _format_msg(results, tags=None): '''Format the message to be passed to ask_yes_no().''' r_names = [] for res in results: resp = _check_tags(res, tags) if resp: r_names.append('{0}\n{1}'.format(res['name'], resp)) else: r_names.append('{0}'.format(res['name'])) msg = 'We are ready to update the following physical_racks: ' \ '\n {0}\nContinue?'.format('\n '.join(r_names)) return msg def process_actions(args, client, results): '''Process change actions for physical_racks search results.''' resp = None if args.set_tags: msg = _format_msg(results, args.set_tags) if ask_yes_no(msg, args.answer_yes): tags = [tag for tag in args.set_tags.split(',')] for tag in tags: name, value = tag.split('=') resp = client.tags.assign(name, value, 'physical_racks', results) if args.del_tags: msg = _format_msg(results, args.del_tags) if ask_yes_no(msg, args.answer_yes): tags = [tag for tag in args.del_tags.split(',')] for tag in tags: name, value = tag.split('=') resp = client.tags.deassign(name, value, 'physical_racks', results) if any(getattr(args, key) for key in UPDATE_FIELDS): msg = _format_msg(results) if ask_yes_no(msg, args.answer_yes): for physical_rack in results: pd_update = update_object_fields(args, 'physical_rack', physical_rack, UPDATE_FIELDS) client.physical_racks.update(pd_update) return resp def search_physical_racks(args, client): '''Search for physical_racks and perform optional assignment actions.''' LOG.debug('action_command is: {0}'.format(args.action_command)) LOG.debug('object_type is: {0}'.format(args.object_type)) resp = None action_fields = UPDATE_FIELDS + TAG_FIELDS search_fields = args.fields # If we are adding or deleting tags, we need existing tags for comparison. if args.set_tags or args.del_tags: if args.fields: args.fields += ',tags' else: args.fields = 'tags' if any(getattr(args, key) for key in UPDATE_FIELDS): search_fields = 'all' params = parse_cli_args(args.search, search_fields, args.exact_get, args.exclude) resp = client.physical_racks.search(params) if not resp.get('results'): return resp results = resp['results'] # Allows for multiple actions to be performed at once. if not any(getattr(args, key) for key in action_fields): if args.audit_history: results = client.physical_racks.get_audit_history(results) print_results(args, results) else: resp = process_actions(args, client, results) if resp: check_resp(resp) LOG.debug('Complete.') def create_physical_rack(args, client): '''Create a new physical_rack.''' LOG.info('Checking if physical_rack exists name: {0} physical_location: ' '{1}'.format(args.name, args.physical_location)) device = { 'name': args.name, 'physical_location': args.physical_location, } try: resp = client.physical_racks.get_by_name_location(args.name, args.physical_location) if ask_yes_no('Entry already exists for physical_rack name: {0}\n Would you ' \ 'like to update it?'.format(resp['name']), args.answer_yes): resp = client.physical_racks.update(device) check_resp(resp) except NoResultFound: resp = client.physical_racks.create(device) check_resp(resp) def delete_physical_rack(args, client): '''Delete an existing physical_rack.''' LOG.debug('action_command is: {0}'.format(args.action_command)) LOG.debug('object_type is: {0}'.format(args.object_type)) results = client.physical_racks.get_by_name(args.physical_rack_name) if results: r_names = [] for physical_racks in results: r_names.append(physical_racks['name']) msg = 'We are ready to delete the following {0}: ' \ '\n{1}\n Continue?'.format(args.object_type, '\n '.join(r_names)) if ask_yes_no(msg, args.answer_yes): for physical_rack in results: resp = client.physical_racks.delete(physical_rack) check_resp(resp)
{ "repo_name": "CityGrid/arsenal", "path": "client/arsenalclient/cli/physical_rack.py", "copies": "1", "size": "5906", "license": "apache-2.0", "hash": 3653607186209441000, "line_mean": 30.752688172, "line_max": 87, "alpha_frac": 0.5985438537, "autogenerated": false, "ratio": 3.8601307189542484, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.4958674572654248, "avg_score": null, "num_lines": null }
'''Arsenal client PhysicalRacks class.''' import logging from arsenalclient.interface.arsenal_interface import ArsenalInterface from arsenalclient.exceptions import NoResultFound LOG = logging.getLogger(__name__) class PhysicalRacks(ArsenalInterface): '''The arsenal client PhysicalRacks class.''' def __init__(self, **kwargs): super(PhysicalRacks, self).__init__(**kwargs) self.uri = '/api/physical_racks' # Overridden methods def search(self, params=None): '''Search for physical_racks. Usage: >>> params = { ... 'name': 'R500', ... 'exact_get': True, ... } >>> PhysicalRacks.search(params) Args: params (dict): a dictionary of url parameters for the request. Returns: A json response from ArsenalInterface.check_response_codes(). ''' return super(PhysicalRacks, self).search(params) def create(self, params): '''Create a new physical_rack. Args: params (dict): A dictionary with the following attributes: name : The name of the physical_rack you wish to create. physical_location : The name of the physical_location the physical_rack you wish to create will be in. Usage: >>> params = { ... 'name': 'R500', ... 'physical_location': 'TEST DC SCIF 1', ... } >>> PhysicalRacks.create(params) <Response [200]> ''' return super(PhysicalRacks, self).create(params) def update(self, params): '''Update a physical_rack. Args: params (dict): A dictionary of url parameters for the request. Usage: Only the params in the example are updatable from this action. >>> params = { ... 'name': 'R500', ... 'physical_location': 'TEST DC SCIF 2', ... } >>> PhysicalRacks.update(params) Returns: A json response from ArsenalInterface.check_response_codes(). ''' return super(PhysicalRacks, self).update(params) def delete(self, params): '''Delete a physical_rack object from the server. Args: params: A physical_rack dictionary to delete. Must contain the physical_rack id, and name. Usage: >>> params = { ... 'id': 1, ... 'name': 'R500', ... } >>> PhysicalRacks.delete(params) ''' return super(PhysicalRacks, self).delete(params) def get_audit_history(self, results): '''Get the audit history for physical_racks.''' return super(PhysicalRacks, self).get_audit_history(results) def get_by_name(self, name): '''Get a single physical_rack by it's name. This is not possible as physical_racks are not unique by name alone. Use PhysicalRacks.get_by_name_location() instead. ''' pass # Custom methods def get_by_name_location(self, name, location): '''Get a single physical_rack by it's name and location.''' LOG.debug('Searching for physical_rack by name: {0} location: {1}'.format(name, location)) data = { 'name': name, 'physical_location.name': location, } resp = self.api_conn('/api/physical_racks', data, log_success=False) LOG.debug('Results are: {0}'.format(resp)) try: resource = resp['results'][0] except IndexError: msg = 'Physical Rack not found, name: {0} location: {1}'.format(name, location) LOG.info(msg) raise NoResultFound(msg) if len(resp['results']) > 1: msg = 'More than one result found, name: {0} location: {1}'.format(name, location) LOG.error(msg) raise RuntimeError(msg) return resource
{ "repo_name": "CityGrid/arsenal", "path": "client/arsenalclient/interface/physical_racks.py", "copies": "1", "size": "4165", "license": "apache-2.0", "hash": 2734161379985650700, "line_mean": 29.1811594203, "line_max": 93, "alpha_frac": 0.53757503, "autogenerated": false, "ratio": 4.298245614035087, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5335820644035087, "avg_score": null, "num_lines": null }
'''Arsenal client physical_racks command line parser''' # # Copyright 2015 CityGrid Media, LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # from arsenalclient.cli.common import gen_help from arsenalclient.cli.physical_rack import ( search_physical_racks, create_physical_rack, delete_physical_rack, ) def parser_physical_racks(top_parser, otsp): '''Add the physical_racks CLI parser.''' ### physical_racks object_type parser (otp) my_help = ('Perform actions on the physical_racks object_type. Use the \n' 'search action to perform assignment actions such as tagging (TBD).\n\n') otp = otsp.add_parser('physical_racks', description=my_help, help=my_help, parents=[top_parser]) # physical_racks action sub-parser (asp) asp = otp.add_subparsers(title='Available actions', dest='action_command') # physical_racks search subcommand (ssc) ssc = asp.add_parser('search', help='Search for physical_rack objects and optionally ' \ 'act upon the results.', parents=[top_parser]) ssc.add_argument('--fields', '-f', dest='fields', help='Comma separated list of fields to display, or \'all\' for all fields.', default=None) ssc.add_argument('--exact', action='store_true', dest='exact_get', default=None, help='Exact match search terms.') ssc.add_argument('--exclude', dest='exclude', default=None, help='Comma separated list of key=value pairs to exclude.') ssc.add_argument('-a', '--audit-history', action='store_true', default=None, help='Show audit history for search results.') # physical_racks update action argument group (uaag) uaag = ssc.add_argument_group('Update Actions') uaag.add_argument('-l', '--location', dest='physical_location', help='Update physical_rack location.') # physical_racks assignment action argument group (aag) aag = ssc.add_argument_group('Assignment Actions') aag.add_argument('--tag', dest='set_tags', help='Comma separated list of key=value pairs to tag to ' \ 'the search results.') aag.add_argument('--del_tag', dest='del_tags', help='Comma separated list of key=value pairs to un-tag from the ' \ 'search results.') ssc.add_argument('search', default=None, metavar='search_terms', help='Comma separated list of key=value pairs to search ' \ 'for.\n {0}'.format(gen_help('physical_racks_search'))) ssc.set_defaults(func=search_physical_racks) # physical_racks create subcommand (csc) csc = asp.add_parser('create', help='Create physical_rack objects.', parents=[top_parser]) # required physical_rack create argument group (rcag) rcag = csc.add_argument_group('required arguments') rcag.add_argument('-l', '--location', dest='physical_location', required=True, help='The physical rack location name.') rcag.add_argument('-n', '--name', help='The physical rack name.') rcag.set_defaults(func=create_physical_rack) # physical_racks delete subcommand (dsc) dsc = asp.add_parser('delete', help='Delete physical_rack objects.', parents=[top_parser]) # required physical_rack delete argument group (rdag) rdag = dsc.add_argument_group('required arguments') rdag.add_argument('-n', '--name', required=True, dest='physical_rack_name', help='physical_rack_name to delete.') dsc.set_defaults(func=delete_physical_rack) return top_parser, otsp
{ "repo_name": "CityGrid/arsenal", "path": "client/arsenalclient/parser/physical_racks.py", "copies": "1", "size": "4950", "license": "apache-2.0", "hash": 8570557374262896000, "line_mean": 39.243902439, "line_max": 98, "alpha_frac": 0.5507070707, "autogenerated": false, "ratio": 4.471544715447155, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5522251786147154, "avg_score": null, "num_lines": null }
'''Arsenal client register command line parser''' # # Copyright 2015 CityGrid Media, LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # from arsenalclient.cli.node import register def parser_register(top_parser, otsp): '''Add the register CLI parser. This is a bit of a cheat since technically it's not an object type. Putting it at the top level since it is the primary command.''' r_help = 'Register this node to the server.\n\n' rotp = otsp.add_parser('register', description=r_help, help=r_help, parents=[top_parser]) rotp.set_defaults(func=register) return top_parser, otsp
{ "repo_name": "CityGrid/arsenal", "path": "client/arsenalclient/parser/register.py", "copies": "1", "size": "1203", "license": "apache-2.0", "hash": 7294668129366622000, "line_mean": 37.8064516129, "line_max": 79, "alpha_frac": 0.6816292602, "autogenerated": false, "ratio": 3.9185667752442996, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.0008271298593879239, "num_lines": 31 }
'''Arsenal client status command line helpers. These functions are called directly by args.func() to invoke the appropriate action. They also handle output formatting to the commmand line. ''' # # Copyright 2015 CityGrid Media, LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # from __future__ import print_function import sys import logging from arsenalclient.cli.common import ( ask_yes_no, check_resp, parse_cli_args, print_results, update_object_fields, ) LOG = logging.getLogger(__name__) def search_statuses(args, client): '''Search for statuses and perform optional updates.''' LOG.debug('action_command is: {0}'.format(args.action_command)) LOG.debug('object_type is: {0}'.format(args.object_type)) resp = None update_fields = [ 'statuses_description', ] search_fields = args.fields if any(getattr(args, key) for key in update_fields): search_fields = 'all' params = parse_cli_args(args.search, search_fields, args.exact_get, args.exclude) resp = client.statuses.search(params) if not resp.get('results'): return resp results = resp['results'] if args.audit_history: results = client.statuses.get_audit_history(results) if not any(getattr(args, key) for key in update_fields): print_results(args, results) else: if len(results) > 1: LOG.error('Expected 1 result, exiting.') sys.exit(1) else: status = results[0] LOG.debug('STATUS: {0}'.format(status)) msg = 'We are ready to update the following status: \n ' \ '{0}\nContinue?'.format(status['name']) if any(getattr(args, key) for key in update_fields) and ask_yes_no(msg, args.answer_yes): status_update = update_object_fields(args, 'statuses', status, update_fields) resp = client.statuses.update(status_update) if resp: check_resp(resp) LOG.debug('Complete.')
{ "repo_name": "CityGrid/arsenal", "path": "client/arsenalclient/cli/status.py", "copies": "1", "size": "2649", "license": "apache-2.0", "hash": 5479448015066096000, "line_mean": 30.9156626506, "line_max": 97, "alpha_frac": 0.6281615704, "autogenerated": false, "ratio": 3.9894578313253013, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5117619401725302, "avg_score": null, "num_lines": null }
'''Arsenal client Statuses class.''' import logging from arsenalclient.interface.arsenal_interface import ArsenalInterface from arsenalclient.exceptions import NoResultFound LOG = logging.getLogger(__name__) class Statuses(ArsenalInterface): '''The arsenal client Statuses class.''' def __init__(self, **kwargs): super(Statuses, self).__init__(**kwargs) self.uri = '/api/statuses' # Overridden methods def search(self, params=None): '''Search for statuses. Usage: >>> params = { ... 'name': 'inservice', ... 'exact_get': True, ... } >>> Statuses.search(params) Args: params (dict): a dictionary of url parameters for the request. Returns: A json response from ArsenalInterface.check_response_codes(). ''' return super(Statuses, self).search(params=params) def create(self, params): '''Create a status. Args: params (dict): A dictionary of url parameters for the request. The following keys arew required: name description Usage: >>> params = { ... 'description': 'Instances that have been spun down that will be spun up on demand.', ... 'name': 'hibernating' ... } >>> Statuses.create(params) Returns: A json response from ArsenalInterface.check_response_codes(). ''' return super(Statuses, self).create(params) def update(self, params): '''Update a status. Args: params (dict): A dictionary of url parameters for the request. Usage: Only these params are updatable from this action. >>> params = { ... 'description': 'Instances that have been spun down that will be spun up on demand.', ... 'name': 'hibernating' ... } >>> Statuses.update(params) Returns: A json response from ArsenalInterface.check_response_codes(). ''' return super(Statuses, self).update(params) def delete(self, params): '''Delete a status object from the server. Args: params: A status dictionary to delete. Must contain the status id and name. Usage: >>> params = { ... 'id': 4, ... 'name': 'hibernating' ... } >>> Statuses.delete(params) ''' return super(Statuses, self).delete(params) def get_audit_history(self, results): '''Get the audit history for statuses.''' return super(Statuses, self).get_audit_history(results) def get_by_name(self, name): '''Get a single status by it's name. Args: name (str): A string representing the status name you wish to find. ''' return super(Statuses, self).get_by_name(name) # Custom methods def assign(self, status_name, object_type, results): '''Set the status of one or more nodes or data_centers. Args: status_name (string): The name of the status you wish to set the node(s) to. object_type (str): A string representing the object_type to assign the status to. One of nodes or data_centers. results : The nodes or data_centers from the results of <Class>.search() to assign the status to. Usage: >>> Status.assign('inservice', 'nodes' <search() results>) <Response [200]> ''' try: status = self.get_by_name(status_name) except NoResultFound: return None action_ids = [result['id'] for result in results] LOG.info('Assigning status: {0}'.format(status['name'])) for result in results: LOG.info(' {0}: {1}'.format(object_type, result['name'])) data = { object_type: action_ids } uri = '/api/statuses/{0}/{1}'.format(status['id'], object_type) return self.api_conn(uri, data, method='put')
{ "repo_name": "CityGrid/arsenal", "path": "client/arsenalclient/interface/statuses.py", "copies": "1", "size": "4158", "license": "apache-2.0", "hash": 3813897269108759600, "line_mean": 27.2857142857, "line_max": 98, "alpha_frac": 0.5555555556, "autogenerated": false, "ratio": 4.313278008298755, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5368833563898755, "avg_score": null, "num_lines": null }
'''Arsenal client statuses command line parser''' # # Copyright 2015 CityGrid Media, LLC # # Licensed under the Apache License, Version 2.0 (the 'License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # from arsenalclient.cli.common import gen_help from arsenalclient.cli.status import ( search_statuses, ) def parser_statuses(top_parser, otsp): '''Add the statuses CLI parser.''' ### statues object_type parser (sotp) s_help = ('Perform actions on the statuses object_type. Use the \n' 'search action to perform actions such as updating ' 'the description.\n\n') sotp = otsp.add_parser('statuses', description=s_help, help=s_help, parents=[top_parser]) # statuses action sub-parser (sasp) sasp = sotp.add_subparsers(title='Available actions', dest='action_command') # statuses search subcommand (sssc) sssc = sasp.add_parser('search', help='Search for statues objects and optionally act upon the results.', parents=[top_parser]) sssc.add_argument('--fields', '-f', dest='fields', help='Comma separated list of fields to display, or \'all\' for all fields.', default=None) sssc.add_argument('--exact', action='store_true', dest='exact_get', default=None, help='Exact match search terms.') sssc.add_argument('--exclude', dest='exclude', default=None, help='Comma separated list of key=value pairs to exclude.') sssc.add_argument('-a', '--audit-history', action='store_true', default=None, help='Show audit history for search results.') # statuses update action argument group (anguag) suag = sssc.add_argument_group('Update Actions') suag.add_argument('--description', '-d', dest='statuses_description', help='Update statuses_description.') sssc.add_argument('search', default=None, metavar='search_terms', help='Comma separated list of key=value pairs to search ' \ 'for.\n {0}'.format(gen_help('statuses_search'))) sssc.set_defaults(func=search_statuses) return top_parser, otsp
{ "repo_name": "CityGrid/arsenal", "path": "client/arsenalclient/parser/statuses.py", "copies": "1", "size": "3065", "license": "apache-2.0", "hash": -189609769788920640, "line_mean": 40.9863013699, "line_max": 99, "alpha_frac": 0.5634584013, "autogenerated": false, "ratio": 4.487554904831625, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5551013306131625, "avg_score": null, "num_lines": null }
'''Arsenal client tag command line helpers. These functions are called directly by args.func() to invoke the appropriate action. They also handle output formatting to the commmand line. ''' # # Copyright 2015 CityGrid Media, LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # from __future__ import print_function import logging from arsenalclient.cli.common import ( ask_yes_no, check_resp, parse_cli_args, print_results, ) LOG = logging.getLogger(__name__) def search_tags(args, client): '''Search for tags and perform optional assignment actions.''' LOG.debug('action_command is: {0}'.format(args.action_command)) LOG.debug('object_type is: {0}'.format(args.object_type)) resp = None params = parse_cli_args(args.search, args.fields, args.exact_get, args.exclude) resp = client.tags.search(params) if not resp.get('results'): return resp results = resp['results'] if args.audit_history: results = client.tags.get_audit_history(results) # switch to any if there's more than one if not args.set_tags: skip_keys = [ 'name', 'value', ] print_results(args, results, skip_keys=skip_keys, default_key='tag') else: LOG.info('Assigning tags via tag search is not implemented.') if resp: check_resp(resp) LOG.debug('Complete.') def create_tag(args, client): '''Create a new tag.''' params = { 'name': args.tag_name, 'value': args.tag_value, } client.tags.create(params) def delete_tag(args, client): '''Delete an existing tag. Requires a tag name and value.''' LOG.debug('action_command is: {0}'.format(args.action_command)) LOG.debug('object_type is: {0}'.format(args.object_type)) search = { 'name': args.tag_name, 'value': args.tag_value, 'exact_get': True, } resp = client.tags.search(search) results = resp['results'] if results: r_names = [] for tag in results: r_names.append('{0}={1}'.format(tag['name'], tag['value'])) msg = 'We are ready to delete the following {0}: ' \ '\n{1}\n Continue?'.format(args.object_type, '\n '.join(r_names)) if ask_yes_no(msg, args.answer_yes): for tag in results: resp = client.tags.delete(tag) check_resp(resp)
{ "repo_name": "CityGrid/arsenal", "path": "client/arsenalclient/cli/tag.py", "copies": "1", "size": "2928", "license": "apache-2.0", "hash": 958740324206589400, "line_mean": 26.3644859813, "line_max": 83, "alpha_frac": 0.6328551913, "autogenerated": false, "ratio": 3.678391959798995, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9807575589016218, "avg_score": 0.0007343124165554072, "num_lines": 107 }
'''Arsenal client Tags class.''' import logging from arsenalclient.interface.arsenal_interface import ArsenalInterface from arsenalclient.exceptions import NoResultFound LOG = logging.getLogger(__name__) class Tags(ArsenalInterface): '''The arsenal client Tags class.''' def __init__(self, **kwargs): super(Tags, self).__init__(**kwargs) self.uri = '/api/tags' # Overridden methods def search(self, params=None): '''Search for tags. Usage: >>> params = { ... 'name': 'my_tag', ... 'exact_get': True, ... } >>> Tags.search(params) Args: params (dict): a dictionary of url parameters for the request. Returns: A json response from ArsenalInterface.check_response_codes(). ''' return super(Tags, self).search(params) def create(self, params): '''Create a new tag. Args: params (dict): A dictionary with the following attributes: tag_name : The name of the tag you wish to create. tag_value: The value of the tag you wish to create. Usage: >>> params = { ... 'name': 'meaning', ... 'value': 42, ... } >>> Tags.create(params) <Response [200]> ''' return super(Tags, self).create(params) def update(self, params): '''Update a tag. There is nothing to update with tags as every field must be unique.''' pass def delete(self, params): '''Delete a tag object from the server. Args: params: A tag dictionary to delete. Must contain the tag id, name, and value. Usage: >>> params = { ... 'id': 1, ... 'name': 'my_tag', ... 'value': 'my_string', ... } >>> Tags.delete(params) ''' return super(Tags, self).delete(params) def get_audit_history(self, results): '''Get the audit history for tags.''' return super(Tags, self).get_audit_history(results) def get_by_name(self, name): '''Get a single tag by it's name. This is not possible as a tag's uniqueness is determined by both it's name and value. Use Tags.get_by_name_value() instead. ''' pass # Custom methods def get_by_name_value(self, name, value): '''Get a tag from the server based on it's name and value.''' LOG.debug('Searching for tag name: {0} value: {1}'.format(name, value)) data = { 'name': name, 'value': value, 'exact_get': True, } resp = self.api_conn('/api/tags', data, log_success=False) LOG.debug('Results are: {0}'.format(resp)) try: resource = resp['results'][0] except IndexError: msg = 'Tag not found: {0}={1}'.format(name, value) LOG.info(msg) raise NoResultFound(msg) if len(resp['results']) > 1: msg = 'More than one result found: {0}'.format(name) LOG.error(msg) raise RuntimeError(msg) return resource def _manage_assignments(self, name, value, object_type, results, api_method): '''Assign or de-assign a tag to a list of node, node_group, or data_center dictionaries.''' action_names = [] action_ids = [] msg = 'Assigning' if api_method == 'delete': msg = 'De-assigning' for action_object in results: try: action_names.append(action_object['name']) except KeyError: action_names.append(action_object['serial_number']) action_ids.append(action_object['id']) try: this_tag = self.get_by_name_value(name, value) except NoResultFound: if api_method == 'delete': LOG.debug('Tag not found, nothing to do.') return else: params = { 'name': name, 'value': value, } resp = self.create(params) this_tag = resp['results'][0] LOG.info('{0} tag: {1}={2}'.format(msg, this_tag['name'], this_tag['value'])) for action_name in action_names: LOG.info(' {0}: {1}'.format(object_type, action_name)) data = { object_type: action_ids } try: uri = '/api/tags/{0}/{1}'.format(this_tag['id'], object_type) resp = self.api_conn(uri, data, method=api_method) except: raise return resp def assign(self, name, value, object_type, results): '''Assign a tag to one or more nodes, node_groups, or data_centers. Args: name (str) : The name of the tag to assign to the <Class>.search() results. value (str) : The value of the tag to assign to the <Class>.search() results. object_type (str): A string representing the object_type to assign the tag to. One of nodes, node_groups or data_centers. results : The nodes, node_groups, or data_centers from the results of <Class>.search() to assign the tag to. Usage: >>> Tags.assign('meaning', 42, 'nodes', <search results>) <json> ''' return self._manage_assignments(name, value, object_type, results, 'put') def deassign(self, name, value, object_type, results): '''De-assign a tag from one or more nodes, node_groups, or data_centers. Args: name (str) : The name of the tag to deassign to the <Class>.search() results. value (str) : The value of the tag to deassign to the <Class>.search() results. object_type (str): A string representing the object_type to deassign the tag to. One of nodes, node_groups or data_centers. results : The nodes, node_groups, or data_centers from the results of <Class>.search() to deassign the tag from. Usage: >>> Tags.deassign('meaning', 42, 'nodes', <search results>) <json> ''' return self._manage_assignments(name, value, object_type, results, 'delete')
{ "repo_name": "CityGrid/arsenal", "path": "client/arsenalclient/interface/tags.py", "copies": "1", "size": "6469", "license": "apache-2.0", "hash": 6039443982611251000, "line_mean": 29.8047619048, "line_max": 88, "alpha_frac": 0.5294481373, "autogenerated": false, "ratio": 4.157455012853471, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.0009638161543473342, "num_lines": 210 }
'''Arsenal client tags command line parser''' # # Copyright 2015 CityGrid Media, LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # from arsenalclient.cli.common import gen_help from arsenalclient.cli.tag import ( search_tags, create_tag, delete_tag, ) def parser_tags(top_parser, otsp): '''Add the tags CLI parser.''' ### tags object_type parser (totp) t_help = ('Perform actions on the tags object_type. Use the search\n' 'action to perform assignment actions such as tagging.\n\n') totp = otsp.add_parser('tags', description=t_help, help=t_help, parents=[top_parser]) # tags action sub-parser (tasp) tasp = totp.add_subparsers(title='Available actions', dest='action_command') # tags search subcommand (tssc) tssc = tasp.add_parser('search', help='Search for tags objects and optionally act upon the results.', parents=[top_parser]) tssc.add_argument('--fields', '-f', dest='fields', help='Comma separated list of fields to display, or \'all\' for all fields.', default=None) tssc.add_argument('--exact', action='store_true', dest='exact_get', default=None, help='Exact match search terms.') tssc.add_argument('--exclude', dest='exclude', default=None, help='Comma separated list of key=value pairs to exclude.') tssc.add_argument('-a', '--audit-history', action='store_true', default=None, help='Show audit history for search results.') # tags assignment action argument group (atsag) atsag = tssc.add_argument_group('Assignment Actions') atsag.add_argument('--tag', dest='set_tags', help='Comma separated list of key=value pairs to tag to the node_group.') tssc.add_argument('search', default=None, metavar='search_terms', help='Comma separated list of key=value pairs to search ' \ 'for.\n {0}'.format(gen_help('tags_search'))) atsag.set_defaults(func=search_tags) # tags create subcommand (tcsc) tcsc = tasp.add_parser('create', help='Create tag objects.', parents=[top_parser]) # required tag create argument group (rtcag) rtcag = tcsc.add_argument_group('required arguments') rtcag.add_argument('--name', '-n', required=True, dest='tag_name', help='tag_name to create.') rtcag.add_argument('--value', required=True, dest='tag_value', help='tag_value to assign to the name.') rtcag.set_defaults(func=create_tag) # tags delete subcommand (tdsc) tdsc = tasp.add_parser('delete', help='Delete tag objects.', parents=[top_parser]) # required tag delete argument group (rtdag) rtdag = tdsc.add_argument_group('required arguments') rtdag.add_argument('--name', '-n', required=True, dest='tag_name', help='tag_name to delete.') rtdag.add_argument('--value', required=True, dest='tag_value', help='tag_value to delete.') tdsc.set_defaults(func=delete_tag) return top_parser, otsp
{ "repo_name": "CityGrid/arsenal", "path": "client/arsenalclient/parser/tags.py", "copies": "1", "size": "4375", "license": "apache-2.0", "hash": -2455122732533759000, "line_mean": 38.4144144144, "line_max": 99, "alpha_frac": 0.536, "autogenerated": false, "ratio": 4.42366026289181, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.545966026289181, "avg_score": null, "num_lines": null }
'''Arsenal client UID command line parser''' # # Copyright 2015 CityGrid Media, LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # from arsenalclient.cli.node import unique_id def parser_uid(top_parser, otsp): '''Add the UID parser. This is a bit of a cheat since technically it's not an object type. Print out the unique_id of the current node.''' u_help = 'Print out the unique_id of the current node.\n\n' uidotp = otsp.add_parser('uid', description=u_help, help=u_help, parents=[top_parser]) uidotp.set_defaults(func=unique_id) return top_parser, otsp
{ "repo_name": "CityGrid/arsenal", "path": "client/arsenalclient/parser/uid.py", "copies": "1", "size": "1182", "license": "apache-2.0", "hash": 4091396662163528700, "line_mean": 38.4, "line_max": 75, "alpha_frac": 0.6734348562, "autogenerated": false, "ratio": 3.7884615384615383, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.4961896394661538, "avg_score": null, "num_lines": null }
'''Arsenal common DB Model''' # Copyright 2015 CityGrid Media, LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # import logging from datetime import datetime import arrow from dateutil import tz import pyramid from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.ext.hybrid import hybrid_property, hybrid_method from sqlalchemy import ( Column, ForeignKey, Integer, TIMESTAMP, Table, Text, ) from sqlalchemy.orm import relationship from sqlalchemy.orm import backref from sqlalchemy.orm import ( scoped_session, sessionmaker, ) from zope.sqlalchemy import ZopeTransactionExtension DBSession = scoped_session(sessionmaker(extension=ZopeTransactionExtension())) Base = declarative_base() LOG = logging.getLogger(__name__) NO_CONVERT = [ 'postal_code', 'elevation', ] # Many to many association tables. hypervisor_vm_assignments = Table('hypervisor_vm_assignments', Base.metadata, Column('hypervisor_id', Integer, ForeignKey('nodes.id')), Column('guest_vm_id', Integer, ForeignKey('nodes.id')) ) network_interface_assignments = Table('network_interface_assignments', Base.metadata, Column('node_id', Integer, ForeignKey('nodes.id')), Column('network_interface_id', Integer, ForeignKey('network_interfaces.id')) ) node_group_assignments = Table('node_group_assignments', Base.metadata, Column('node_id', Integer, ForeignKey('nodes.id')), Column('node_group_id', Integer, ForeignKey('node_groups.id')) ) tag_data_center_assignments = Table('tag_data_center_assignments', Base.metadata, Column('data_center_id', Integer, ForeignKey('data_centers.id')), Column('tag_id', Integer, ForeignKey('tags.id')) ) tag_node_assignments = Table('tag_node_assignments', Base.metadata, Column('node_id', Integer, ForeignKey('nodes.id')), Column('tag_id', Integer, ForeignKey('tags.id')) ) tag_node_group_assignments = Table('tag_node_group_assignments', Base.metadata, Column('node_group_id', Integer, ForeignKey('node_groups.id')), Column('tag_id', Integer, ForeignKey('tags.id')) ) tag_physical_device_assignments = Table('tag_physical_device_assignments', Base.metadata, Column('physical_device_id', Integer, ForeignKey('physical_devices.id')), Column('tag_id', Integer, ForeignKey('tags.id')) ) # Common functions def check_null_string(obj): '''Check for null string for json object.''' if not obj: return '' else: return obj def check_null_dict(obj): '''Check for null dict for json object.''' if not obj: return {} else: return obj def localize_date(obj): '''Localize dates stored in UTC in the DB to a timezone.''' try: utc = arrow.get(obj) registry = pyramid.threadlocal.get_current_registry() settings = registry.settings zone = settings['arsenal.timezone'] LOG.debug('Time zone is: {0}'.format(zone)) return utc.to(tz.gettz(zone)).format('YYYY-MM-DD HH:mm:ss') except: return 'Datetime object' def jsonify(obj): '''Convert an object or dict to json.''' LOG.debug('jsonify()') resp = {} try: convert = obj.__dict__ except AttributeError: convert = obj except: raise for param in convert: if param.startswith('_'): continue try: if param in NO_CONVERT: p_type = obj.get(param) LOG.debug('Using raw db value for param: {0} value: {1}'.format(param, p_type)) else: try: p_type = int(getattr(obj, param)) except (ValueError, TypeError): p_type = getattr(obj, param) except AttributeError: try: p_type = int(obj.get(param)) except (ValueError, TypeError): p_type = obj.get(param) # Handle datetime objects if isinstance(p_type, datetime): date = localize_date(p_type) resp[param] = date else: resp[param] = p_type return resp def get_name_id_dict(objs, default_keys=None, extra_keys=None): '''Take a list of one object and convert them to json. Returns a dict. Have to iterate over a list to get SQL Alchemy to execute the query.''' if not default_keys: default_keys = ['name', 'id'] LOG.debug('get_name_id_dict()') resp = {} for obj in objs: item = {} for key in default_keys: try: my_val = getattr(obj, key) except AttributeError: my_val = 'None' except: raise item[key] = my_val if extra_keys: for key in extra_keys: LOG.debug('Working on extra key: {0}'.format(key)) try: my_val = getattr(obj, key) except AttributeError: my_val = 'None' except: raise item[key] = my_val resp = jsonify(item) return resp def get_name_id_list(objs, default_keys=None, extra_keys=None): '''Take a list of one or more objects and convert them to json. Returns a list.''' if not default_keys: default_keys = ['name', 'id'] LOG.debug('get_name_id_list()') resp = [] for obj in objs: item = {} for key in default_keys: item[key] = getattr(obj, key) if extra_keys: for key in extra_keys: # Preserve integers in tag values. if key == 'value': try: item[key] = int(getattr(obj, key)) except ValueError: item[key] = getattr(obj, key) else: item[key] = getattr(obj, key) resp.append(jsonify(item)) return resp # Base classes class BaseAudit(Base): '''Arsenal BaseAudit object. Allows for overriding on other Audit classes.''' __abstract__ = True id = Column(Integer, primary_key=True, nullable=False) object_id = Column(Integer, nullable=False) field = Column(Text, nullable=False) old_value = Column(Text, nullable=False) new_value = Column(Text, nullable=False) created = Column(TIMESTAMP, nullable=False) updated_by = Column(Text, nullable=False) def __json__(self, request): return dict( id=self.id, object_id=self.object_id, field=self.field, old_value=self.old_value, new_value=self.new_value, created=localize_date(self.created), updated_by=self.updated_by, ) class User(Base): '''Arsenal User object.''' __tablename__ = 'users' user_id = Column(Integer, primary_key=True, nullable=False) user_name = Column(Text, nullable=False) # email address first_name = Column(Text, nullable=True) last_name = Column(Text, nullable=True) salt = Column(Text, nullable=False) password = Column(Text, nullable=False) updated_by = Column(Text, nullable=False) created = Column(TIMESTAMP, nullable=False) updated = Column(TIMESTAMP, nullable=False) @hybrid_method def get_all_assignments(self): '''Get all group assignents for the user.''' groups = [] for assign in self.local_user_group_assignments: groups.append(assign.group.group_name) return groups @hybrid_property def localize_date_created(self): '''Return localized created datetime object.''' local = localize_date(self.created) return local @hybrid_property def localize_date_updated(self): '''Return localized updated datetime object.''' local = localize_date(self.updated) return local class LocalUserGroupAssignment(Base): '''Arsenal LocalUserGroupAssignment object.''' __tablename__ = 'local_user_group_assignments' user_group_assignment_id = Column(Integer, primary_key=True, nullable=False) group_id = Column(Integer, ForeignKey('groups.group_id'), nullable=False) user_id = Column(Integer, ForeignKey('users.user_id'), nullable=False) updated_by = Column(Text, nullable=False) created = Column(TIMESTAMP, nullable=False) updated = Column(TIMESTAMP, nullable=False) user = relationship('User', backref=backref('local_user_group_assignments')) group = relationship('Group', backref=backref('local_user_group_assignments')) class Group(Base): '''Arsenal Group object.''' __tablename__ = 'groups' group_id = Column(Integer, primary_key=True, nullable=False) group_name = Column(Text, nullable=False) updated_by = Column(Text, nullable=False) created = Column(TIMESTAMP, nullable=False) updated = Column(TIMESTAMP, nullable=False) @hybrid_method def get_all_assignments(self): '''Get all permissions a group is assigned to.''' group_assign = [] for assign in self.group_perm_assignments: group_assign.append(assign.group_perms.perm_name) return group_assign @hybrid_property def localize_date_created(self): '''Return localized created datetime object.''' local = localize_date(self.created) return local @hybrid_property def localize_date_updated(self): '''Return localized updated datetime object.''' local = localize_date(self.updated) return local class GroupPermAssignment(Base): '''Arsenal GroupPermAssignment object.''' __tablename__ = 'group_perm_assignments' group_assignment_id = Column(Integer, primary_key=True, nullable=False) group_id = Column(Integer, ForeignKey('groups.group_id'), nullable=False) perm_id = Column(Integer, ForeignKey('group_perms.perm_id'), nullable=False) updated_by = Column(Text, nullable=False) created = Column(TIMESTAMP, nullable=False) updated = Column(TIMESTAMP, nullable=False) group = relationship('Group', backref=backref('group_perm_assignments')) @hybrid_method def get_assignments_by_group(self, group_name): '''Return a list of permission assignments by group name.''' query = DBSession.query(GroupPermAssignment) query = query.join(Group, GroupPermAssignment.group_id == Group.group_id) query = query.filter(Group.group_name == group_name) return query.all() @hybrid_method def get_assignments_by_perm(self, perm_name): '''Return a list of permission assignments by permission name.''' query = DBSession.query(GroupPermAssignment) query = query.join(Group, GroupPermAssignment.group_id == Group.group_id) query = query.join(GroupPerm, GroupPermAssignment.perm_id == GroupPerm.perm_id) query = query.filter(GroupPerm.perm_name == perm_name) return query.all() class GroupPerm(Base): '''Arsenal GroupPerm object.''' __tablename__ = 'group_perms' perm_id = Column(Integer, primary_key=True, nullable=False) perm_name = Column(Text, nullable=False) created = Column(TIMESTAMP, nullable=False) group_perm_assignments = relationship('GroupPermAssignment', backref=backref('group_perms'), order_by=GroupPermAssignment.created.desc, lazy='dynamic') def __repr__(self): return "GroupPerm(perm_id='%s', perm_name='%s', )" % (self.perm_id, self.perm_name) @hybrid_method def get_all_assignments(self): '''Return a list of all group permission assignments.''' perm_assign = [] for assign in self.group_perm_assignments: perm_assign.append(assign.group.group_name) return perm_assign @hybrid_method def get_group_perm_id(self, perm_name): '''Convert the perm name to the id.''' query = DBSession.query(GroupPerm) query = query.filter(GroupPerm.perm_name == '%s' % perm_name) return query.one()
{ "repo_name": "CityGrid/arsenal", "path": "server/arsenalweb/models/common.py", "copies": "1", "size": "14759", "license": "apache-2.0", "hash": 2864046689607062500, "line_mean": 34.0570071259, "line_max": 96, "alpha_frac": 0.5366217223, "autogenerated": false, "ratio": 4.63536432160804, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.002024505849727042, "num_lines": 421 }
'''Arsenal data_centers DB Model''' # Copyright 2015 CityGrid Media, LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # import logging from sqlalchemy import ( Column, ForeignKey, Integer, TIMESTAMP, Text, ) from sqlalchemy.orm import relationship from arsenalweb.models.common import ( Base, BaseAudit, get_name_id_dict, get_name_id_list, jsonify, ) LOG = logging.getLogger(__name__) class DataCenter(Base): '''Arsenal DataCenter object.''' __tablename__ = 'data_centers' id = Column(Integer, primary_key=True, nullable=False) name = Column(Text, nullable=False) status_id = Column(Integer, ForeignKey('statuses.id'), nullable=False) status = relationship('Status', backref='data_centers', lazy='joined') created = Column(TIMESTAMP, nullable=False) updated = Column(TIMESTAMP, nullable=False) updated_by = Column(Text, nullable=False) tags = relationship('Tag', secondary='tag_data_center_assignments', backref='data_centers', lazy='joined') def __json__(self, request): try: fields = request.params['fields'] if fields == 'all': # Everything. all_fields = dict( id=self.id, name=self.name, status=get_name_id_dict([self.status]), tags=get_name_id_list(self.tags, extra_keys=['value']), created=self.created, updated=self.updated, updated_by=self.updated_by, ) return jsonify(all_fields) else: # Always return name and id, then return whatever additional fields # are asked for. resp = get_name_id_dict([self]) my_fields = fields.split(',') # Backrefs are not in the instance dict, so we handle them here. if 'tags' in my_fields: resp['tags'] = get_name_id_list(self.tags, extra_keys=['value']) resp.update((key, getattr(self, key)) for key in my_fields if key in self.__dict__) return jsonify(resp) # Default to returning only name and id. except KeyError: resp = get_name_id_dict([self]) return resp class DataCenterAudit(BaseAudit): '''Arsenal DataCenterAudit object.''' __tablename__ = 'data_centers_audit'
{ "repo_name": "CityGrid/arsenal", "path": "server/arsenalweb/models/data_centers.py", "copies": "1", "size": "3125", "license": "apache-2.0", "hash": 594985754293032200, "line_mean": 30.887755102, "line_max": 83, "alpha_frac": 0.57376, "autogenerated": false, "ratio": 4.352367688022284, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.0005566680736748764, "num_lines": 98 }
'''Arsenal data_centers UI''' # Copyright 2015 CityGrid Media, LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # import logging from pyramid.view import view_config from arsenalweb.views import ( _api_get, get_authenticated_user, get_nav_urls, get_pag_params, site_layout, ) LOG = logging.getLogger(__name__) @view_config(route_name='data_center', permission='view', renderer='arsenalweb:templates/data_center.pt') def view_data_center(request): '''Handle requests for data_center UI route.''' page_title_type = 'objects/' page_title_name = 'data_center' auth_user = get_authenticated_user(request) uri = '/api/data_centers/{0}'.format(request.matchdict['id']) data_center = _api_get(request, uri) return { 'au': auth_user, 'data_center': data_center['results'][0], 'page_title_name': page_title_name, 'page_title_type': page_title_type, } @view_config(route_name='data_centers', permission='view', renderer='arsenalweb:templates/data_centers.pt') def view_data_centers(request): '''Handle requests for data_centers UI route.''' page_title_type = 'objects/' page_title_name = 'data_centers' auth_user = get_authenticated_user(request) (perpage, offset) = get_pag_params(request) payload = {} for k in request.GET: payload[k] = request.GET[k] # Force the UI to 50 results per page if not perpage: perpage = 50 payload['perpage'] = perpage uri = '/api/data_centers' LOG.info('UI requesting data from API={0},payload={1}'.format(uri, payload)) resp = _api_get(request, uri, payload) total = 0 data_centers = [] if resp: total = resp['meta']['total'] data_centers = resp['results'] nav_urls = get_nav_urls(request.path, offset, perpage, total, payload) # Used by the columns menu to determine what to show/hide. column_selectors = [ {'name': 'created', 'pretty_name': 'Date Created'}, {'name': 'name', 'pretty_name': 'Name'}, {'name': 'status', 'pretty_name': 'Status'}, {'name': 'updated', 'pretty_name': 'Date Updated'}, {'name': 'updated_by', 'pretty_name': 'Updated By'}, ] return { 'au': auth_user, 'column_selectors': column_selectors, 'layout': site_layout('max'), 'nav_urls': nav_urls, 'data_centers': data_centers, 'offset': offset, 'page_title_name': page_title_name, 'page_title_type': page_title_type, 'perpage': perpage, 'total': total, }
{ "repo_name": "CityGrid/arsenal", "path": "server/arsenalweb/views/data_centers.py", "copies": "1", "size": "3106", "license": "apache-2.0", "hash": -8721439121784910000, "line_mean": 30.06, "line_max": 107, "alpha_frac": 0.6349001932, "autogenerated": false, "ratio": 3.5375854214123006, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9670470706622549, "avg_score": 0.00040298159795015137, "num_lines": 100 }
'''Arsenal EC2 DB Model''' # Copyright 2015 CityGrid Media, LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # import logging from sqlalchemy import ( Column, Integer, TIMESTAMP, Text, ) from arsenalweb.models.common import ( Base, BaseAudit, get_name_id_dict, jsonify, localize_date, ) LOG = logging.getLogger(__name__) class Ec2Instance(Base): '''Arsenal Ec2Instance object.''' __tablename__ = 'ec2_instances' id = Column(Integer, primary_key=True, nullable=False) ami_id = Column(Text, nullable=False) hostname = Column(Text, nullable=False) instance_id = Column(Text, nullable=False) instance_type = Column(Text, nullable=False) availability_zone = Column(Text, nullable=False) profile = Column(Text, nullable=False) reservation_id = Column(Text, nullable=False) security_groups = Column(Text, nullable=False) created = Column(TIMESTAMP, nullable=False) updated = Column(TIMESTAMP, nullable=False) updated_by = Column(Text, nullable=False) def __json__(self, request): try: fields = request.params['fields'] if fields == 'all': # Everything. all_fields = dict( id=self.id, ami_id=self.ami_id, hostname=self.hostname, instance_id=self.instance_id, instance_type=self.instance_type, availability_zone=self.availability_zone, profile=self.profile, reservation_id=self.reservation_id, security_groups=self.security_groups, created=localize_date(self.created), updated=localize_date(self.updated), updated_by=self.updated_by, ) return jsonify(all_fields) else: # Always return id and instance_id, then return whatever additional fields # are asked for. resp = get_name_id_dict([self], default_keys=['id', 'instance_id']) my_fields = fields.split(',') resp.update((key, getattr(self, key)) for key in my_fields if key in self.__dict__) return jsonify(resp) # Default to returning only instance_id and id. except KeyError: resp = get_name_id_dict([self], default_keys=['id', 'instance_id']) return resp class Ec2InstanceAudit(BaseAudit): '''Arsenal Ec2InstanceAudit object.''' __tablename__ = 'ec2_instances_audit'
{ "repo_name": "CityGrid/arsenal", "path": "server/arsenalweb/models/ec2_instances.py", "copies": "1", "size": "3158", "license": "apache-2.0", "hash": 356816707042487800, "line_mean": 32.2421052632, "line_max": 90, "alpha_frac": 0.6006966434, "autogenerated": false, "ratio": 4.177248677248677, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.00024098708309234628, "num_lines": 95 }
'''Arsenal facts class''' # # Copyright 2015 CityGrid Media, LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # import os import sys import logging import subprocess import json import re try: import libvirt def libvirt_callback(ignore, err): '''Callback function to suppress libvirt warnings.''' if err[3] != libvirt.VIR_ERR_ERROR: # Don't log libvirt errors: global error handler will do that logging.warn('Non-error from libvirt: {0}'.format(err[2])) libvirt.registerErrorHandler(f=libvirt_callback, ctx=None) except ImportError: pass LOG = logging.getLogger(__name__) class ArsenalFacts(object): '''The Arsenal Facts class. Usage:: >>> from arsenalclient.arsenal_facts import ArsenalFacts >>> my_facts = ArsenalFacts() >>> my_facts.resolve() >>> print my_facts.facts['uptime'] 20:43 hours ''' def __init__(self): self.facts = { 'uptime': None, 'data_center': { 'name': None, }, 'ec2': { 'ami_id': None, 'availability_zone': None, 'hostname': None, 'instance_id': None, 'instance_type': None, 'profile': None, 'reservation_id': None, 'security_groups': None, }, 'hardware': { 'manufacturer': None, 'product_name': None, 'name': None, 'virtual': None, 'is_virtual': None, 'serial_number': 'Unknown', }, 'networking': { 'fqdn': None, 'mac_address': None, 'interfaces': {}, }, 'os': { 'name': None, 'variant': None, 'version_number': None, 'architecture': None, 'description': None, 'kernel': None, }, 'processors': { 'count': None, }, 'guest_vms': [], } self.facts_resolved = False def resolve(self, provider='_facter'): '''Resolve all Arsenal facts to their final values. Allows for swapping out facter for another fact collector of your choosing. Each fact collector must provide values for all of the facts defined in __init__ in order to function correctly.''' if not self.facts_resolved: getattr(self, provider)() LOG.debug(json.dumps(self.facts, indent=2, sort_keys=True)) LOG.debug('Setting facts_resolved = True.') self.facts_resolved = True else: LOG.debug('Facts already resolved, skipping resolution.') def _facter(self): '''Reads in facts from facter and stores them in a dict.''' LOG.debug('Gathering facts...') if os.path.isfile('/opt/puppetlabs/bin/facter'): facter_bin = '/opt/puppetlabs/bin/facter' facter_style = 'modern' else: facter_bin = 'facter' facter_style = 'legacy' LOG.debug('Using {0} facts...'.format(facter_style)) facter_cmd = [ facter_bin, '-p', '--json', ] try: proc = subprocess.Popen( facter_cmd, stdin=open(os.devnull), stdout=subprocess.PIPE, stderr=subprocess.PIPE ) stdout, stderr = proc.communicate(None) resp = json.loads(stdout) except: LOG.error('Unable to collect facts! Error: {0}'.format(stderr)) raise if facter_style == 'modern': self._map_facter_modern(resp) else: self._map_facter_legacy(resp) LOG.debug('Gathering facts complete.') def _map_facter_modern(self, resp): '''Map modern facter facts to arsenal facts for later use in the client code.''' LOG.debug('Mapping modern facts...') self.facts['uptime'] = resp['system_uptime']['uptime'] try: self.facts['hardware']['manufacturer'] = resp['dmi']['manufacturer'] self.facts['hardware']['product_name'] = resp['dmi']['product']['name'] hw_name = '{0} {1}'.format(resp['dmi']['manufacturer'], resp['dmi']['product']['name']) self.facts['hardware']['name'] = hw_name LOG.debug('Hardware profile from dmidecode.') except KeyError: try: xen_match = "xen" if re.match(xen_match, resp['virtual']) and resp['is_virtual']: self.facts['hardware']['manufacturer'] = 'Citrix' self.facts['hardware']['product_name'] = 'Xen Guest' self.facts['hardware']['name'] = 'Citrix Xen Guest' LOG.debug('Hardware profile is virtual.') except KeyError: LOG.error('Unable to determine hardware profile.') self.facts['hardware']['virtual'] = resp['virtual'] self.facts['hardware']['is_virtual'] = resp['is_virtual'] try: self.facts['hardware']['serial_number'] = resp['dmi']['product']['serial_number'] except KeyError: LOG.warn('Unable to determine serial number.') self.facts['networking']['fqdn'] = resp['networking']['fqdn'] self.facts['networking']['mac_address'] = resp['networking']['mac'] try: os_name = '{0} {1} {2}'.format(resp['os']['name'], resp['os']['distro']['release']['full'], resp['os']['architecture']) self.facts['os']['name'] = os_name self.facts['os']['variant'] = resp['os']['name'] self.facts['os']['version_number'] = resp['os']['distro']['release']['full'] self.facts['os']['architecture'] = resp['os']['architecture'] self.facts['os']['description'] = resp['os']['distro']['description'] self.facts['os']['kernel'] = resp['kernel'] except KeyError: LOG.error('Unable to determine operating system.') self.facts['processors']['count'] = resp['processors']['count'] try: self.facts['ec2']['ami_id'] = resp['ec2_metadata']['ami-id'] self.facts['ec2']['availability_zone'] = resp['ec2_metadata']['placement']['availability-zone'] self.facts['ec2']['hostname'] = resp['ec2_metadata']['hostname'] self.facts['ec2']['instance_id'] = resp['ec2_metadata']['instance-id'] self.facts['ec2']['instance_type'] = resp['ec2_metadata']['instance-type'] self.facts['ec2']['profile'] = resp['ec2_metadata']['profile'] self.facts['ec2']['reservation_id'] = resp['ec2_metadata']['reservation-id'] self.facts['ec2']['security_groups'] = resp['ec2_metadata']['security-groups'].replace('\n', ',') except KeyError: LOG.debug('ec2 facts not found, nothing to do.') self._map_network_interfaces(resp) self._map_data_center(resp) self._map_guest_vms() def _map_guest_vms(self): '''If this is a hypervisor, find it's guest vms for inclusion in the payload. Sets self.facts['guest_vms'] to a list of dicts, each with the following keys: name: The fqdn of the guest vm. unique_id: The unique_id of the guest vm. ''' # Potential to add other hypervisor types later. if 'libvirt' in sys.modules: self._map_libvirt_guests() def _map_libvirt_guests(self): '''Find guests on a libvirt managed hypervisor.''' try: try: conn = libvirt.open('qemu:///system') except libvirt.libvirtError: conn = libvirt.open('xen:///system') domains = conn.listAllDomains(0) if len(domains) != 0: for domain in domains: mac_addresses = re.search(r"<mac address='([A-Z0-9:]+)'", domain.XMLDesc(), re.IGNORECASE).groups() this_guest = { 'name': domain.name(), 'unique_id': mac_addresses[0] } self.facts['guest_vms'].append(this_guest) except: LOG.verbose('Libvirt loaded but unable to connect') def _map_network_interfaces(self, resp): '''Map network interface information for modern facter facts to arsenal facts for later use in the client. We skip loopback (unneccessary) and veth (change every time a container is restarted) interfaces from collection.''' results = {} skip_interfaces = ( 'lo', 'veth', ) for net_if in resp['networking']['interfaces']: if net_if.startswith(skip_interfaces): LOG.debug('Skipping interface: {0}'.format(net_if)) continue LOG.debug('Network interface found: {0}'.format(net_if)) results[net_if] = {} if 'ip' in resp['networking']['interfaces'][net_if]: results[net_if]['ip_address'] = resp['networking']['interfaces'][net_if]['ip'] try: if 'int_switchports' in resp: for key in resp['int_switchports'][net_if]: results[net_if][key] = resp['int_switchports'][net_if][key] except KeyError: pass # Bonded interfaces get their unique_id during the call to register. if net_if.startswith('bond'): continue if 'mac' in resp['networking']['interfaces'][net_if]: results[net_if]['unique_id'] = resp['networking']['interfaces'][net_if]['mac'] self.facts['networking']['interfaces'] = results def _map_data_center(self, resp): '''Map data_center information for modern facter facts to arsenal facts for later use in the client. We are using a custom fact for this. In the future we can make alternate implementations configrable here.''' try: self.facts['data_center']['name'] = resp['int_datacenter'] except KeyError: pass def _map_facter_legacy(self, resp): '''Map legacy facter facts to arsenal facts for later use in the client code.''' LOG.debug('Mapping legacy facts...') self.facts['uptime'] = resp['uptime'] try: self.facts['hardware']['manufacturer'] = resp['manufacturer'] self.facts['hardware']['product_name'] = resp['productname'] hw_name = '{0} {1}'.format(resp['manufacturer'], resp['productname']) self.facts['hardware']['name'] = hw_name LOG.debug('Hardware profile from dmidecode.') except KeyError: try: xen_match = "xen" if re.match(xen_match, resp['virtual']) and resp['is_virtual']: self.facts['hardware']['manufacturer'] = 'Citrix' self.facts['hardware']['product_name'] = 'Xen Guest' self.facts['hardware']['name'] = 'Citrix Xen Guest' LOG.debug('Hardware profile is virtual.') except KeyError: LOG.error('Unable to determine hardware profile.') self.facts['hardware']['virtual'] = resp['virtual'] self.facts['hardware']['is_virtual'] = resp['is_virtual'] try: self.facts['hardware']['serial_number'] = resp['serialnumber'] except KeyError: LOG.warn('Unable to determine serial number.') self.facts['networking']['fqdn'] = resp['fqdn'] self.facts['networking']['mac_address'] = resp['macaddress'] try: os_name = '{0} {1} {2}'.format(resp['operatingsystem'], resp['operatingsystemrelease'], resp['architecture']) self.facts['os']['name'] = os_name self.facts['os']['variant'] = resp['operatingsystem'] self.facts['os']['version_number'] = resp['operatingsystemrelease'] self.facts['os']['architecture'] = resp['architecture'] self.facts['os']['description'] = resp['lsbdistdescription'] self.facts['os']['kernel'] = resp['kernel'] except KeyError: LOG.error('Unable to determine operating system.') self.facts['processors']['count'] = resp['processorcount'] try: self.facts['ec2']['instance_id'] = resp['ec2_instance_id'] self.facts['ec2']['hostname'] = resp['ec2_hostname'] self.facts['ec2']['ami_id'] = resp['ec2_ami_id'] self.facts['ec2']['public_hostname'] = resp['ec2_public_hostname'] self.facts['ec2']['instance_type'] = resp['ec2_instance_type'] self.facts['ec2']['security_groups'] = resp['ec2_security_groups'] self.facts['ec2']['availability_zone'] = resp['ec2_placement_availability_zone'] except KeyError: pass
{ "repo_name": "CityGrid/arsenal", "path": "client/arsenalclient/arsenal_facts.py", "copies": "1", "size": "14009", "license": "apache-2.0", "hash": -8708454831142906000, "line_mean": 39.7238372093, "line_max": 109, "alpha_frac": 0.5303019487, "autogenerated": false, "ratio": 4.335809346951408, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5366111295651408, "avg_score": null, "num_lines": null }
'''Arsenal hardware_profiles DB Model''' # Copyright 2015 CityGrid Media, LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # import logging from sqlalchemy.ext.hybrid import hybrid_method from sqlalchemy import ( Column, Integer, TIMESTAMP, Text, ) from arsenalweb.models.common import ( Base, BaseAudit, DBSession, get_name_id_dict, jsonify, localize_date, ) LOG = logging.getLogger(__name__) class HardwareProfile(Base): '''Arsenal HardwareProfile object.''' __tablename__ = 'hardware_profiles' id = Column(Integer, primary_key=True, nullable=False) name = Column(Text, nullable=False) model = Column(Text, nullable=False) manufacturer = Column(Text, nullable=False) created = Column(TIMESTAMP, nullable=False) updated = Column(TIMESTAMP, nullable=False) updated_by = Column(Text, nullable=False) @hybrid_method def get_hardware_profile_id(self, manufacturer, model): '''Find a hardware_profile id by name.''' query = DBSession.query(HardwareProfile) query = query.filter(HardwareProfile.manufacturer == '%s' % manufacturer) query = query.filter(HardwareProfile.model == '%s' % model) try: hw_profile = query.one() return hw_profile.id except: return None def __json__(self, request): try: if request.path_info.startswith('/api/hardware_profiles'): fields = request.params['fields'] if fields == 'all': # Everything. all_fields = dict( id=self.id, name=self.name, model=self.model, manufacturer=self.manufacturer, created=localize_date(self.created), updated=localize_date(self.updated), updated_by=self.updated_by, ) return jsonify(all_fields) else: # Always return name and id, then return whatever additional fields # are asked for. resp = get_name_id_dict([self]) my_fields = fields.split(',') resp.update((key, getattr(self, key)) for key in my_fields if key in self.__dict__) return jsonify(resp) # Default to returning only name and id. except (KeyError, UnboundLocalError): resp = get_name_id_dict([self]) return resp class HardwareProfileAudit(BaseAudit): '''Arsenal HardwareProfileAudit object.''' __tablename__ = 'hardware_profiles_audit'
{ "repo_name": "CityGrid/arsenal", "path": "server/arsenalweb/models/hardware_profiles.py", "copies": "1", "size": "3192", "license": "apache-2.0", "hash": 7994315504186905000, "line_mean": 30.603960396, "line_max": 83, "alpha_frac": 0.6049498747, "autogenerated": false, "ratio": 4.284563758389262, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5389513633089262, "avg_score": null, "num_lines": null }
'''Arsenal hardware_profiles UI.''' # Copyright 2015 CityGrid Media, LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # import logging from pyramid.view import view_config from arsenalweb.views import ( _api_get, get_authenticated_user, get_nav_urls, get_pag_params, site_layout, ) LOG = logging.getLogger(__name__) @view_config(route_name='hardware_profile', permission='view', renderer='arsenalweb:templates/hardware_profile.pt') def view_hardware_profile(request): '''Handle requests for hardware_profile UI route.''' page_title_type = 'objects/' page_title_name = 'hardware_profile' auth_user = get_authenticated_user(request) uri = '/api/hardware_profiles/{0}'.format(request.matchdict['id']) hardware_profile = _api_get(request, uri) return { 'au': auth_user, 'hardware_profile': hardware_profile['results'][0], 'page_title_name': page_title_name, 'page_title_type': page_title_type, } @view_config(route_name='hardware_profiles', permission='view', renderer='arsenalweb:templates/hardware_profiles.pt') def view_hardware_profiles(request): '''Handle requests for hardware profiles UI route.''' page_title_type = 'objects/' page_title_name = 'hardware_profiles' auth_user = get_authenticated_user(request) (perpage, offset) = get_pag_params(request) payload = {} for k in request.GET: payload[k] = request.GET[k] # Force the UI to 50 results per page if not perpage: perpage = 50 payload['perpage'] = perpage uri = '/api/hardware_profiles' LOG.info('UI requesting data from API={0},payload={1}'.format(uri, payload)) resp = _api_get(request, uri, payload) total = 0 hardware_profiles = [] if resp: total = resp['meta']['total'] hardware_profiles = resp['results'] nav_urls = get_nav_urls(request.path, offset, perpage, total, payload) # Used by the columns menu to determine what to show/hide. column_selectors = [ {'name': 'created', 'pretty_name': 'Date Created'}, {'name': 'hardware_profile_id', 'pretty_name': 'Hardware Profile ID'}, {'name': 'manufacturer', 'pretty_name': 'Manufacturer'}, {'name': 'model', 'pretty_name': 'Model'}, {'name': 'updated', 'pretty_name': 'Date Updated'}, {'name': 'updated_by', 'pretty_name': 'Updated By'}, ] return { 'au': auth_user, 'column_selectors': column_selectors, 'hardware_profiles': hardware_profiles, 'layout': site_layout('max'), 'nav_urls': nav_urls, 'offset': offset, 'page_title_name': page_title_name, 'page_title_type': page_title_type, 'perpage': perpage, 'total': total, }
{ "repo_name": "CityGrid/arsenal", "path": "server/arsenalweb/views/hardware_profiles.py", "copies": "1", "size": "3300", "license": "apache-2.0", "hash": 4167211278943553000, "line_mean": 31.6732673267, "line_max": 117, "alpha_frac": 0.6466666667, "autogenerated": false, "ratio": 3.670745272525028, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.48174119392250275, "avg_score": null, "num_lines": null }
'''Arsenal home UI.''' # Copyright 2015 CityGrid Media, LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # import logging from pyramid.view import view_config from pyramid.response import Response from datetime import datetime from datetime import timedelta import arrow from arsenalweb.views import ( get_authenticated_user, site_layout, ) from arsenalweb.models.common import ( DBSession, User, ) LOG = logging.getLogger(__name__) @view_config(route_name='home', permission='view', renderer='arsenalweb:templates/home.pt') def view_home(request): '''Handle requests for home UI route.''' page_title_type = '_' page_title_name = 'Home' auth_user = get_authenticated_user(request) # Used by the columns menu to determine what to show/hide. column_selectors = [ {'name': 'created', 'pretty_name': 'Date Created'}, {'name': 'description', 'pretty_name': 'Description'}, {'name': 'status_id', 'pretty_name': 'Status ID'}, {'name': 'status_name', 'pretty_name': 'Status Name'}, {'name': 'updated', 'pretty_name': 'Date Update'}, {'name': 'updated_by', 'pretty_name': 'Updated By'}, ] return { 'au': auth_user, 'column_selectors': column_selectors, 'layout': site_layout('max'), 'page_title_name': page_title_name, 'page_title_type': page_title_type, }
{ "repo_name": "CityGrid/arsenal", "path": "server/arsenalweb/views/home.py", "copies": "1", "size": "1912", "license": "apache-2.0", "hash": -2541681411239290000, "line_mean": 32.5438596491, "line_max": 91, "alpha_frac": 0.6668410042, "autogenerated": false, "ratio": 3.734375, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.49012160041999997, "avg_score": null, "num_lines": null }
'''Arsenal ip_addresses DB Model''' # Copyright 2015 CityGrid Media, LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # import logging from sqlalchemy import ( Column, Integer, TIMESTAMP, Text, ) from arsenalweb.models.common import ( Base, BaseAudit, get_name_id_dict, get_name_id_list, jsonify, ) LOG = logging.getLogger(__name__) class IpAddress(Base): '''Arsenal IpAddress object.''' __tablename__ = 'ip_addresses' id = Column(Integer, primary_key=True, nullable=False) ip_address = Column(Text, nullable=False) created = Column(TIMESTAMP, nullable=False) updated = Column(TIMESTAMP, nullable=False) updated_by = Column(Text, nullable=False) def __json__(self, request): try: fields = request.params['fields'] if fields == 'all': # Everything. all_fields = dict( id=self.id, ip_address=self.ip_address, network_interfaces=get_name_id_list(self.network_interfaces), created=self.created, updated=self.updated, updated_by=self.updated_by, ) return jsonify(all_fields) else: # Always return ip_address and id, then return whatever additional fields # are asked for. resp = get_name_id_dict([self], default_keys=['id', 'ip_address']) my_fields = fields.split(',') resp.update((key, getattr(self, key)) for key in my_fields if key in self.__dict__) # Backrefs are not in the instance dict, so we handle them here. if 'network_interfaces' in my_fields: resp['network_interfaces'] = get_name_id_list(self.network_interfaces) return jsonify(resp) # Default to returning only ip_address and id. except KeyError: resp = get_name_id_dict([self], default_keys=['id', 'ip_address']) return resp class IpAddressAudit(BaseAudit): '''Arsenal IpAddressAudit object.''' __tablename__ = 'ip_addresses_audit'
{ "repo_name": "CityGrid/arsenal", "path": "server/arsenalweb/models/ip_addresses.py", "copies": "1", "size": "2744", "license": "apache-2.0", "hash": 2336409031349168600, "line_mean": 30.9069767442, "line_max": 90, "alpha_frac": 0.595845481, "autogenerated": false, "ratio": 4.182926829268292, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5278772310268293, "avg_score": null, "num_lines": null }
'''Arsenal ip_addresses UI.''' # Copyright 2015 CityGrid Media, LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # import logging from pyramid.view import view_config from arsenalweb.views import ( _api_get, get_authenticated_user, get_nav_urls, get_pag_params, site_layout, ) LOG = logging.getLogger(__name__) @view_config(route_name='ip_address', permission='view', renderer='arsenalweb:templates/ip_address.pt') def view_ip_address(request): '''Handle requests for ip_address UI route.''' page_title_type = 'objects/' page_title_name = 'ip_address' auth_user = get_authenticated_user(request) uri = '/api/ip_addresses/{0}'.format(request.matchdict['id']) ip_address = _api_get(request, uri) return { 'au': auth_user, 'ip_address': ip_address['results'][0], 'page_title_name': page_title_name, 'page_title_type': page_title_type, } @view_config(route_name='ip_addresses', permission='view', renderer='arsenalweb:templates/ip_addresses.pt') def view_ip_addresses(request): '''Handle requests for ip_addresses UI route.''' page_title_type = 'objects/' page_title_name = 'ip_addresses' auth_user = get_authenticated_user(request) (perpage, offset) = get_pag_params(request) payload = {} for k in request.GET: payload[k] = request.GET[k] # Force the UI to 50 results per page if not perpage: perpage = 50 payload['perpage'] = perpage uri = '/api/ip_addresses' LOG.info('UI requesting data from API={0},payload={1}'.format(uri, payload)) resp = _api_get(request, uri, payload) total = 0 ip_addresses = [] if resp: total = resp['meta']['total'] ip_addresses = resp['results'] nav_urls = get_nav_urls(request.path, offset, perpage, total, payload) # Used by the columns menu to determine what to show/hide. column_selectors = [ {'name': 'created', 'pretty_name': 'Date Created'}, {'name': 'ip_address', 'pretty_name': 'IP Address'}, {'name': 'ip_address_id', 'pretty_name': 'IP Address ID'}, {'name': 'updated', 'pretty_name': 'Date Updated'}, {'name': 'updated_by', 'pretty_name': 'Updated By'}, ] return { 'au': auth_user, 'column_selectors': column_selectors, 'ip_addresses': ip_addresses, 'layout': site_layout('max'), 'nav_urls': nav_urls, 'offset': offset, 'page_title_name': page_title_name, 'page_title_type': page_title_type, 'perpage': perpage, 'total': total, }
{ "repo_name": "CityGrid/arsenal", "path": "server/arsenalweb/views/ip_addresses.py", "copies": "1", "size": "3125", "license": "apache-2.0", "hash": -1579289000008893700, "line_mean": 30.25, "line_max": 107, "alpha_frac": 0.63488, "autogenerated": false, "ratio": 3.5231116121758737, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.46579916121758735, "avg_score": null, "num_lines": null }
'''Arsenal login page.''' # Copyright 2015 CityGrid Media, LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # import logging from pyramid.view import view_config, forbidden_view_config from pyramid.httpexceptions import HTTPOk from pyramid.httpexceptions import HTTPFound from pyramid.httpexceptions import HTTPUnauthorized from pyramid.httpexceptions import HTTPForbidden from pyramid.security import remember from pyramid.session import signed_serialize from pyramid_ldap import get_ldap_connector from arsenalweb.views import ( db_authenticate, get_authenticated_user, pam_authenticate, site_layout, ) LOG = logging.getLogger(__name__) @view_config(route_name='login', renderer='arsenalweb:templates/login.pt') @forbidden_view_config(renderer='arsenalweb:templates/login.pt') def login(request): '''Process requests for the /login route.''' page_title = 'Login' LOG.debug('Processing login request...') auth_user = get_authenticated_user(request) if request.referer: referer_host = request.referer.split('/')[2] else: referer_host = None # Need to send the client a 401 so it can send a user/pass to auth. # Without this the client just gets the login page with a 200 and # thinks the command was successful. if request.path_info.split('/')[1][:3] == 'api' and not request.authenticated_userid: LOG.debug('request came from the api, sending request to re-auth') return HTTPUnauthorized() if request.referer and referer_host == request.host \ and request.referer.split('/')[3][:6] != 'logout': return_url = request.referer elif request.path != '/login': return_url = request.url else: return_url = '/nodes' login_name = '' password = '' error = '' if 'form.submitted' in request.POST: login_name = request.POST['login'] password = request.POST['password'] LOG.debug('Attempting to authenticate login: {0}'.format(login_name)) # Try local first, ldap/pam second (if configured) LOG.debug('Authenticating against local DB...') data = db_authenticate(login_name, password) if data is None and request.registry.settings['arsenal.use_ldap']: LOG.debug('Authenticating against LDAP...') connector = get_ldap_connector(request) data = connector.authenticate(login_name, password) if data is None and request.registry.settings['arsenal.use_pam']: LOG.debug('Authenticating against PAM...') data = pam_authenticate(login_name, password) if data is not None: user_name = data[0] encrypted = signed_serialize(login_name, request.registry.settings['arsenal.cookie_token']) headers = remember(request, user_name) headers.append(('Set-Cookie', 'un=' + str(encrypted) + '; Max-Age=604800; Path=/')) if 'api.client' in request.POST: return HTTPOk(headers=headers) else: return HTTPFound(request.POST['return_url'], headers=headers) else: error = 'Invalid credentials' request.response.status = 403 if request.authenticated_userid: if request.path == '/login': error = 'You are already logged in' page_title = 'Already Logged In' else: error = 'You do not have permission to access this page' page_title = 'Access Denied' request.response.status = 403 return { 'au': auth_user, 'error': error, 'layout': site_layout('max'), 'login': login_name, 'page_title': page_title, 'password': password, 'return_url': return_url, }
{ "repo_name": "CityGrid/arsenal", "path": "server/arsenalweb/views/login.py", "copies": "1", "size": "4340", "license": "apache-2.0", "hash": 4483435209964893000, "line_mean": 34.867768595, "line_max": 95, "alpha_frac": 0.6453917051, "autogenerated": false, "ratio": 4.09433962264151, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.0003779394737892762, "num_lines": 121 }
'''Arsenal network_interfaces DB Model''' # Copyright 2015 CityGrid Media, LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # import logging from sqlalchemy import ( Column, ForeignKey, Integer, TIMESTAMP, Text, ) from sqlalchemy.orm import relationship from arsenalweb.models.common import ( Base, BaseAudit, get_name_id_dict, get_name_id_list, jsonify, ) LOG = logging.getLogger(__name__) class NetworkInterface(Base): '''Arsenal NetworkInterface object.''' __tablename__ = 'network_interfaces' id = Column(Integer, primary_key=True, nullable=False) name = Column(Text, nullable=False) unique_id = Column(Text, nullable=False) ip_address_id = Column(Integer, ForeignKey('ip_addresses.id'), nullable=True) ip_address = relationship('IpAddress', backref='network_interfaces', lazy='joined') bond_master = Column(Text, nullable=True) port_description = Column(Text, nullable=True) port_number = Column(Text, nullable=True) port_switch = Column(Text, nullable=True) port_vlan = Column(Text, nullable=True) created = Column(TIMESTAMP, nullable=False) updated = Column(TIMESTAMP, nullable=False) updated_by = Column(Text, nullable=False) def __json__(self, request): try: fields = request.params['fields'] if fields == 'all': # Everything. all_fields = dict( id=self.id, name=self.name, unique_id=self.unique_id, ip_address=get_name_id_dict([self.ip_address], default_keys=['id', 'ip_address']), bond_master=self.bond_master, port_description=self.port_description, port_number=self.port_number, port_switch=self.port_switch, port_vlan=self.port_vlan, nodes=get_name_id_list(self.nodes), created=self.created, updated=self.updated, updated_by=self.updated_by, ) return jsonify(all_fields) else: # Always return name, id, and unique_id, then return whatever # additional fields are asked for. resp = get_name_id_dict([self], extra_keys=['unique_id']) my_fields = fields.split(',') # Backrefs are not in the instance dict, so we handle them here. if 'nodes' in my_fields: resp['nodes'] = get_name_id_list(self.nodes) resp.update((key, getattr(self, key)) for key in my_fields if key in self.__dict__) return jsonify(resp) # Default to returning only name, id, and unique_id. except KeyError: resp = get_name_id_dict([self], extra_keys=['unique_id']) return resp class NetworkInterfaceAudit(BaseAudit): '''Arsenal NetworkInterfaceAudit object.''' __tablename__ = 'network_interfaces_audit'
{ "repo_name": "CityGrid/arsenal", "path": "server/arsenalweb/models/network_interfaces.py", "copies": "1", "size": "3717", "license": "apache-2.0", "hash": 5417627122003131000, "line_mean": 33.4166666667, "line_max": 83, "alpha_frac": 0.5829970406, "autogenerated": false, "ratio": 4.277330264672037, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5360327305272037, "avg_score": null, "num_lines": null }
'''Arsenal network_interfaces UI''' # Copyright 2015 CityGrid Media, LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # import logging from pyramid.view import view_config from arsenalweb.views import ( _api_get, get_authenticated_user, get_nav_urls, get_pag_params, site_layout, ) LOG = logging.getLogger(__name__) @view_config(route_name='network_interface', permission='view', renderer='arsenalweb:templates/network_interface.pt') def view_network_interface(request): '''Handle requests for network_interface UI route.''' page_title_type = 'objects/' page_title_name = 'network_interface' auth_user = get_authenticated_user(request) uri = '/api/network_interfaces/{0}'.format(request.matchdict['id']) network_interface = _api_get(request, uri) return { 'au': auth_user, 'network_interface': network_interface['results'][0], 'page_title_name': page_title_name, 'page_title_type': page_title_type, } @view_config(route_name='network_interfaces', permission='view', renderer='arsenalweb:templates/network_interfaces.pt') def view_network_interfaces(request): '''Handle requests for network_interfaces UI route.''' page_title_type = 'objects/' page_title_name = 'network_interfaces' auth_user = get_authenticated_user(request) (perpage, offset) = get_pag_params(request) payload = {} for k in request.GET: payload[k] = request.GET[k] # Force the UI to 50 results per page if not perpage: perpage = 50 payload['perpage'] = perpage uri = '/api/network_interfaces' LOG.info('UI requesting data from API={0},payload={1}'.format(uri, payload)) resp = _api_get(request, uri, payload) total = 0 network_interfaces = [] if resp: total = resp['meta']['total'] network_interfaces = resp['results'] nav_urls = get_nav_urls(request.path, offset, perpage, total, payload) # Used by the columns menu to determine what to show/hide. column_selectors = [ {'name': 'bond_master', 'pretty_name': 'Bond Master'}, {'name': 'created', 'pretty_name': 'Date Created'}, {'name': 'ip_address', 'pretty_name': 'IP Address'}, {'name': 'name', 'pretty_name': 'Name'}, {'name': 'network_interface_id', 'pretty_name': 'Network Interface ID'}, {'name': 'port_description', 'pretty_name': 'Port Description'}, {'name': 'port_number', 'pretty_name': 'Port Number'}, {'name': 'port_switch', 'pretty_name': 'Switch'}, {'name': 'port_vlan', 'pretty_name': 'VLAN'}, {'name': 'unique_id', 'pretty_name': 'Unique ID'}, {'name': 'updated', 'pretty_name': 'Date Updated'}, {'name': 'updated_by', 'pretty_name': 'Updated By'}, ] return { 'au': auth_user, 'column_selectors': column_selectors, 'layout': site_layout('max'), 'nav_urls': nav_urls, 'network_interfaces': network_interfaces, 'offset': offset, 'page_title_name': page_title_name, 'page_title_type': page_title_type, 'perpage': perpage, 'total': total, }
{ "repo_name": "CityGrid/arsenal", "path": "server/arsenalweb/views/network_interfaces.py", "copies": "1", "size": "3685", "license": "apache-2.0", "hash": 309921261752176000, "line_mean": 33.4392523364, "line_max": 119, "alpha_frac": 0.6366350068, "autogenerated": false, "ratio": 3.6521308225966305, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.478876582939663, "avg_score": null, "num_lines": null }
'''Arsenal node_groups DB Model''' # Copyright 2015 CityGrid Media, LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # import logging from sqlalchemy.ext.hybrid import hybrid_method from sqlalchemy import ( Column, Integer, TIMESTAMP, Text, ) from sqlalchemy.orm import relationship from arsenalweb.models.common import ( Base, BaseAudit, DBSession, get_name_id_dict, get_name_id_list, jsonify, ) LOG = logging.getLogger(__name__) class NodeGroup(Base): '''Arsenal NodeGroup object.''' __tablename__ = 'node_groups' id = Column(Integer, primary_key=True, nullable=False) name = Column(Text, nullable=False) owner = Column(Text, nullable=False) description = Column(Text, nullable=False) notes_url = Column(Text, nullable=True) created = Column(TIMESTAMP, nullable=False) updated = Column(TIMESTAMP, nullable=False) updated_by = Column(Text, nullable=False) tags = relationship('Tag', secondary='tag_node_group_assignments', backref='node_groups', lazy='joined') @hybrid_method def find_node_group_by_name(self, name): '''Find a node_group by name.''' query = DBSession.query(NodeGroup) query = query.filter(NodeGroup.name == '%s' % name) return query.one() def __json__(self, request): try: fields = request.params['fields'] if fields == 'all': # Everything. all_fields = dict( id=self.id, name=self.name, owner=self.owner, description=self.description, notes_url=self.notes_url, tags=get_name_id_list(self.tags, extra_keys=['value']), nodes=get_name_id_list(self.nodes), created=self.created, updated=self.updated, updated_by=self.updated_by, ) return jsonify(all_fields) else: # Always return name and id, then return whatever additional fields # are asked for. resp = get_name_id_dict([self]) my_fields = fields.split(',') # Backrefs are not in the instance dict, so we handle them here. if 'nodes' in my_fields: resp['nodes'] = get_name_id_list(self.nodes) if 'tags' in my_fields: resp['tags'] = get_name_id_list(self.tags, extra_keys=['value']) resp.update((key, getattr(self, key)) for key in my_fields if key in self.__dict__) return jsonify(resp) # Default to returning only name, id, and unique_id. except KeyError: resp = get_name_id_dict([self]) return resp class NodeGroupAudit(BaseAudit): '''Arsenal NodeGroupAudit object.''' __tablename__ = 'node_groups_audit'
{ "repo_name": "CityGrid/arsenal", "path": "server/arsenalweb/models/node_groups.py", "copies": "1", "size": "3631", "license": "apache-2.0", "hash": -5454191541481278000, "line_mean": 30.850877193, "line_max": 83, "alpha_frac": 0.5678876343, "autogenerated": false, "ratio": 4.251756440281031, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.531964407458103, "avg_score": null, "num_lines": null }
'''Arsenal node_groups UI.''' # Copyright 2015 CityGrid Media, LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # import logging from pyramid.view import view_config from arsenalweb.views import ( _api_get, get_authenticated_user, get_nav_urls, get_pag_params, site_layout, ) LOG = logging.getLogger(__name__) @view_config(route_name='node_group', permission='view', renderer='arsenalweb:templates/node_group.pt') def view_node_group(request): '''Handle requests for node_group UI route.''' page_title = 'Node Group' auth_user = get_authenticated_user(request) uri = '/api/node_groups/{0}'.format(request.matchdict['id']) node_group = _api_get(request, uri) return { 'au': auth_user, 'node_group': node_group['results'][0], 'page_title': page_title, } @view_config(route_name='node_groups', permission='view', renderer='arsenalweb:templates/node_groups.pt') def view_node_groups(request): '''Handle requests for node groups UI route.''' page_title_type = 'objects/' page_title_name = 'node_groups' auth_user = get_authenticated_user(request) (perpage, offset) = get_pag_params(request) payload = {} for k in request.GET: payload[k] = request.GET[k] # Force the UI to 50 results per page if not perpage: perpage = 50 payload['perpage'] = perpage uri = '/api/node_groups' LOG.info('UI requesting data from API={0},payload={1}'.format(uri, payload)) resp = _api_get(request, uri, payload) total = 0 node_groups = [] if resp: total = resp['meta']['total'] node_groups = resp['results'] nav_urls = get_nav_urls(request.path, offset, perpage, total, payload) # Used by the columns menu to determine what to show/hide. column_selectors = [ {'name': 'created', 'pretty_name': 'Date Created'}, {'name': 'description', 'pretty_name': 'Node Group Description'}, {'name': 'node_group_id', 'pretty_name': 'Node Group ID'}, {'name': 'node_group_name', 'pretty_name': 'Node Group Name'}, {'name': 'notes_url', 'pretty_name': 'Notes URL'}, {'name': 'owner', 'pretty_name': 'Node Group Owner'}, {'name': 'updated', 'pretty_name': 'Date Updated'}, {'name': 'updated_by', 'pretty_name': 'Updated By'}, ] return { 'au': auth_user, 'column_selectors': column_selectors, 'layout': site_layout('max'), 'nav_urls': nav_urls, 'node_groups': node_groups, 'offset': offset, 'page_title_name': page_title_name, 'page_title_type': page_title_type, 'perpage': perpage, 'total': total, }
{ "repo_name": "CityGrid/arsenal", "path": "server/arsenalweb/views/node_groups.py", "copies": "1", "size": "3226", "license": "apache-2.0", "hash": 2117727284921581000, "line_mean": 30.9405940594, "line_max": 105, "alpha_frac": 0.6292622443, "autogenerated": false, "ratio": 3.5411635565312842, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.46704258008312843, "avg_score": null, "num_lines": null }
'''Arsenal nodes DB Model''' # Copyright 2015 CityGrid Media, LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # import logging from sqlalchemy import ( Column, ForeignKey, Integer, TIMESTAMP, Text, ) from sqlalchemy.orm import relationship from sqlalchemy.orm import backref from arsenalweb.models.common import ( Base, BaseAudit, check_null_dict, check_null_string, get_name_id_dict, get_name_id_list, hypervisor_vm_assignments, jsonify, ) LOG = logging.getLogger(__name__) class Node(Base): '''Arsenal Node object.''' __tablename__ = 'nodes' id = Column(Integer, primary_key=True, nullable=False) name = Column(Text, nullable=False) unique_id = Column(Text, nullable=False) status_id = Column(Integer, ForeignKey('statuses.id'), nullable=False) hardware_profile_id = Column(Integer, ForeignKey('hardware_profiles.id'), nullable=False) operating_system_id = Column(Integer, ForeignKey('operating_systems.id'), nullable=False) ec2_id = Column(Integer, ForeignKey('ec2_instances.id')) data_center_id = Column(Integer, ForeignKey('data_centers.id')) uptime = Column(Text, nullable=False) serial_number = Column(Text, ForeignKey('physical_devices.serial_number')) processor_count = Column(Integer) last_registered = Column(TIMESTAMP) created = Column(TIMESTAMP, nullable=False) updated = Column(TIMESTAMP, nullable=False) updated_by = Column(Text, nullable=False) status = relationship('Status', backref='nodes', lazy='joined') hardware_profile = relationship('HardwareProfile', backref=backref('nodes'), lazy='joined') operating_system = relationship('OperatingSystem', backref=backref('nodes'), lazy='joined') ec2_instance = relationship('Ec2Instance', backref=backref('nodes'), lazy='joined') data_center = relationship('DataCenter', backref=backref('nodes'), lazy='joined') physical_device = relationship('PhysicalDevice', backref=backref('nodes'), lazy='joined', foreign_keys=[serial_number]) node_groups = relationship('NodeGroup', secondary='node_group_assignments', backref='nodes', lazy='dynamic') tags = relationship('Tag', secondary='tag_node_assignments', backref='nodes', lazy='dynamic') network_interfaces = relationship('NetworkInterface', secondary='network_interface_assignments', backref='nodes', lazy='dynamic') hypervisor = relationship('Node', secondary='hypervisor_vm_assignments', primaryjoin=hypervisor_vm_assignments.c.hypervisor_id == id, secondaryjoin=hypervisor_vm_assignments.c.guest_vm_id == id, backref='guest_vms', lazy='dynamic') def __json__(self, request): try: fields = request.params['fields'] if fields == 'all': # Everything. all_fields = dict( id=self.id, name=self.name, unique_id=self.unique_id, status=get_name_id_dict([self.status]), hardware_profile=get_name_id_dict([self.hardware_profile]), operating_system=get_name_id_dict([self.operating_system]), ec2_instance=check_null_dict(self.ec2_instance), data_center=get_name_id_dict([self.data_center]), uptime=check_null_string(self.uptime), serial_number=check_null_string(self.serial_number), processor_count=check_null_string(self.processor_count), node_groups=get_name_id_list(self.node_groups), tags=get_name_id_list(self.tags, extra_keys=['value']), network_interfaces=get_name_id_list(self.network_interfaces, extra_keys=[ 'unique_id', ]), guest_vms=get_name_id_list(self.guest_vms), hypervisor=get_name_id_list(self.hypervisor), physical_device=self.physical_device, last_registered=self.last_registered, created=self.created, updated=self.updated, updated_by=self.updated_by, ) return jsonify(all_fields) else: # Always return name id and unique_id, then return whatever additional fields # are asked for. resp = get_name_id_dict([self], extra_keys=['unique_id']) my_fields = fields.split(',') # Backrefs are not in the instance dict, so we handle them here. if 'node_groups' in my_fields: resp['node_groups'] = get_name_id_list(self.node_groups) if 'hypervisor' in my_fields: resp['hypervisor'] = get_name_id_list(self.hypervisor) if 'guest_vms' in my_fields: my_guest_vms = get_name_id_list(self.guest_vms) if my_guest_vms: resp['guest_vms'] = my_guest_vms # Need this so we don't return an empty list of guest_vms # for each guest vm. else: del resp['guest_vms'] if 'tags' in my_fields: resp['tags'] = get_name_id_list(self.tags, extra_keys=['value']) if 'network_interfaces' in my_fields: resp['network_interfaces'] = get_name_id_list(self.network_interfaces, extra_keys=[ 'unique_id', 'ip_address', 'bond_master', 'port_description', 'port_number', 'port_switch', 'port_vlan', ]) resp.update((key, getattr(self, key)) for key in my_fields if key in self.__dict__) return jsonify(resp) # Default to returning only name, id, and unique_id. except KeyError: resp = get_name_id_dict([self], extra_keys=['unique_id']) return resp class NodeAudit(BaseAudit): '''Arsenal NodeAudit object.''' __tablename__ = 'nodes_audit'
{ "repo_name": "CityGrid/arsenal", "path": "server/arsenalweb/models/nodes.py", "copies": "1", "size": "7921", "license": "apache-2.0", "hash": -1277032278955777500, "line_mean": 45.0523255814, "line_max": 95, "alpha_frac": 0.5052392375, "autogenerated": false, "ratio": 4.871463714637146, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5876702952137147, "avg_score": null, "num_lines": null }
'''Arsenal nodes UI.''' # Copyright 2015 CityGrid Media, LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # import logging from pyramid.view import view_config from arsenalweb.views import ( _api_get, get_authenticated_user, get_nav_urls, get_pag_params, site_layout, ) LOG = logging.getLogger(__name__) @view_config(route_name='node', permission='view', renderer='arsenalweb:templates/node.pt') def view_node(request): '''Handle requests for node UI route.''' page_title = 'Node' auth_user = get_authenticated_user(request) uri = '/api/nodes/{0}'.format(request.matchdict['id']) resp = _api_get(request, uri) node = resp['results'][0] # We need all the info about network_interfaces for display in the UI. net_ifs = [] for net_if in node['network_interfaces']: LOG.debug('Getting network interface: {0}'.format(net_if)) uri = '/api/network_interfaces/{0}'.format(net_if['id']) resp = _api_get(request, uri) net_ifs.append(resp['results'][0]) node['network_interfaces'] = sorted(net_ifs, key=lambda k: k['name']) LOG.debug('network interfaces: {0}'.format(node['network_interfaces'])) # We need all the info about the physcial_device for display in the UI. if node['physical_device']: LOG.debug('Getting physical_device: {0}'.format(node['physical_device']['serial_number'])) uri = '/api/physical_devices/{0}'.format(node['physical_device']['id']) resp = _api_get(request, uri) node['physical_device'] = resp['results'][0] return { 'au': auth_user, 'node': node, 'page_title': page_title, } @view_config(route_name='nodes', permission='view', renderer='arsenalweb:templates/nodes.pt') def view_nodes(request): '''Handle requests for nodes UI route.''' page_title_type = 'objects/' page_title_name = 'nodes' auth_user = get_authenticated_user(request) (perpage, offset) = get_pag_params(request) payload = {} for k in request.GET: payload[k] = request.GET[k] # Force the UI to 50 results per page if not perpage: perpage = 50 payload['perpage'] = perpage uri = '/api/nodes' LOG.info('UI requesting data from API={0},payload={1}'.format(uri, payload)) resp = _api_get(request, uri, payload) total = 0 nodes = [] if resp: total = resp['meta']['total'] nodes = resp['results'] nav_urls = get_nav_urls(request.path, offset, perpage, total, payload) # Used by the columns menu to determine what to show/hide. column_selectors = [ {'name': 'created', 'pretty_name': 'Date Created'}, {'name': 'hardware_profile', 'pretty_name': 'Hardware Profile'}, {'name': 'last_registered', 'pretty_name': 'Last Registered'}, {'name': 'node_groups', 'pretty_name': 'Node Groups'}, {'name': 'serial_number', 'pretty_name': 'Serial Number'}, {'name': 'node_id', 'pretty_name': 'Node ID'}, {'name': 'node_name', 'pretty_name': 'Node Name'}, {'name': 'operating_system', 'pretty_name': 'Operating System'}, {'name': 'status', 'pretty_name': 'Status'}, {'name': 'unique_id', 'pretty_name': 'Unique ID'}, {'name': 'updated', 'pretty_name': 'Date Updated'}, {'name': 'updated_by', 'pretty_name': 'Updated By'}, ] return { 'au': auth_user, 'column_selectors': column_selectors, 'layout': site_layout('max'), 'nav_urls': nav_urls, 'nodes': nodes, 'offset': offset, 'page_title_name': page_title_name, 'page_title_type': page_title_type, 'perpage': perpage, 'total': total, }
{ "repo_name": "CityGrid/arsenal", "path": "server/arsenalweb/views/nodes.py", "copies": "1", "size": "4244", "license": "apache-2.0", "hash": -2636350571472831500, "line_mean": 33.2258064516, "line_max": 98, "alpha_frac": 0.6182846371, "autogenerated": false, "ratio": 3.5814345991561183, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.4699719236256118, "avg_score": null, "num_lines": null }
'''Arsenal operating_systems DB Model''' # Copyright 2015 CityGrid Media, LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # import logging from sqlalchemy.ext.hybrid import hybrid_method from sqlalchemy import ( Column, Integer, TIMESTAMP, Text, ) from arsenalweb.models.common import ( Base, BaseAudit, DBSession, get_name_id_dict, jsonify, ) LOG = logging.getLogger(__name__) class OperatingSystem(Base): '''Arsenal OperatingSystem object.''' __tablename__ = 'operating_systems' id = Column(Integer, primary_key=True, nullable=False) name = Column(Text, nullable=False) variant = Column(Text, nullable=False) version_number = Column(Text, nullable=False) architecture = Column(Text, nullable=False) description = Column(Text, nullable=False) created = Column(TIMESTAMP, nullable=False) updated = Column(TIMESTAMP, nullable=False) updated_by = Column(Text, nullable=False) @hybrid_method def get_operating_system_id(self, variant, version_number, architecture): '''Get operating_system id by name.''' query = DBSession.query(OperatingSystem) query = query.filter(OperatingSystem.variant == '%s' % variant) query = query.filter(OperatingSystem.version_number == '%s' % version_number) query = query.filter(OperatingSystem.architecture == '%s' % architecture) return query.one() def __json__(self, request): try: fields = request.params['fields'] if fields == 'all': # Everything. all_fields = dict( id=self.id, name=self.name, variant=self.variant, version_number=self.version_number, architecture=self.architecture, description=self.description, created=self.created, updated=self.updated, updated_by=self.updated_by, ) return jsonify(all_fields) else: # Always return id and name, then return whatever additional fields # are asked for. resp = get_name_id_dict([self]) my_fields = fields.split(',') resp.update((key, getattr(self, key)) for key in my_fields if key in self.__dict__) return jsonify(resp) # Default to returning only id and name. except KeyError: resp = get_name_id_dict([self]) return resp class OperatingSystemAudit(BaseAudit): '''Arsenal OperatingSystemAudit object.''' __tablename__ = 'operating_systems_audit'
{ "repo_name": "CityGrid/arsenal", "path": "server/arsenalweb/models/operating_systems.py", "copies": "1", "size": "3265", "license": "apache-2.0", "hash": -8483435560717833000, "line_mean": 31.65, "line_max": 85, "alpha_frac": 0.6125574273, "autogenerated": false, "ratio": 4.318783068783069, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.00035727790832725605, "num_lines": 100 }
'''Arsenal operating_systems UI.''' # Copyright 2015 CityGrid Media, LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # import logging from pyramid.view import view_config from arsenalweb.views import ( _api_get, get_authenticated_user, get_nav_urls, get_pag_params, site_layout, ) LOG = logging.getLogger(__name__) @view_config(route_name='operating_system', permission='view', renderer='arsenalweb:templates/operating_system.pt') def view_operating_system(request): '''Handle requests for opaerating_system UI route.''' page_title = 'Operating System' auth_user = get_authenticated_user(request) uri = '/api/operating_systems/{0}'.format(request.matchdict['id']) operating_system = _api_get(request, uri) return { 'au': auth_user, 'operating_system': operating_system['results'][0], 'page_title': page_title, } @view_config(route_name='operating_systems', permission='view', renderer='arsenalweb:templates/operating_systems.pt') def view_operating_systems(request): '''Handle requests for operating_systems UI route.''' page_title_type = 'object/' page_title_name = 'operating_systems' auth_user = get_authenticated_user(request) (perpage, offset) = get_pag_params(request) payload = {} for k in request.GET: payload[k] = request.GET[k] # Force the UI to 50 results per page if not perpage: perpage = 50 payload['perpage'] = perpage uri = '/api/operating_systems' LOG.info('UI requesting data from API={0},payload={1}'.format(uri, payload)) resp = _api_get(request, uri, payload) total = 0 operating_systems = [] if resp: total = resp['meta']['total'] operating_systems = resp['results'] nav_urls = get_nav_urls(request.path, offset, perpage, total, payload) # Used by the columns menu to determine what to show/hide. column_selectors = [ {'name': 'architecture', 'pretty_name': 'Architecture'}, {'name': 'created', 'pretty_name': 'Date Created'}, {'name': 'description', 'pretty_name': 'Description'}, {'name': 'operating_system_id', 'pretty_name': 'Operating system ID'}, {'name': 'updated', 'pretty_name': 'Date Updated'}, {'name': 'updated_by', 'pretty_name': 'Updated By'}, {'name': 'variant', 'pretty_name': 'Variant'}, {'name': 'version_number', 'pretty_name': 'Version Number'}, ] return { 'au': auth_user, 'column_selectors': column_selectors, 'layout': site_layout('max'), 'nav_urls': nav_urls, 'offset': offset, 'operating_systems': operating_systems, 'page_title_name': page_title_name, 'page_title_type': page_title_type, 'perpage': perpage, 'total': total, }
{ "repo_name": "CityGrid/arsenal", "path": "server/arsenalweb/views/operating_systems.py", "copies": "1", "size": "3344", "license": "apache-2.0", "hash": -1063064780656874900, "line_mean": 32.1089108911, "line_max": 117, "alpha_frac": 0.6447368421, "autogenerated": false, "ratio": 3.6466739367502727, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9789533772849783, "avg_score": 0.00037540120009793045, "num_lines": 101 }
'''Arsenal physical_devices DB Model''' # Copyright 2015 CityGrid Media, LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # import logging from sqlalchemy import ( Column, ForeignKey, Integer, TIMESTAMP, Text, ) from sqlalchemy.orm import relationship from sqlalchemy.orm import backref from arsenalweb.models.common import ( Base, BaseAudit, check_null_string, get_name_id_dict, get_name_id_list, jsonify, ) LOG = logging.getLogger(__name__) class PhysicalDevice(Base): '''Arsenal PhysicalDevice object.''' __tablename__ = 'physical_devices' id = Column(Integer, primary_key=True, nullable=False) serial_number = Column(Text, nullable=False) physical_location_id = Column(Integer, ForeignKey('physical_locations.id'), nullable=False) physical_location = relationship('PhysicalLocation', backref='physical_devices', lazy='joined') physical_rack_id = Column(Integer, ForeignKey('physical_racks.id'), nullable=False) physical_rack = relationship('PhysicalRack', backref='physical_devices', lazy='joined') physical_elevation_id = Column(Integer, ForeignKey('physical_elevations.id'), nullable=False) mac_address_1 = Column(Text, nullable=False) mac_address_2 = Column(Text, nullable=True) hardware_profile_id = Column(Integer, ForeignKey('hardware_profiles.id'), nullable=False) hardware_profile = relationship('HardwareProfile', backref=backref('physical_devices'), lazy='joined') oob_ip_address = Column(Text, nullable=True) oob_mac_address = Column(Text, nullable=True) tags = relationship('Tag', secondary='tag_physical_device_assignments', backref='physical_devices', lazy='joined') created = Column(TIMESTAMP, nullable=False) updated = Column(TIMESTAMP, nullable=False) updated_by = Column(Text, nullable=False) def __json__(self, request): try: if request.path_info.startswith('/api/physical_devices'): fields = request.params['fields'] if fields == 'all': all_fields = dict( id=self.id, hardware_profile=get_name_id_dict([self.hardware_profile], default_keys=['id', 'name']), physical_location=self.physical_location, physical_rack=self.physical_rack, physical_elevation=self.physical_elevation, mac_address_1=self.mac_address_1, mac_address_2=self.mac_address_2, node=get_name_id_dict(self.nodes), oob_ip_address=self.oob_ip_address, oob_mac_address=self.oob_mac_address, serial_number=check_null_string(self.serial_number), tags=get_name_id_list(self.tags, extra_keys=['value']), created=self.created, updated=self.updated, updated_by=self.updated_by, ) return jsonify(all_fields) else: # Always return these fields, then return whatever additional fields # are asked for. resp = get_name_id_dict([self], default_keys=['id', 'serial_number', ]) my_fields = fields.split(',') resp.update((key, getattr(self, key)) for key in my_fields if key in self.__dict__) if 'node' in my_fields: resp['node'] = get_name_id_dict(self.nodes) if 'tags' in my_fields: resp['tags'] = get_name_id_list(self.tags, extra_keys=['value']) return jsonify(resp) # Default to returning only these fields. except (KeyError, UnboundLocalError): resp = get_name_id_dict([self], default_keys=['id', 'serial_number', ]) return resp class PhysicalDeviceAudit(BaseAudit): '''Arsenal PhysicalDeviceAudit object.''' __tablename__ = 'physical_devices_audit'
{ "repo_name": "CityGrid/arsenal", "path": "server/arsenalweb/models/physical_devices.py", "copies": "1", "size": "5498", "license": "apache-2.0", "hash": 777380110910657200, "line_mean": 38.8405797101, "line_max": 84, "alpha_frac": 0.5143688614, "autogenerated": false, "ratio": 4.891459074733096, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.0007976354243937364, "num_lines": 138 }
'''Arsenal physical_devices UI''' # Copyright 2015 CityGrid Media, LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # import logging from pyramid.view import view_config from arsenalweb.views import ( _api_get, get_authenticated_user, get_nav_urls, get_pag_params, site_layout, ) LOG = logging.getLogger(__name__) @view_config(route_name='physical_device', permission='view', renderer='arsenalweb:templates/physical_device.pt') def view_physical_device(request): '''Handle requests for physical_device UI route.''' page_title_type = 'objects/' page_title_name = 'physical_device' auth_user = get_authenticated_user(request) uri = '/api/physical_devices/{0}'.format(request.matchdict['id']) physical_device = _api_get(request, uri) return { 'au': auth_user, 'physical_device': physical_device['results'][0], 'page_title_name': page_title_name, 'page_title_type': page_title_type, } @view_config(route_name='physical_devices', permission='view', renderer='arsenalweb:templates/physical_devices.pt') def view_physical_devices(request): '''Handle requests for physical_devices UI route.''' page_title_type = 'objects/' page_title_name = 'physical_devices' auth_user = get_authenticated_user(request) (perpage, offset) = get_pag_params(request) payload = {} for k in request.GET: payload[k] = request.GET[k] # Force the UI to 50 results per page if not perpage: perpage = 50 payload['perpage'] = perpage uri = '/api/physical_devices' LOG.info('UI requesting data from API={0},payload={1}'.format(uri, payload)) resp = _api_get(request, uri, payload) total = 0 physical_devices = [] if resp: total = resp['meta']['total'] physical_devices = resp['results'] nav_urls = get_nav_urls(request.path, offset, perpage, total, payload) # Used by the columns menu to determine what to show/hide. column_selectors = [ {'name': 'hardware_profile', 'pretty_name': 'Hardware Profile'}, {'name': 'created', 'pretty_name': 'Date Created'}, {'name': 'mac_address_1', 'pretty_name': 'Mac Address 1'}, {'name': 'mac_address_2', 'pretty_name': 'Mac Address 2'}, {'name': 'oob_ip_address', 'pretty_name': 'OOB IP Address'}, {'name': 'oob_mac_address', 'pretty_name': 'OOB Mac Address'}, {'name': 'physical_location', 'pretty_name': 'Physical Location'}, {'name': 'physical_elevation', 'pretty_name': 'Physical Elevation'}, {'name': 'physical_rack', 'pretty_name': 'Physical Rack'}, {'name': 'updated', 'pretty_name': 'Date Updated'}, {'name': 'updated_by', 'pretty_name': 'Updated By'}, ] return { 'au': auth_user, 'column_selectors': column_selectors, 'layout': site_layout('max'), 'nav_urls': nav_urls, 'physical_devices': physical_devices, 'offset': offset, 'page_title_name': page_title_name, 'page_title_type': page_title_type, 'perpage': perpage, 'total': total, }
{ "repo_name": "CityGrid/arsenal", "path": "server/arsenalweb/views/physical_devices.py", "copies": "1", "size": "3650", "license": "apache-2.0", "hash": -768403790375163600, "line_mean": 33.4339622642, "line_max": 115, "alpha_frac": 0.6383561644, "autogenerated": false, "ratio": 3.621031746031746, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.4759387910431746, "avg_score": null, "num_lines": null }
'''Arsenal physical_elevations DB Model''' # Copyright 2015 CityGrid Media, LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # import logging from sqlalchemy import ( Column, ForeignKey, Integer, TIMESTAMP, Text, ) from sqlalchemy.orm import relationship from sqlalchemy.orm import backref from arsenalweb.models.common import ( Base, BaseAudit, get_name_id_dict, jsonify, ) LOG = logging.getLogger(__name__) class PhysicalElevation(Base): '''Arsenal PhysicalElevation object.''' __tablename__ = 'physical_elevations' id = Column(Integer, primary_key=True, nullable=False) elevation = Column(Text, nullable=False) physical_rack_id = Column(Integer, ForeignKey('physical_racks.id'), nullable=False) created = Column(TIMESTAMP, nullable=False) updated = Column(TIMESTAMP, nullable=False) updated_by = Column(Text, nullable=False) physical_rack = relationship('PhysicalRack', backref='physical_elevations', lazy='joined') physical_device = relationship('PhysicalDevice', primaryjoin='PhysicalElevation.id==PhysicalDevice.physical_elevation_id', backref='physical_elevation') def __json__(self, request): try: if request.path_info.startswith('/api/physical_elevations'): fields = request.params['fields'] if fields == 'all': # Everything. all_fields = dict( id=self.id, elevation=self.elevation, physical_device=get_name_id_dict(self.physical_device, default_keys=['id', 'serial_number', 'hardware_profile']), physical_rack=get_name_id_dict([self.physical_rack], default_keys=['id', 'name', 'physical_location']), created=self.created, updated=self.updated, updated_by=self.updated_by, ) return jsonify(all_fields) else: # Always return id and name, then return whatever additional fields # are asked for. resp = get_name_id_dict([self]) my_fields = fields.split(',') resp.update((key, getattr(self, key)) for key in my_fields if key in self.__dict__) return jsonify(resp) # Default to returning only these fields. except (KeyError, UnboundLocalError): resp = get_name_id_dict([self], default_keys=['id', 'elevation',]) resp['physical_device'] = get_name_id_dict(self.physical_device, default_keys=['id', 'serial_number', 'hardware_profile']) return resp class PhysicalElevationAudit(BaseAudit): '''Arsenal PhysicalElevationAudit object.''' __tablename__ = 'physical_elevations_audit'
{ "repo_name": "CityGrid/arsenal", "path": "server/arsenalweb/models/physical_elevations.py", "copies": "1", "size": "4031", "license": "apache-2.0", "hash": -6767618862225960000, "line_mean": 37.3904761905, "line_max": 108, "alpha_frac": 0.5239394691, "autogenerated": false, "ratio": 4.976543209876543, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.001481692325719655, "num_lines": 105 }
'''Arsenal physical_elevations UI''' # Copyright 2015 CityGrid Media, LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # import logging from pyramid.view import view_config from arsenalweb.views import ( _api_get, get_authenticated_user, get_nav_urls, get_pag_params, site_layout, ) LOG = logging.getLogger(__name__) @view_config(route_name='physical_elevation', permission='view', renderer='arsenalweb:templates/physical_elevation.pt') def view_physical_elevation(request): '''Handle requests for physical_elevation UI route.''' page_title_type = 'objects/' page_title_name = 'physical_elevation' auth_user = get_authenticated_user(request) uri = '/api/physical_elevations/{0}'.format(request.matchdict['id']) physical_elevation = _api_get(request, uri) return { 'au': auth_user, 'physical_elevation': physical_elevation['results'][0], 'page_title_name': page_title_name, 'page_title_type': page_title_type, } @view_config(route_name='physical_elevations', permission='view', renderer='arsenalweb:templates/physical_elevations.pt') def view_physical_elevations(request): '''Handle requests for physical_elevations UI route.''' page_title_type = 'objects/' page_title_name = 'physical_elevations' auth_user = get_authenticated_user(request) (perpage, offset) = get_pag_params(request) payload = {} for k in request.GET: payload[k] = request.GET[k] # Force the UI to 50 results per page if not perpage: perpage = 50 payload['perpage'] = perpage uri = '/api/physical_elevations' LOG.info('UI requesting data from API={0},payload={1}'.format(uri, payload)) resp = _api_get(request, uri, payload) total = 0 physical_elevations = [] if resp: total = resp['meta']['total'] physical_elevations = resp['results'] nav_urls = get_nav_urls(request.path, offset, perpage, total, payload) # Used by the columns menu to determine what to show/hide. column_selectors = [ {'name': 'created', 'pretty_name': 'Date Created'}, {'name': 'elevation', 'pretty_name': 'Physical Elevation'}, {'name': 'physical_location', 'pretty_name': 'Physical Location'}, {'name': 'physical_rack', 'pretty_name': 'Physical Rack'}, {'name': 'updated', 'pretty_name': 'Date Updated'}, {'name': 'updated_by', 'pretty_name': 'Updated By'}, ] return { 'au': auth_user, 'column_selectors': column_selectors, 'layout': site_layout('max'), 'nav_urls': nav_urls, 'physical_elevations': physical_elevations, 'offset': offset, 'page_title_name': page_title_name, 'page_title_type': page_title_type, 'perpage': perpage, 'total': total, }
{ "repo_name": "CityGrid/arsenal", "path": "server/arsenalweb/views/physical_elevations.py", "copies": "1", "size": "3354", "license": "apache-2.0", "hash": 2836784564725957000, "line_mean": 32.2079207921, "line_max": 121, "alpha_frac": 0.6523553965, "autogenerated": false, "ratio": 3.6695842450765865, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9820104371528635, "avg_score": 0.0003670540095903944, "num_lines": 101 }
'''Arsenal physical_locations DB Model''' # Copyright 2015 CityGrid Media, LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # import logging from sqlalchemy import ( Column, ForeignKey, Integer, TIMESTAMP, Text, ) from sqlalchemy.orm import relationship from sqlalchemy.orm import backref from arsenalweb.models.common import ( Base, BaseAudit, get_name_id_dict, get_name_id_list, jsonify, ) LOG = logging.getLogger(__name__) class PhysicalLocation(Base): '''Arsenal PhysicalLocation object.''' __tablename__ = 'physical_locations' id = Column(Integer, primary_key=True, nullable=False) name = Column(Text, nullable=False) provider = Column(Text, nullable=True) address_1 = Column(Text, nullable=True) address_2 = Column(Text, nullable=True) city = Column(Text, nullable=True) admin_area = Column(Text, nullable=True) country = Column(Text, nullable=True) postal_code = Column(Text, nullable=True) contact_name = Column(Text, nullable=True) phone_number = Column(Text, nullable=True) created = Column(TIMESTAMP, nullable=False) updated = Column(TIMESTAMP, nullable=False) updated_by = Column(Text, nullable=False) def __json__(self, request): try: if request.path_info.startswith('/api/physical_locations'): fields = request.params['fields'] if fields == 'all': # Everything. all_fields = dict( id=self.id, name=self.name, provider=self.provider, address_1=self.address_1, address_2=self.address_2, city=self.city, admin_area=self.admin_area, country=self.country, postal_code=self.postal_code, contact_name=self.contact_name, phone_number=self.phone_number, physical_racks=get_name_id_list(self.physical_racks, default_keys=['id', 'name', 'physical_elevations']), created=self.created, updated=self.updated, updated_by=self.updated_by, ) return jsonify(all_fields) else: # Always return id and name, then return whatever additional fields # are asked for. resp = get_name_id_dict([self]) my_fields = fields.split(',') resp.update((key, getattr(self, key)) for key in my_fields if key in self.__dict__) return jsonify(resp) # Default to returning only name and id. except (KeyError, UnboundLocalError): resp = get_name_id_dict([self]) return resp class PhysicalLocationAudit(BaseAudit): '''Arsenal PhysicalLocationAudit object.''' __tablename__ = 'physical_locations_audit'
{ "repo_name": "CityGrid/arsenal", "path": "server/arsenalweb/models/physical_locations.py", "copies": "1", "size": "3693", "license": "apache-2.0", "hash": 1827730498998594800, "line_mean": 33.1944444444, "line_max": 90, "alpha_frac": 0.5705388573, "autogenerated": false, "ratio": 4.417464114832536, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5488002972132536, "avg_score": null, "num_lines": null }
'''Arsenal physical_locations UI''' # Copyright 2015 CityGrid Media, LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # import logging from pyramid.view import view_config from arsenalweb.views import ( _api_get, get_authenticated_user, get_nav_urls, get_pag_params, site_layout, ) LOG = logging.getLogger(__name__) @view_config(route_name='physical_location', permission='view', renderer='arsenalweb:templates/physical_location.pt') def view_physical_location(request): '''Handle requests for physical_location UI route.''' page_title_type = 'objects/' page_title_name = 'physical_location' auth_user = get_authenticated_user(request) uri = '/api/physical_locations/{0}'.format(request.matchdict['id']) physical_location = _api_get(request, uri) return { 'au': auth_user, 'physical_location': physical_location['results'][0], 'page_title_name': page_title_name, 'page_title_type': page_title_type, } @view_config(route_name='physical_locations', permission='view', renderer='arsenalweb:templates/physical_locations.pt') def view_physical_locations(request): '''Handle requests for physical_locations UI route.''' page_title_type = 'objects/' page_title_name = 'physical_locations' auth_user = get_authenticated_user(request) (perpage, offset) = get_pag_params(request) payload = {} for k in request.GET: payload[k] = request.GET[k] # Force the UI to 50 results per page if not perpage: perpage = 50 payload['perpage'] = perpage uri = '/api/physical_locations' LOG.info('UI requesting data from API={0},payload={1}'.format(uri, payload)) resp = _api_get(request, uri, payload) total = 0 physical_locations = [] if resp: total = resp['meta']['total'] physical_locations = resp['results'] nav_urls = get_nav_urls(request.path, offset, perpage, total, payload) # Used by the columns menu to determine what to show/hide. column_selectors = [ {'name': 'contact_name', 'pretty_name': 'DC Contact'}, {'name': 'created', 'pretty_name': 'Date Created'}, {'name': 'name', 'pretty_name': 'Name'}, {'name': 'phone_number', 'pretty_name': 'DC Phone Number'}, {'name': 'provider', 'pretty_name': 'DC Provider'}, {'name': 'address_1', 'pretty_name': 'Address 1'}, {'name': 'address_2', 'pretty_name': 'Address 2'}, {'name': 'city', 'pretty_name': 'City'}, {'name': 'admin_area', 'pretty_name': 'State'}, {'name': 'postal_code', 'pretty_name': 'Postal Code'}, {'name': 'country', 'pretty_name': 'Country'}, {'name': 'updated', 'pretty_name': 'Date Updated'}, {'name': 'updated_by', 'pretty_name': 'Updated By'}, ] return { 'au': auth_user, 'column_selectors': column_selectors, 'layout': site_layout('max'), 'nav_urls': nav_urls, 'physical_locations': physical_locations, 'offset': offset, 'page_title_name': page_title_name, 'page_title_type': page_title_type, 'perpage': perpage, 'total': total, }
{ "repo_name": "CityGrid/arsenal", "path": "server/arsenalweb/views/physical_locations.py", "copies": "1", "size": "3705", "license": "apache-2.0", "hash": 663326864963324200, "line_mean": 33.3055555556, "line_max": 119, "alpha_frac": 0.6321187584, "autogenerated": false, "ratio": 3.6394891944990175, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9769872447253175, "avg_score": 0.00034710112916850727, "num_lines": 108 }
'''Arsenal physical_racks DB Model''' # Copyright 2015 CityGrid Media, LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # import logging from sqlalchemy import ( Column, ForeignKey, Integer, TIMESTAMP, Text, ) from sqlalchemy.orm import relationship from sqlalchemy.orm import backref from arsenalweb.models.common import ( Base, BaseAudit, get_name_id_dict, get_name_id_list, jsonify, ) LOG = logging.getLogger(__name__) class PhysicalRack(Base): '''Arsenal PhysicalRack object.''' __tablename__ = 'physical_racks' id = Column(Integer, primary_key=True, nullable=False) name = Column(Text, nullable=False) physical_location_id = Column(Integer, ForeignKey('physical_locations.id'), nullable=False) created = Column(TIMESTAMP, nullable=False) updated = Column(TIMESTAMP, nullable=False) updated_by = Column(Text, nullable=False) physical_location = relationship('PhysicalLocation', backref='physical_racks', lazy='joined') def __json__(self, request): try: if request.path_info.startswith('/api/physical_racks'): fields = request.params['fields'] if fields == 'all': # Everything. all_fields = dict( id=self.id, name=self.name, physical_location=get_name_id_dict([self.physical_location]), physical_elevations=self.physical_elevations, created=self.created, updated=self.updated, updated_by=self.updated_by, ) return jsonify(all_fields) else: # Always return id and name, then return whatever additional fields # are asked for. resp = get_name_id_dict([self]) my_fields = fields.split(',') resp.update((key, getattr(self, key)) for key in my_fields if key in self.__dict__) return jsonify(resp) # Default to returning only name and id. except (KeyError, UnboundLocalError): resp = get_name_id_dict([self]) return resp class PhysicalRackAudit(BaseAudit): '''Arsenal PhysicalRackAudit object.''' __tablename__ = 'physical_racks_audit'
{ "repo_name": "CityGrid/arsenal", "path": "server/arsenalweb/models/physical_racks.py", "copies": "1", "size": "2881", "license": "apache-2.0", "hash": -7654623814995391000, "line_mean": 30.6593406593, "line_max": 97, "alpha_frac": 0.6147171121, "autogenerated": false, "ratio": 4.230543318649046, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5345260430749046, "avg_score": null, "num_lines": null }
'''Arsenal physical_racks UI''' # Copyright 2015 CityGrid Media, LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # import logging from pyramid.view import view_config from arsenalweb.views import ( _api_get, get_authenticated_user, get_nav_urls, get_pag_params, site_layout, ) LOG = logging.getLogger(__name__) @view_config(route_name='physical_rack', permission='view', renderer='arsenalweb:templates/physical_rack.pt') def view_physical_rack(request): '''Handle requests for physical_rack UI route.''' page_title_type = 'objects/' page_title_name = 'physical_rack' auth_user = get_authenticated_user(request) uri = '/api/physical_racks/{0}'.format(request.matchdict['id']) physical_rack = _api_get(request, uri) return { 'au': auth_user, 'physical_rack': physical_rack['results'][0], 'page_title_name': page_title_name, 'page_title_type': page_title_type, } @view_config(route_name='physical_racks', permission='view', renderer='arsenalweb:templates/physical_racks.pt') def view_physical_racks(request): '''Handle requests for physical_racks UI route.''' page_title_type = 'objects/' page_title_name = 'physical_racks' auth_user = get_authenticated_user(request) (perpage, offset) = get_pag_params(request) payload = {} for k in request.GET: payload[k] = request.GET[k] # Force the UI to 50 results per page if not perpage: perpage = 50 payload['perpage'] = perpage uri = '/api/physical_racks' LOG.info('UI requesting data from API={0},payload={1}'.format(uri, payload)) resp = _api_get(request, uri, payload) total = 0 physical_racks = [] if resp: total = resp['meta']['total'] physical_racks = resp['results'] nav_urls = get_nav_urls(request.path, offset, perpage, total, payload) # Used by the columns menu to determine what to show/hide. column_selectors = [ {'name': 'created', 'pretty_name': 'Date Created'}, {'name': 'name', 'pretty_name': 'Physical Rack Name'}, {'name': 'physical_location', 'pretty_name': 'Physical Location'}, {'name': 'updated', 'pretty_name': 'Date Updated'}, {'name': 'updated_by', 'pretty_name': 'Updated By'}, ] return { 'au': auth_user, 'column_selectors': column_selectors, 'layout': site_layout('max'), 'nav_urls': nav_urls, 'physical_racks': physical_racks, 'offset': offset, 'page_title_name': page_title_name, 'page_title_type': page_title_type, 'perpage': perpage, 'total': total, }
{ "repo_name": "CityGrid/arsenal", "path": "server/arsenalweb/views/physical_racks.py", "copies": "1", "size": "3182", "license": "apache-2.0", "hash": 3873988493663222000, "line_mean": 30.82, "line_max": 111, "alpha_frac": 0.6423632935, "autogenerated": false, "ratio": 3.5553072625698325, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.46976705560698323, "avg_score": null, "num_lines": null }
'''Arsenal Pyramid WSGI application.''' # Copyright 2015 CityGrid Media, LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # import logging import ConfigParser import os import time from pyramid.config import Configurator from pyramid.authentication import AuthTktAuthenticationPolicy from pyramid.authorization import ACLAuthorizationPolicy from pyramid.security import Allow, Authenticated from pyramid.renderers import JSON from pyramid_xml_renderer import XML from sqlalchemy import engine_from_config from sqlalchemy import event from sqlalchemy.exc import DisconnectionError import ldap from .views import global_groupfinder from .models.common import ( DBSession, Base, Group, ) class RootFactory(object): '''Top level ACL class.''' # Additional ACLs loaded from the DB below __acl__ = [ (Allow, Authenticated, ('view', 'tag_write', 'tag_delete')) ] def __init__(self, request): pass def get_settings(global_config, settings): '''Read in settings from config files.''' # Secrets mcp = ConfigParser.ConfigParser() mcp.read(settings['arsenal.secrets_file']) for key, val in mcp.items("app:main"): settings[key] = val scp = ConfigParser.SafeConfigParser() scp.read(global_config) for key, val in scp.items("app:safe"): settings[key] = val return settings def checkout_listener(dbapi_con, con_record, con_proxy): '''Test the listener.''' try: try: dbapi_con.ping(False) except TypeError: dbapi_con.ping() except Exception, ex: import sys print >> sys.stderr, "Error: %s (%s)" % (Exception, ex) raise DisconnectionError() def main(global_config, **settings): '''This function returns a Pyramid WSGI application.''' settings = get_settings(global_config['__file__'], settings) # Have to do this becasue it can be a boolean or a string. if settings['arsenal.verify_ssl'] == 'True': settings['arsenal.verify_ssl'] = bool(settings['arsenal.verify_ssl']) if settings['arsenal.verify_ssl'] == 'False': settings['arsenal.verify_ssl'] = bool('') log = logging.getLogger(__name__) engine = engine_from_config(settings, 'sqlalchemy.') event.listen(engine, 'checkout', checkout_listener) DBSession.configure(bind=engine) Base.metadata.bind = engine # # Routes # config = Configurator(settings=settings, root_factory=RootFactory) config.include('pyramid_chameleon') config.include('pyramid_ldap') config.add_static_view('static', 'static', cache_max_age=3600) config.add_route('home', '/') config.add_route('user', '/user') config.add_route('login', '/login') config.add_route('logout', '/logout') config.add_route('signup', '/signup') config.add_route('help', '/help') config.add_route('search', '/search') config.add_route('data_centers', '/data_centers') config.add_route('data_center', '/data_centers/{id}') config.add_route('data_centers_audit', '/data_centers_audit') config.add_route('data_center_audit', '/data_centers_audit/{id}') config.add_route('ip_addresses', '/ip_addresses') config.add_route('ip_address', '/ip_addresses/{id}') config.add_route('ip_addresses_audit', '/ip_addresses_audit') config.add_route('ip_address_audit', '/ip_addresses_audit/{id}') config.add_route('network_interfaces', '/network_interfaces') config.add_route('network_interface', '/network_interfaces/{id}') config.add_route('network_interfaces_audit', '/network_interfaces_audit') config.add_route('network_interface_audit', '/network_interfaces_audit/{id}') config.add_route('nodes', '/nodes') config.add_route('node', '/nodes/{id}') config.add_route('nodes_audit', '/nodes_audit') config.add_route('node_audit', '/nodes_audit/{id}') config.add_route('node_groups', '/node_groups') config.add_route('node_group', '/node_groups/{id}') config.add_route('node_groups_audit', '/node_groups_audit') config.add_route('node_group_audit', '/node_groups_audit/{id}') config.add_route('physical_locations', '/physical_locations') config.add_route('physical_location', '/physical_locations/{id}') config.add_route('physical_locations_audit', '/physical_locations_audit') config.add_route('physical_location_audit', '/physical_locations_audit/{id}') config.add_route('physical_devices', '/physical_devices') config.add_route('physical_device', '/physical_devices/{id}') config.add_route('physical_devices_audit', '/physical_devices_audit') config.add_route('physical_device_audit', '/physical_devices_audit/{id}') config.add_route('physical_elevations', '/physical_elevations') config.add_route('physical_elevation', '/physical_elevations/{id}') config.add_route('physical_elevations_audit', '/physical_elevations_audit') config.add_route('physical_elevation_audit', '/physical_elevations_audit/{id}') config.add_route('physical_racks', '/physical_racks') config.add_route('physical_rack', '/physical_racks/{id}') config.add_route('physical_racks_audit', '/physical_racks_audit') config.add_route('physical_rack_audit', '/physical_racks_audit/{id}') config.add_route('statuses', '/statuses') config.add_route('status', '/statuses/{id}') config.add_route('statuses_audit', '/statuses_audit') config.add_route('status_audit', '/statuses_audit/{id}') config.add_route('tags', '/tags') config.add_route('tag', '/tags/{id}') config.add_route('tags_audit', '/tags_audit') config.add_route('tag_audit', '/tags_audit/{id}') config.add_route('hardware_profiles', '/hardware_profiles') config.add_route('hardware_profile', '/hardware_profiles/{id}') config.add_route('hardware_profiles_audit', '/hardware_profiles_audit') config.add_route('hardware_profile_audit', '/hardware_profiles_audit/{id}') config.add_route('operating_systems', '/operating_systems') config.add_route('operating_system', '/operating_systems/{id}') config.add_route('operating_systems_audit', '/operating_systems_audit') config.add_route('operating_system_audit', '/operating_systems_audit/{id}') # # API Endpoints. Order matters. # # api_register is a special endpoint in order to use pyramid # secirty to control access to node registrations. Don't love it # but can't use request_param on a put request. config.add_route('api_register', '/api/register') config.add_route('api_enc', '/api/enc') config.add_route('api_data_centers', '/api/data_centers') config.add_route('api_data_center_r', '/api/data_centers/{id}/{resource}') config.add_route('api_data_center', '/api/data_centers/{id}') config.add_route('api_data_centers_audit', '/api/data_centers_audit') config.add_route('api_data_center_audit_r', '/api/data_centers_audit/{id}/{resource}') config.add_route('api_data_center_audit', '/api/data_centers_audit/{id}') config.add_route('api_nodes', '/api/nodes') config.add_route('api_node_r', '/api/nodes/{id}/{resource}') config.add_route('api_node', '/api/nodes/{id}') config.add_route('api_nodes_audit', '/api/nodes_audit') config.add_route('api_node_audit_r', '/api/nodes_audit/{id}/{resource}') config.add_route('api_node_audit', '/api/nodes_audit/{id}') config.add_route('api_statuses', '/api/statuses') config.add_route('api_status_r', '/api/statuses/{id}/{resource}') config.add_route('api_status', '/api/statuses/{id}') config.add_route('api_statuses_audit', '/api/statuses_audit') config.add_route('api_status_audit_r', '/api/statuses_audit/{id}/{resource}') config.add_route('api_status_audit', '/api/statuses_audit/{id}') config.add_route('api_tags', '/api/tags') config.add_route('api_tag_r', '/api/tags/{id}/{resource}') config.add_route('api_tag', '/api/tags/{id}') config.add_route('api_tags_audit', '/api/tags_audit') config.add_route('api_tag_audit_r', '/api/tags_audit/{id}/{resource}') config.add_route('api_tag_audit', '/api/tags_audit/{id}') config.add_route('api_hardware_profiles', '/api/hardware_profiles') config.add_route('api_hardware_profile_r', '/api/hardware_profiles/{id}/{resource}') config.add_route('api_hardware_profile', '/api/hardware_profiles/{id}') config.add_route('api_hardware_profiles_audit', '/api/hardware_profiles_audit') config.add_route('api_hardware_profile_audit_r', '/api/hardware_profiles_audit/{id}/{resource}') config.add_route('api_hardware_profile_audit', '/api/hardware_profiles_audit/{id}') config.add_route('api_ip_addresses', '/api/ip_addresses') config.add_route('api_ip_address_r', '/api/ip_addresses/{id}/{resource}') config.add_route('api_ip_address', '/api/ip_addresses/{id}') config.add_route('api_ip_addresses_audit', '/api/ip_addresses_audit') config.add_route('api_ip_address_audit_r', '/api/ip_addresses_audit/{id}/{resource}') config.add_route('api_ip_address_audit', '/api/ip_addresses_audit/{id}') config.add_route('api_operating_systems', '/api/operating_systems') config.add_route('api_operating_system_r', '/api/operating_systems/{id}/{resource}') config.add_route('api_operating_system', '/api/operating_systems/{id}') config.add_route('api_operating_systems_audit', '/api/operating_systems_audit') config.add_route('api_operating_system_audit_r', '/api/operating_systems_audit/{id}/{resource}') config.add_route('api_operating_system_audit', '/api/operating_systems_audit/{id}') config.add_route('api_physical_devices', '/api/physical_devices') config.add_route('api_physical_device_r', '/api/physical_devices/{id}/{resource}') config.add_route('api_physical_device', '/api/physical_devices/{id}') config.add_route('api_physical_devices_audit', '/api/physical_devices_audit') config.add_route('api_physical_device_audit_r', '/api/physical_devices_audit/{id}/{resource}') config.add_route('api_physical_device_audit', '/api/physical_devices_audit/{id}') config.add_route('api_physical_elevations', '/api/physical_elevations') config.add_route('api_physical_elevation_r', '/api/physical_elevations/{id}/{resource}') config.add_route('api_physical_elevation', '/api/physical_elevations/{id}') config.add_route('api_physical_elevations_audit', '/api/physical_elevations_audit') config.add_route('api_physical_elevation_audit_r', '/api/physical_elevations_audit/{id}/{resource}') config.add_route('api_physical_elevation_audit', '/api/physical_elevations_audit/{id}') config.add_route('api_physical_locations', '/api/physical_locations') config.add_route('api_physical_location_r', '/api/physical_locations/{id}/{resource}') config.add_route('api_physical_location', '/api/physical_locations/{id}') config.add_route('api_physical_locations_audit', '/api/physical_locations_audit') config.add_route('api_physical_location_audit_r', '/api/physical_locations_audit/{id}/{resource}') config.add_route('api_physical_location_audit', '/api/physical_locations_audit/{id}') config.add_route('api_physical_racks', '/api/physical_racks') config.add_route('api_physical_rack_r', '/api/physical_racks/{id}/{resource}') config.add_route('api_physical_rack', '/api/physical_racks/{id}') config.add_route('api_physical_racks_audit', '/api/physical_racks_audit') config.add_route('api_physical_rack_audit_r', '/api/physical_racks_audit/{id}/{resource}') config.add_route('api_physical_rack_audit', '/api/physical_racks_audit/{id}') config.add_route('api_node_groups', '/api/node_groups') config.add_route('api_node_group_r', '/api/node_groups/{id}/{resource}') config.add_route('api_node_group', '/api/node_groups/{id}') config.add_route('api_b_node_groups_deassign', '/api/bulk/node_groups/deassign') config.add_route('api_node_groups_audit', '/api/node_groups_audit') config.add_route('api_node_group_audit_r', '/api/node_groups_audit/{id}/{resource}') config.add_route('api_node_group_audit', '/api/node_groups_audit/{id}') config.add_route('api_hypervisor_vm_assignments', '/api/hypervisor_vm_assignments') config.add_route('api_hypervisor_vm_assignment_r', '/api/hypervisor_vm_assignments/{id}/{resource}') config.add_route('api_hypervisor_vm_assignment', '/api/hypervisor_vm_assignments/{id}') config.add_route('api_ec2_instances', '/api/ec2_instances') config.add_route('api_ec2_instance_r', '/api/ec2_instances/{id}/{resource}') config.add_route('api_ec2_instance', '/api/ec2_instances/{id}') config.add_route('api_ec2_instances_audit', '/api/ec2_instances_audit') config.add_route('api_ec2_instance_audit_r', '/api/ec2_instances_audit/{id}/{resource}') config.add_route('api_ec2_instance_audit', '/api/ec2_instances_audit/{id}') config.add_route('api_network_interfaces', '/api/network_interfaces') config.add_route('api_network_interface_r', '/api/network_interfaces/{id}/{resource}') config.add_route('api_network_interface', '/api/network_interfaces/{id}') config.add_route('api_network_interfaces_audit', '/api/network_interfaces_audit') config.add_route('api_network_interface_audit_r', '/api/network_interfaces_audit/{id}/{resource}') config.add_route('api_network_interface_audit', '/api/network_interfaces_audit/{id}') config.add_route('api_reports_db', '/api/reports/db') config.add_route('api_reports_nodes', '/api/reports/nodes') config.add_route('api_reports_stale_nodes', '/api/reports/stale_nodes') config.add_route('api_testing', '/api/testing') config.add_renderer('json', JSON(indent=2, sort_keys=True)) config.add_renderer('xml', XML()) if settings['arsenal.use_ldap']: log.info('Configuring ldap users and groups') # Load the cert if it's defined and exists if os.path.isfile(settings['arsenal.ldap_cert']): ldap.set_option(ldap.OPT_X_TLS_CACERTFILE, settings['arsenal.ldap_cert']) config.ldap_setup( settings['arsenal.ldap_server'] + ':' + settings['arsenal.ldap_port'], bind=settings['arsenal.ldap_bind'], passwd=settings['arsenal.ldap_password'], ) config.ldap_set_login_query( base_dn=settings['arsenal.login_base_dn'], filter_tmpl=settings['arsenal.login_filter'], scope=ldap.SCOPE_SUBTREE, cache_period=600, ) config.ldap_set_groups_query( base_dn=settings['arsenal.group_base_dn'], filter_tmpl=settings['arsenal.group_filter'], scope=ldap.SCOPE_SUBTREE, cache_period=600, ) config.set_authentication_policy( AuthTktAuthenticationPolicy(settings['arsenal.cookie_token'], callback=global_groupfinder, max_age=604800, hashalg='sha512') ) config.set_authorization_policy( ACLAuthorizationPolicy() ) # Load our groups and perms from the db and load them into the ACL max_retries = 10 for retry in range(1, max_retries): try: resp = DBSession.query(Group).all() for group in resp: gr_ass = group.get_all_assignments() if gr_ass: gr_ass = tuple(gr_ass) log.info('Adding group: {0} perm: {1}'.format(group.group_name, gr_ass)) RootFactory.__acl__.append([Allow, group.group_name, gr_ass]) except Exception as ex: log.warn('Unable to load ACLs from database({0} of {1})! Exception: ' '{2}'.format(retry, max_retries, repr(ex))) sleep_secs = 5 log.warn('Sleeping {0} seconds before retrying'.format(sleep_secs)) time.sleep(sleep_secs) else: break else: log.warn('Unable to load ACLs from database after {0} retries! ' 'Continuing in an ACL-less universe.'.format(max_retries)) config.scan() return config.make_wsgi_app()
{ "repo_name": "CityGrid/arsenal", "path": "server/arsenalweb/__init__.py", "copies": "1", "size": "16883", "license": "apache-2.0", "hash": 1700943995596844800, "line_mean": 47.5143678161, "line_max": 104, "alpha_frac": 0.6612568856, "autogenerated": false, "ratio": 3.511439267886855, "config_test": true, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.4672696153486855, "avg_score": null, "num_lines": null }
'''Arsenal search UI.''' # Copyright 2015 CityGrid Media, LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # import logging from pyramid.view import view_config from pyramid.httpexceptions import HTTPFound LOG = logging.getLogger(__name__) @view_config(route_name='search', permission='view', renderer='arsenalweb:templates/search.pt') def view_home(request): '''Handle requests for search UI route.''' for key, value in request.POST.iteritems(): LOG.debug('Searching for {0}: {1}'.format(key, value)) url_base = '/{0}?'.format(request.POST.get('object_type')) search_params = request.POST.get('search_terms') url_suffix = '' for term in search_params.split(): if '=' not in term: key = 'name' val = term else: key, val = term.split('=') url_suffix += '{0}={1}&'.format(key, val) url_suffix = url_suffix[:-1] return_url = '{0}{1}'.format(url_base, url_suffix) LOG.debug('Search url is: {0}'.format(return_url)) return HTTPFound(return_url)
{ "repo_name": "CityGrid/arsenal", "path": "server/arsenalweb/views/search.py", "copies": "1", "size": "1567", "license": "apache-2.0", "hash": -9207760966493578000, "line_mean": 33.0652173913, "line_max": 95, "alpha_frac": 0.6675175495, "autogenerated": false, "ratio": 3.6357308584686776, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9800983915215055, "avg_score": 0.00045289855072463763, "num_lines": 46 }
'''Arsenal statuses DB Model''' # Copyright 2015 CityGrid Media, LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # import logging from sqlalchemy.ext.hybrid import hybrid_method from sqlalchemy import ( Column, Integer, TIMESTAMP, Text, ) from arsenalweb.models.common import ( Base, BaseAudit, DBSession, get_name_id_dict, jsonify, ) LOG = logging.getLogger(__name__) class Status(Base): '''Arsenal Status object.''' __tablename__ = 'statuses' id = Column(Integer, primary_key=True, nullable=False) name = Column(Text, nullable=False) description = Column(Text, nullable=False) created = Column(TIMESTAMP, nullable=False) updated = Column(TIMESTAMP, nullable=False) updated_by = Column(Text, nullable=False) @hybrid_method def get_status_id(self, name): '''Find a status id by name.''' query = DBSession.query(Status) query = query.filter(Status.name == name) try: status = query.one() return status.id except: return None def __json__(self, request): try: fields = request.params['fields'] if fields == 'all': # Everything. all_fields = dict( id=self.id, name=self.name, description=self.description, created=self.created, updated=self.updated, updated_by=self.updated_by, ) return jsonify(all_fields) else: # Always return name and id, then return whatever additional fields # are asked for. resp = get_name_id_dict([self]) my_fields = fields.split(',') resp.update((key, getattr(self, key)) for key in my_fields if key in self.__dict__) return jsonify(resp) # Default to returning only name and id. except KeyError: resp = get_name_id_dict([self]) return resp class StatusAudit(BaseAudit): '''Arsenal StatusAudit object.''' __tablename__ = 'statuses_audit'
{ "repo_name": "CityGrid/arsenal", "path": "server/arsenalweb/models/statuses.py", "copies": "1", "size": "2750", "license": "apache-2.0", "hash": -1044336049757326600, "line_mean": 27.6458333333, "line_max": 83, "alpha_frac": 0.5865454545, "autogenerated": false, "ratio": 4.30359937402191, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.539014482852191, "avg_score": null, "num_lines": null }
'''Arsenal statuses UI.''' # Copyright 2015 CityGrid Media, LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # import logging from pyramid.view import view_config from arsenalweb.views import ( _api_get, get_authenticated_user, get_nav_urls, get_pag_params, site_layout, ) LOG = logging.getLogger(__name__) @view_config(route_name='status', permission='view', renderer='arsenalweb:templates/status.pt') def view_status(request): '''Handle requests for status UI route.''' page_title = 'Status' auth_user = get_authenticated_user(request) uri = '/api/statuses/{0}'.format(request.matchdict['id']) status = _api_get(request, uri) return { 'au': auth_user, 'page_title': page_title, 'status': status['results'][0], } @view_config(route_name='statuses', permission='view', renderer='arsenalweb:templates/statuses.pt') def view_statuses(request): '''Handle requests for statuses UI route.''' page_title_type = 'objects/' page_title_name = 'statuses' auth_user = get_authenticated_user(request) (perpage, offset) = get_pag_params(request) payload = {} for k in request.GET: payload[k] = request.GET[k] # Force the UI to 50 results per page if not perpage: perpage = 50 payload['perpage'] = perpage uri = '/api/statuses' LOG.info('UI requesting data from API={0},payload={1}'.format(uri, payload)) resp = _api_get(request, uri, payload) total = 0 statuses = [] if resp: total = resp['meta']['total'] statuses = resp['results'] nav_urls = get_nav_urls(request.path, offset, perpage, total, payload) # Used by the columns menu to determine what to show/hide. column_selectors = [ {'name': 'created', 'pretty_name': 'Date Created'}, {'name': 'description', 'pretty_name': 'Description'}, {'name': 'status_id', 'pretty_name': 'Status ID'}, {'name': 'status_name', 'pretty_name': 'Status Name'}, {'name': 'updated', 'pretty_name': 'Date Updated'}, {'name': 'updated_by', 'pretty_name': 'Updated By'}, ] return { 'au': auth_user, 'column_selectors': column_selectors, 'layout': site_layout('max'), 'nav_urls': nav_urls, 'offset': offset, 'page_title_name': page_title_name, 'page_title_type': page_title_type, 'perpage': perpage, 'statuses': statuses, 'total': total, }
{ "repo_name": "CityGrid/arsenal", "path": "server/arsenalweb/views/statuses.py", "copies": "1", "size": "3010", "license": "apache-2.0", "hash": 8773256462018915000, "line_mean": 29.404040404, "line_max": 99, "alpha_frac": 0.6305647841, "autogenerated": false, "ratio": 3.6308805790108565, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9759285648682623, "avg_score": 0.00043194288564658937, "num_lines": 99 }
'''Arsenal tags DB Model''' # Copyright 2015 CityGrid Media, LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # import logging from sqlalchemy import ( Column, Integer, TIMESTAMP, Text, ) from arsenalweb.models.common import ( Base, BaseAudit, get_name_id_dict, get_name_id_list, jsonify, ) LOG = logging.getLogger(__name__) class Tag(Base): '''Arsenal Tag object.''' __tablename__ = 'tags' id = Column(Integer, primary_key=True, nullable=False) name = Column(Text, nullable=False) value = Column(Text, nullable=False) created = Column(TIMESTAMP, nullable=False) updated = Column(TIMESTAMP, nullable=False) updated_by = Column(Text, nullable=False) def __json__(self, request): try: fields = request.params['fields'] if fields == 'all': try: self.value = int(self.value) except ValueError: pass # Everything. all_fields = dict( id=self.id, name=self.name, value=self.value, nodes=get_name_id_list(self.nodes), node_groups=get_name_id_list(self.node_groups), physical_devices=get_name_id_list(self.physical_devices), created=self.created, updated=self.updated, updated_by=self.updated_by, ) return jsonify(all_fields) else: # Always return id, name, and value, then return whatever additional fields # are asked for. resp = get_name_id_dict([self], extra_keys=['value']) my_fields = fields.split(',') # Backrefs are not in the instance dict, so we handle them here. if 'nodes' in my_fields: resp['nodes'] = get_name_id_list(self.nodes) if 'node_groups' in my_fields: resp['node_groups'] = get_name_id_list(self.node_groups) if 'physical_devices' in my_fields: resp['physical_devices'] = get_name_id_list(self.physical_devices) resp.update((key, getattr(self, key)) for key in my_fields if key in self.__dict__) try: resp['value'] = int(resp['value']) except ValueError: pass return jsonify(resp) # Default to returning only id, value, and name. except KeyError: resp = get_name_id_dict([self], extra_keys=['value']) return resp class TagAudit(BaseAudit): '''Arsenal TagAudit object.''' __tablename__ = 'tags_audit'
{ "repo_name": "CityGrid/arsenal", "path": "server/arsenalweb/models/tags.py", "copies": "1", "size": "3348", "license": "apache-2.0", "hash": -7403587274699867000, "line_mean": 30.8857142857, "line_max": 91, "alpha_frac": 0.5537634409, "autogenerated": false, "ratio": 4.25412960609911, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.0006191669276793382, "num_lines": 105 }
'''Arsenal tags UI.''' # Copyright 2015 CityGrid Media, LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # import logging from pyramid.view import view_config from arsenalweb.views import ( _api_get, get_authenticated_user, get_nav_urls, get_pag_params, site_layout, ) LOG = logging.getLogger(__name__) @view_config(route_name='tag', permission='view', renderer='arsenalweb:templates/tag.pt') def view_tag(request): '''Handle requests for tag UI route.''' page_title = 'Tag' auth_user = get_authenticated_user(request) uri = '/api/tags/{0}'.format(request.matchdict['id']) tag = _api_get(request, uri) return { 'au': auth_user, 'page_title': page_title, 'tag': tag['results'][0], } @view_config(route_name='tags', permission='view', renderer='arsenalweb:templates/tags.pt') def view_tags(request): '''Handle requests for tags UI route.''' page_title_type = 'objects/' page_title_name = 'tags' auth_user = get_authenticated_user(request) (perpage, offset) = get_pag_params(request) payload = {} for k in request.GET: payload[k] = request.GET[k] # Force the UI to 50 results per page if not perpage: perpage = 50 payload['perpage'] = perpage uri = '/api/tags' LOG.info('UI requesting data from uri: {0} payload: {1}'.format(uri, payload)) resp = _api_get(request, uri, payload) total = 0 tags = [] if resp: total = resp['meta']['total'] tags = resp['results'] nav_urls = get_nav_urls(request.path, offset, perpage, total, payload) # Used by the columns menu to determine what to show/hide. column_selectors = [ {'name': 'created', 'pretty_name': 'Date Created'}, {'name': 'tag_id', 'pretty_name': 'Tag ID'}, {'name': 'tag_name', 'pretty_name': 'Tag Name'}, {'name': 'tag_value', 'pretty_name': 'Tag Value'}, {'name': 'updated', 'pretty_name': 'Date Updated'}, {'name': 'updated_by', 'pretty_name': 'Updated By'}, ] return { 'au': auth_user, 'column_selectors': column_selectors, 'layout': site_layout('max'), 'nav_urls': nav_urls, 'offset': offset, 'page_title_name': page_title_name, 'page_title_type': page_title_type, 'perpage': perpage, 'tags': tags, 'total': total, }
{ "repo_name": "CityGrid/arsenal", "path": "server/arsenalweb/views/tags.py", "copies": "1", "size": "2924", "license": "apache-2.0", "hash": -6907356200276350000, "line_mean": 28.5353535354, "line_max": 91, "alpha_frac": 0.6183310534, "autogenerated": false, "ratio": 3.5059952038369304, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9622058659544154, "avg_score": 0.0004535195385553339, "num_lines": 99 }
'''Arsenal UI logout.''' # Copyright 2015 CityGrid Media, LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # import logging from pyramid.view import view_config from pyramid.security import forget from arsenalweb.views import ( site_layout, ) LOG = logging.getLogger(__name__) @view_config(route_name='logout', renderer='arsenalweb:templates/logout.pt') def logout(request): '''The logout route.''' page_title = 'Login' message = None try: message = request.params['message'] except KeyError: pass headers = forget(request) # Do I really need this? headers.append(('Set-Cookie', 'un=; Max-Age=0; Path=/')) request.response.headers = headers # No idea why I have to re-define these, but I do or it poops itself request.response.content_type = 'text/html' request.response.charset = 'UTF-8' request.response.status = '200 OK' return { 'layout': site_layout('max'), 'message': message, 'page_title': page_title, }
{ "repo_name": "CityGrid/arsenal", "path": "server/arsenalweb/views/logout.py", "copies": "1", "size": "1532", "license": "apache-2.0", "hash": 3709664017918573000, "line_mean": 29.64, "line_max": 76, "alpha_frac": 0.6853785901, "autogenerated": false, "ratio": 3.764127764127764, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.4949506354227764, "avg_score": null, "num_lines": null }
'''Arsenal UI''' # Copyright 2015 CityGrid Media, LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # import logging import grp import pwd import pam from pyramid.renderers import get_renderer from pyramid.httpexceptions import HTTPFound from pyramid.session import signed_deserialize from pyramid_ldap import groupfinder as ldap_groupfinder from pyramid.response import Response from sqlalchemy.orm.exc import NoResultFound import requests from passlib.hash import sha512_crypt from arsenalweb.models.common import ( DBSession, Group, User, ) LOG = logging.getLogger(__name__) def _api_get(request, uri, payload=None): '''GET request to the API.''' # FIXME: Why did I do this? It returns way to much to the UI. if payload: payload['fields'] = 'all' else: payload = {'fields': 'all'} verify_ssl = request.registry.settings['arsenal.verify_ssl'] api_protocol = request.registry.settings['arsenal.api_protocol'] api_host = request.host api_url = '{0}://{1}{2}'.format(api_protocol, api_host, uri) LOG.info('Requesting data from API: {0} params: {1}'.format(api_url, payload)) resp = requests.get(api_url, verify=verify_ssl, params=payload) if resp.status_code == requests.codes.ok: LOG.debug('Response data: {0}'.format(resp.json())) return resp.json() elif resp.status_code == requests.codes.not_found: LOG.warn('404: Object not found.') else: msg = 'There was an error querying the API: ' \ 'http_status_code={0},reason={1},request={2}'.format(resp.status_code, resp.reason, api_url) LOG.error(msg) raise RuntimeError(msg) return None def _api_put(request, uri, data=None): '''PUT request to the API.''' verify_ssl = request.registry.settings['arsenal.verify_ssl'] api_protocol = request.registry.settings['arsenal.api_protocol'] api_host = request.host headers = request.headers headers['content-type'] = 'application/json' api_url = '{0}://{1}{2}'.format(api_protocol, api_host, uri) LOG.info('Submitting data to API: {0} data: {1}'.format(api_url, data)) resp = requests.put(api_url, verify=verify_ssl, headers=headers, data=data) if resp.status_code == requests.codes.ok: LOG.debug('Response data: {0}'.format(resp.json())) return resp.json() else: msg = 'There was an error querying the API: ' \ 'http_status_code={0},reason={1},request={2}'.format(resp.status_code, resp.reason, api_url) LOG.error(msg) raise RuntimeError(msg) def contains(list, filter): for lst in list: if filter(lst): return True return False def site_layout(level): '''Return the global layout.''' try: if level == 'min': renderer = get_renderer("arsenalweb:templates/min_layout.pt") elif level == 'audit': renderer = get_renderer("arsenalweb:templates/audit_layout.pt") else: renderer = get_renderer("arsenalweb:templates/global_layout.pt") layout = renderer.implementation().macros['layout'] except: raise return layout def global_groupfinder(userid, request): '''Wraps all groupfinders (ldap, pam and db) so we can use one callback in the auth policy.''' groups = None try: LOG.debug('Checking local groups for userid: {0}'.format(userid)) # FIXME: Getting called twice groups = db_groupfinder(userid) if groups: LOG.debug('Found local groups for userid: {0} groups: {1}'.format(userid, groups)) except Exception as ex: LOG.error('{0} ({1})'.format(Exception, ex)) if request.registry.settings['arsenal.use_ldap'] and not groups: try: LOG.debug('Checking ldap groups for userid: {0}'.format(userid)) groups = ldap_groupfinder(userid, request) if groups: LOG.debug('Found ldap groups for userid: {0} groups: {1}'.format(userid, groups)) except Exception as ex: LOG.error('{0} ({1})'.format(Exception, ex)) if request.registry.settings['arsenal.use_pam'] and not groups: try: LOG.debug('Checking pam groups for userid: {0}'.format(userid)) groups = pam_groupfinder(userid) if groups: LOG.debug('Found pam groups for userid: {0} groups: {1}'.format(userid, groups)) except Exception as ex: LOG.error('{0} ({1})'.format(Exception, ex)) return groups def pam_groupfinder(userid): '''Queries pam for a list of groups the user belongs to. Returns either a list of groups (empty if no groups) or None if the user doesn't exist.''' groups = [] try: groups = [g.gr_name for g in grp.getgrall() if userid in g.gr_mem] # Also add the user's default group gid = pwd.getpwnam(userid).pw_gid groups.append(grp.getgrgid(gid).gr_name) except Exception as ex: LOG.error('{0} ({1})'.format(Exception, ex)) LOG.debug('User: {0} has the following groups: {1}'.format(userid, groups)) return groups def pam_authenticate(login, password): '''Checks the validity of a username/password against unix pam.''' try: pam_auth = pam.pam() if pam_auth.authenticate(login, password): return [login] except Exception as ex: LOG.error('{0} ({1})'.format(Exception, ex)) return None def db_groupfinder(userid): '''Queries the db for a list of groups the user belongs to. Returns either a list of groups (empty if no groups) or None if the user doesn't exist.''' groups = None try: user = DBSession.query(User).filter(User.user_name == userid).one() groups = user.get_all_assignments() except NoResultFound: LOG.debug('No db groups for: {0}'.format(userid)) except Exception as ex: LOG.error('{0} ({1})'.format(Exception, ex)) return groups def db_authenticate(login, password): '''Checks the validity of a username/password against what is stored in the database.''' try: q = DBSession.query(User) q = q.filter(User.user_name == login) db_user = q.one() except Exception as e: LOG.debug("%s (%s)" % (Exception, e)) # Should return invalid username here somehow return None try: if sha512_crypt.verify(password, db_user.password): LOG.debug('Successfully authenticated via local DB') return [login] except Exception as e: LOG.error('{0} ({1})'.format(Exception, e)) return None # FIXME: This whole thing sucks def get_authenticated_user(request): '''Gets all the user information for an authenticated user. Checks groups and permissions, and returns a dict of everything.''' authenticated_user = { 'user_id': '', 'login': '', 'groups': '', 'first': '', 'last': '', 'first_last': '', 'auth': False, 'prd_auth': False, 'admin_auth': False, 'cp_auth': False, } user_id = request.authenticated_userid first = '' last = '' groups = [] try: user = DBSession.query(User).filter(User.user_name == user_id).one() first = user.first_name last = user.last_name # FIXME: Getting called twice groups = db_groupfinder(user_id) first_last = '{0} {1}'.format(first, last) auth = True except NoResultFound: LOG.debug('No db user for: {0}'.format(user_id)) except Exception as ex: LOG.error('{0} ({1})'.format(Exception, ex)) if request.registry.settings['arsenal.use_ldap'] and not groups: LOG.debug('Using LDAP...') try: (first, last) = format_user(user_id) groups = ldap_groupfinder(user_id, request) first_last = '{0} {1}'.format(first, last) auth = True except Exception as ex: LOG.error('{0} ({1})'.format(Exception, ex)) if request.registry.settings['arsenal.use_pam'] and not groups: LOG.debug('Using PAM...') try: try: (first, last) = pwd.getpwnam(user_id).pw_gecos.split() except ValueError: first = user_id groups = pam_groupfinder(user_id) first_last = '{0} {1}'.format(first, last) auth = True except Exception as ex: LOG.error('{0} ({1})'.format(Exception, ex)) try: login = validate_username_cookie(request.cookies['un'], request.registry.settings['arsenal.cookie_token']) except: return HTTPFound('/logout?message=Your cookie has been tampered with. You have been logged out') LOG.debug('first: {0} last: {1} first_last: {2} auth: {3} groups: {4}'.format(first, last, first_last, auth, groups)) # authenticated user authenticated_user['user_id'] = user_id authenticated_user['login'] = login authenticated_user['groups'] = groups authenticated_user['first'] = first authenticated_user['last'] = last authenticated_user['first_last'] = first_last authenticated_user['loggedin'] = auth return authenticated_user def get_all_groups(): '''Gets all the groups that are configured in the db and returns a dict of everything.''' # Get the groups from the db group_perms = [] r = DBSession.query(Group).all() for g in range(len(r)): ga = r[g].get_all_assignments() if ga: ga = tuple(ga) group_perms.append([r[g].group_name, ga]) return(group_perms) def format_user(user): '''Remove the extra stuff from ldap users for display purposes.''' (last_name, first_name, junk) = user.split(',', 2) last_name = last_name.rstrip('\\') last_name = last_name.strip('CN=') return(first_name, last_name) def format_groups(groups): '''Remove the extra stuff from ldap group for display purposes.''' formatted = [] for group in range(len(groups)): formatted.append(find_between(groups[group], 'CN=', ',OU=')) return formatted def find_between(srch, first, last): '''Find text in between two delimeters''' try: start = srch.index(first) + len(first) end = srch.index(last, start) return srch[start:end] except ValueError: return "" def validate_username_cookie(cookieval, cookie_token): '''Returns the username if it validates. Otherwise throws an exception.''' return signed_deserialize(cookieval, cookie_token) def get_pag_params(request): '''Parse and return page params.''' try: offset = int(request.GET.getone("start")) except KeyError: offset = 0 try: perpage = int(request.GET.getone("perpage")) except KeyError: # Default limit the web UI to 50 results, no limit for the client. if request.path.startswith('/api/'): perpage = None else: perpage = 50 return (perpage, offset) def get_nav_urls(path, offset, perpage, total, payload=None): '''Format and return navigation urls.''' nav_urls = {} skip_keys = ['start', 'perpage', 'fields'] for key in skip_keys: try: del payload[key] except KeyError: pass nav_start = '{0}?start={1}'.format(path, 0) nav_prev = '{0}?start={1}'.format(path, offset - perpage) nav_next = '{0}?start={1}'.format(path, offset + perpage) nav_end = '{0}?start={1}'.format(path, (total-1)/perpage*perpage) key_params = '' for key, val in payload.items(): key_params += '&{0}={1}'.format(key, val) nav_urls['nav_start'] = '{0}{1}'.format(nav_start, key_params) nav_urls['nav_prev'] = '{0}{1}'.format(nav_prev, key_params) nav_urls['nav_next'] = '{0}{1}'.format(nav_next, key_params) nav_urls['nav_end'] = '{0}{1}'.format(nav_end, key_params) nav_urls['next_disable'] = False if (offset+perpage) >= total: nav_urls['next_disable'] = True return nav_urls
{ "repo_name": "CityGrid/arsenal", "path": "server/arsenalweb/views/__init__.py", "copies": "1", "size": "13451", "license": "apache-2.0", "hash": 5420231399911978000, "line_mean": 33.053164557, "line_max": 104, "alpha_frac": 0.5789904096, "autogenerated": false, "ratio": 3.935342305441779, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.0022523326011981803, "num_lines": 395 }
'''Arsenal user UI.''' # Copyright 2015 CityGrid Media, LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # import logging from pyramid.view import view_config from pyramid.httpexceptions import HTTPFound from passlib.hash import sha512_crypt from arsenalweb.views import ( get_authenticated_user, site_layout, ) from arsenalweb.models.common import ( DBSession, User, ) LOG = logging.getLogger(__name__) @view_config(route_name='user', permission='view', renderer='arsenalweb:templates/user.pt') def view_user(request): '''Handle requests for user UI route.''' auth_user = get_authenticated_user(request) page_title_type = 'user/' page_title_name = 'User Data' change_pw = False perpage = 1 offset = 1 total = 1 if 'user.submitted' in request.POST: email_address = request.POST['email_address'] first_name = request.POST['first_name'] last_name = request.POST['last_name'] password = request.POST['password'] # Need some security checking here if email_address != auth_user['login']: print "Naughty monkey" else: # Update LOG.info('UPDATE: email_address=%s,first_name=%s,last_name=%s,password=%s' % (email_address, first_name, last_name, 'pass')) try: user = DBSession.query(User).filter(User.user_name==email_address).one() user.first_name = first_name user.last_name = last_name if password: LOG.info('Changing password for: %s' % email_address) salt = sha512_crypt.genconfig()[17:33] encrypted_password = sha512_crypt.encrypt(password, salt=salt) user.salt = salt user.password = encrypted_password DBSession.flush() return_url = '/logout?message=Your password has been changed successfully. Log in again.' return HTTPFound(return_url) DBSession.flush() except Exception, e: pass LOG.info("%s (%s)" % (Exception, e)) # Get the changes auth_user = get_authenticated_user(request) subtitle = auth_user['first_last'] column_selectors = [] return { 'au': auth_user, 'change_pw': change_pw, 'column_selectors': column_selectors, 'layout': site_layout('max'), 'offset': offset, 'page_title_name': page_title_name, 'page_title_type': page_title_type, 'perpage': perpage, 'subtitle': subtitle, 'total': total, }
{ "repo_name": "CityGrid/arsenal", "path": "server/arsenalweb/views/user.py", "copies": "1", "size": "3273", "license": "apache-2.0", "hash": -1761750534077628200, "line_mean": 33.09375, "line_max": 109, "alpha_frac": 0.5924228537, "autogenerated": false, "ratio": 4.055762081784387, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5148184935484387, "avg_score": null, "num_lines": null }
# Author: Peter Hinch # Copyright Peter Hinch 2017 Released under the MIT license # This uses a pair of buttons to turn an on-board LED on and off. Its aim is # to enable you to decide if the reliability on the ESP8266 is adequate for # your needs. from sys import platform import uasyncio as asyncio ESP32 = platform == 'esp32' or platform == 'esp32_LoBo' if platform == 'pyboard': from pyb import Pin, LED elif platform == 'esp8266' or ESP32: from machine import Pin, freq else: print('Unsupported platform', platform) from aremote import NEC_IR, REPEAT def cb(data, addr, led): if addr == 0x40: # Adapt for your remote if data == 1: # Button 1. Adapt for your remote/buttons print('LED on') if platform == 'pyboard': led.on() else: led(0) elif data == 2: print('LED off') if platform == 'pyboard': led.off() else: led(1) elif data < REPEAT: print('Bad IR data') else: print('Incorrect remote') def test(): print('Test for IR receiver. Assumes NEC protocol. Turn LED on or off.') if platform == 'pyboard': p = Pin('X3', Pin.IN) led = LED(2) elif platform == 'esp8266': freq(160000000) p = Pin(13, Pin.IN) led = Pin(2, Pin.OUT) led(1) elif ESP32: p = Pin(23, Pin.IN) led = Pin(21, Pin.OUT) # LED with 220Ω series resistor between 3.3V and pin 21 led(1) ir = NEC_IR(p, cb, True, led) # Assume extended address mode r/c loop = asyncio.get_event_loop() loop.run_forever() test()
{ "repo_name": "peterhinch/micropython-async", "path": "v2/nec_ir/art1.py", "copies": "1", "size": "1784", "license": "mit", "hash": 7029406542613063000, "line_mean": 28.7166666667, "line_max": 87, "alpha_frac": 0.5860908581, "autogenerated": false, "ratio": 3.4222648752399234, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9482845271579461, "avg_score": 0.005102092352092353, "num_lines": 60 }
# art3d.py, original mplot3d version by John Porter # Parts rewritten by Reinier Heeres <reinier@heeres.eu> # Minor additions by Ben Axelrod <baxelrod@coroware.com> ''' Module containing 3D artist code and functions to convert 2D artists into 3D versions which can be added to an Axes3D. ''' from __future__ import (absolute_import, division, print_function, unicode_literals) import six from six.moves import zip from matplotlib import lines, text as mtext, path as mpath, colors as mcolors from matplotlib import artist from matplotlib.collections import Collection, LineCollection, \ PolyCollection, PatchCollection, PathCollection from matplotlib.cm import ScalarMappable from matplotlib.patches import Patch from matplotlib.colors import Normalize from matplotlib.cbook import iterable import warnings import numpy as np import math from . import proj3d def norm_angle(a): """Return angle between -180 and +180""" a = (a + 360) % 360 if a > 180: a = a - 360 return a def norm_text_angle(a): """Return angle between -90 and +90""" a = (a + 180) % 180 if a > 90: a = a - 180 return a def get_dir_vector(zdir): if zdir == 'x': return np.array((1, 0, 0)) elif zdir == 'y': return np.array((0, 1, 0)) elif zdir == 'z': return np.array((0, 0, 1)) elif zdir is None: return np.array((0, 0, 0)) elif iterable(zdir) and len(zdir) == 3: return zdir else: raise ValueError("'x', 'y', 'z', None or vector of length 3 expected") class Text3D(mtext.Text): ''' Text object with 3D position and (in the future) direction. ''' def __init__(self, x=0, y=0, z=0, text='', zdir='z', **kwargs): ''' *x*, *y*, *z* Position of text *text* Text string to display *zdir* Direction of text Keyword arguments are passed onto :func:`~matplotlib.text.Text`. ''' mtext.Text.__init__(self, x, y, text, **kwargs) self.set_3d_properties(z, zdir) def set_3d_properties(self, z=0, zdir='z'): x, y = self.get_position() self._position3d = np.array((x, y, z)) self._dir_vec = get_dir_vector(zdir) self.stale = True def draw(self, renderer): proj = proj3d.proj_trans_points([self._position3d, \ self._position3d + self._dir_vec], renderer.M) dx = proj[0][1] - proj[0][0] dy = proj[1][1] - proj[1][0] if dx==0. and dy==0.: # atan2 raises ValueError: math domain error on 0,0 angle = 0. else: angle = math.degrees(math.atan2(dy, dx)) self.set_position((proj[0][0], proj[1][0])) self.set_rotation(norm_text_angle(angle)) mtext.Text.draw(self, renderer) self.stale = False def text_2d_to_3d(obj, z=0, zdir='z'): """Convert a Text to a Text3D object.""" obj.__class__ = Text3D obj.set_3d_properties(z, zdir) class Line3D(lines.Line2D): ''' 3D line object. ''' def __init__(self, xs, ys, zs, *args, **kwargs): ''' Keyword arguments are passed onto :func:`~matplotlib.lines.Line2D`. ''' lines.Line2D.__init__(self, [], [], *args, **kwargs) self._verts3d = xs, ys, zs def set_3d_properties(self, zs=0, zdir='z'): xs = self.get_xdata() ys = self.get_ydata() try: # If *zs* is a list or array, then this will fail and # just proceed to juggle_axes(). zs = float(zs) zs = [zs for x in xs] except TypeError: pass self._verts3d = juggle_axes(xs, ys, zs, zdir) self.stale = True def draw(self, renderer): xs3d, ys3d, zs3d = self._verts3d xs, ys, zs = proj3d.proj_transform(xs3d, ys3d, zs3d, renderer.M) self.set_data(xs, ys) lines.Line2D.draw(self, renderer) self.stale = False def line_2d_to_3d(line, zs=0, zdir='z'): ''' Convert a 2D line to 3D. ''' line.__class__ = Line3D line.set_3d_properties(zs, zdir) def path_to_3d_segment(path, zs=0, zdir='z'): '''Convert a path to a 3D segment.''' if not iterable(zs): zs = np.ones(len(path)) * zs seg = [] pathsegs = path.iter_segments(simplify=False, curves=False) for (((x, y), code), z) in zip(pathsegs, zs): seg.append((x, y, z)) seg3d = [juggle_axes(x, y, z, zdir) for (x, y, z) in seg] return seg3d def paths_to_3d_segments(paths, zs=0, zdir='z'): ''' Convert paths from a collection object to 3D segments. ''' if not iterable(zs): zs = np.ones(len(paths)) * zs segments = [] for path, pathz in zip(paths, zs): segments.append(path_to_3d_segment(path, pathz, zdir)) return segments def path_to_3d_segment_with_codes(path, zs=0, zdir='z'): '''Convert a path to a 3D segment with path codes.''' if not iterable(zs): zs = np.ones(len(path)) * zs seg = [] codes = [] pathsegs = path.iter_segments(simplify=False, curves=False) for (((x, y), code), z) in zip(pathsegs, zs): seg.append((x, y, z)) codes.append(code) seg3d = [juggle_axes(x, y, z, zdir) for (x, y, z) in seg] return seg3d, codes def paths_to_3d_segments_with_codes(paths, zs=0, zdir='z'): ''' Convert paths from a collection object to 3D segments with path codes. ''' if not iterable(zs): zs = np.ones(len(paths)) * zs segments = [] codes_list = [] for path, pathz in zip(paths, zs): segs, codes = path_to_3d_segment_with_codes(path, pathz, zdir) segments.append(segs) codes_list.append(codes) return segments, codes_list class Line3DCollection(LineCollection): ''' A collection of 3D lines. ''' def __init__(self, segments, *args, **kwargs): ''' Keyword arguments are passed onto :func:`~matplotlib.collections.LineCollection`. ''' LineCollection.__init__(self, segments, *args, **kwargs) def set_sort_zpos(self, val): '''Set the position to use for z-sorting.''' self._sort_zpos = val self.stale = True def set_segments(self, segments): ''' Set 3D segments ''' self._segments3d = np.asanyarray(segments) LineCollection.set_segments(self, []) def do_3d_projection(self, renderer): ''' Project the points according to renderer matrix. ''' xyslist = [ proj3d.proj_trans_points(points, renderer.M) for points in self._segments3d] segments_2d = [list(zip(xs, ys)) for (xs, ys, zs) in xyslist] LineCollection.set_segments(self, segments_2d) # FIXME minz = 1e9 for (xs, ys, zs) in xyslist: minz = min(minz, min(zs)) return minz def draw(self, renderer, project=False): if project: self.do_3d_projection(renderer) LineCollection.draw(self, renderer) def line_collection_2d_to_3d(col, zs=0, zdir='z'): """Convert a LineCollection to a Line3DCollection object.""" segments3d = paths_to_3d_segments(col.get_paths(), zs, zdir) col.__class__ = Line3DCollection col.set_segments(segments3d) class Patch3D(Patch): ''' 3D patch object. ''' def __init__(self, *args, **kwargs): zs = kwargs.pop('zs', []) zdir = kwargs.pop('zdir', 'z') Patch.__init__(self, *args, **kwargs) self.set_3d_properties(zs, zdir) def set_3d_properties(self, verts, zs=0, zdir='z'): if not iterable(zs): zs = np.ones(len(verts)) * zs self._segment3d = [juggle_axes(x, y, z, zdir) \ for ((x, y), z) in zip(verts, zs)] self._facecolor3d = Patch.get_facecolor(self) def get_path(self): return self._path2d def get_facecolor(self): return self._facecolor2d def do_3d_projection(self, renderer): s = self._segment3d xs, ys, zs = list(zip(*s)) vxs, vys,vzs, vis = proj3d.proj_transform_clip(xs, ys, zs, renderer.M) self._path2d = mpath.Path(list(zip(vxs, vys))) # FIXME: coloring self._facecolor2d = self._facecolor3d return min(vzs) def draw(self, renderer): Patch.draw(self, renderer) class PathPatch3D(Patch3D): ''' 3D PathPatch object. ''' def __init__(self, path, **kwargs): zs = kwargs.pop('zs', []) zdir = kwargs.pop('zdir', 'z') Patch.__init__(self, **kwargs) self.set_3d_properties(path, zs, zdir) def set_3d_properties(self, path, zs=0, zdir='z'): Patch3D.set_3d_properties(self, path.vertices, zs=zs, zdir=zdir) self._code3d = path.codes def do_3d_projection(self, renderer): s = self._segment3d xs, ys, zs = list(zip(*s)) vxs, vys,vzs, vis = proj3d.proj_transform_clip(xs, ys, zs, renderer.M) self._path2d = mpath.Path(list(zip(vxs, vys)), self._code3d) # FIXME: coloring self._facecolor2d = self._facecolor3d return min(vzs) def get_patch_verts(patch): """Return a list of vertices for the path of a patch.""" trans = patch.get_patch_transform() path = patch.get_path() polygons = path.to_polygons(trans) if len(polygons): return polygons[0] else: return [] def patch_2d_to_3d(patch, z=0, zdir='z'): """Convert a Patch to a Patch3D object.""" verts = get_patch_verts(patch) patch.__class__ = Patch3D patch.set_3d_properties(verts, z, zdir) def pathpatch_2d_to_3d(pathpatch, z=0, zdir='z'): """Convert a PathPatch to a PathPatch3D object.""" path = pathpatch.get_path() trans = pathpatch.get_patch_transform() mpath = trans.transform_path(path) pathpatch.__class__ = PathPatch3D pathpatch.set_3d_properties(mpath, z, zdir) class Patch3DCollection(PatchCollection): ''' A collection of 3D patches. ''' def __init__(self, *args, **kwargs): """ Create a collection of flat 3D patches with its normal vector pointed in *zdir* direction, and located at *zs* on the *zdir* axis. 'zs' can be a scalar or an array-like of the same length as the number of patches in the collection. Constructor arguments are the same as for :class:`~matplotlib.collections.PatchCollection`. In addition, keywords *zs=0* and *zdir='z'* are available. Also, the keyword argument "depthshade" is available to indicate whether or not to shade the patches in order to give the appearance of depth (default is *True*). This is typically desired in scatter plots. """ zs = kwargs.pop('zs', 0) zdir = kwargs.pop('zdir', 'z') self._depthshade = kwargs.pop('depthshade', True) PatchCollection.__init__(self, *args, **kwargs) self.set_3d_properties(zs, zdir) def set_sort_zpos(self, val): '''Set the position to use for z-sorting.''' self._sort_zpos = val self.stale = True def set_3d_properties(self, zs, zdir): # Force the collection to initialize the face and edgecolors # just in case it is a scalarmappable with a colormap. self.update_scalarmappable() offsets = self.get_offsets() if len(offsets) > 0: xs, ys = list(zip(*offsets)) else: xs = [] ys = [] self._offsets3d = juggle_axes(xs, ys, np.atleast_1d(zs), zdir) self._facecolor3d = self.get_facecolor() self._edgecolor3d = self.get_edgecolor() self.stale = True def do_3d_projection(self, renderer): xs, ys, zs = self._offsets3d vxs, vys, vzs, vis = proj3d.proj_transform_clip(xs, ys, zs, renderer.M) fcs = (zalpha(self._facecolor3d, vzs) if self._depthshade else self._facecolor3d) fcs = mcolors.to_rgba_array(fcs, self._alpha) self.set_facecolors(fcs) ecs = (zalpha(self._edgecolor3d, vzs) if self._depthshade else self._edgecolor3d) ecs = mcolors.to_rgba_array(ecs, self._alpha) self.set_edgecolors(ecs) PatchCollection.set_offsets(self, list(zip(vxs, vys))) if vzs.size > 0: return min(vzs) else: return np.nan class Path3DCollection(PathCollection): ''' A collection of 3D paths. ''' def __init__(self, *args, **kwargs): """ Create a collection of flat 3D paths with its normal vector pointed in *zdir* direction, and located at *zs* on the *zdir* axis. 'zs' can be a scalar or an array-like of the same length as the number of paths in the collection. Constructor arguments are the same as for :class:`~matplotlib.collections.PathCollection`. In addition, keywords *zs=0* and *zdir='z'* are available. Also, the keyword argument "depthshade" is available to indicate whether or not to shade the patches in order to give the appearance of depth (default is *True*). This is typically desired in scatter plots. """ zs = kwargs.pop('zs', 0) zdir = kwargs.pop('zdir', 'z') self._depthshade = kwargs.pop('depthshade', True) PathCollection.__init__(self, *args, **kwargs) self.set_3d_properties(zs, zdir) def set_sort_zpos(self, val): '''Set the position to use for z-sorting.''' self._sort_zpos = val self.stale = True def set_3d_properties(self, zs, zdir): # Force the collection to initialize the face and edgecolors # just in case it is a scalarmappable with a colormap. self.update_scalarmappable() offsets = self.get_offsets() if len(offsets) > 0: xs, ys = list(zip(*offsets)) else: xs = [] ys = [] self._offsets3d = juggle_axes(xs, ys, np.atleast_1d(zs), zdir) self._facecolor3d = self.get_facecolor() self._edgecolor3d = self.get_edgecolor() self.stale = True def do_3d_projection(self, renderer): xs, ys, zs = self._offsets3d vxs, vys, vzs, vis = proj3d.proj_transform_clip(xs, ys, zs, renderer.M) fcs = (zalpha(self._facecolor3d, vzs) if self._depthshade else self._facecolor3d) fcs = mcolors.to_rgba_array(fcs, self._alpha) self.set_facecolors(fcs) ecs = (zalpha(self._edgecolor3d, vzs) if self._depthshade else self._edgecolor3d) ecs = mcolors.to_rgba_array(ecs, self._alpha) self.set_edgecolors(ecs) PathCollection.set_offsets(self, list(zip(vxs, vys))) if vzs.size > 0 : return min(vzs) else : return np.nan def patch_collection_2d_to_3d(col, zs=0, zdir='z', depthshade=True): """ Convert a :class:`~matplotlib.collections.PatchCollection` into a :class:`Patch3DCollection` object (or a :class:`~matplotlib.collections.PathCollection` into a :class:`Path3DCollection` object). Keywords: *za* The location or locations to place the patches in the collection along the *zdir* axis. Defaults to 0. *zdir* The axis in which to place the patches. Default is "z". *depthshade* Whether to shade the patches to give a sense of depth. Defaults to *True*. """ if isinstance(col, PathCollection): col.__class__ = Path3DCollection elif isinstance(col, PatchCollection): col.__class__ = Patch3DCollection col._depthshade = depthshade col.set_3d_properties(zs, zdir) class Poly3DCollection(PolyCollection): ''' A collection of 3D polygons. ''' def __init__(self, verts, *args, **kwargs): ''' Create a Poly3DCollection. *verts* should contain 3D coordinates. Keyword arguments: zsort, see set_zsort for options. Note that this class does a bit of magic with the _facecolors and _edgecolors properties. ''' zsort = kwargs.pop('zsort', True) PolyCollection.__init__(self, verts, *args, **kwargs) self.set_zsort(zsort) self._codes3d = None _zsort_functions = { 'average': np.average, 'min': np.min, 'max': np.max, } def set_zsort(self, zsort): ''' Set z-sorting behaviour: boolean: if True use default 'average' string: 'average', 'min' or 'max' ''' if zsort is True: zsort = 'average' if zsort is not False: if zsort in self._zsort_functions: zsortfunc = self._zsort_functions[zsort] else: return False else: zsortfunc = None self._zsort = zsort self._sort_zpos = None self._zsortfunc = zsortfunc self.stale = True def get_vector(self, segments3d): """Optimize points for projection""" si = 0 ei = 0 segis = [] points = [] for p in segments3d: points.extend(p) ei = si+len(p) segis.append((si, ei)) si = ei if len(segments3d) > 0 : xs, ys, zs = list(zip(*points)) else : # We need this so that we can skip the bad unpacking from zip() xs, ys, zs = [], [], [] ones = np.ones(len(xs)) self._vec = np.array([xs, ys, zs, ones]) self._segis = segis def set_verts(self, verts, closed=True): '''Set 3D vertices.''' self.get_vector(verts) # 2D verts will be updated at draw time PolyCollection.set_verts(self, [], closed) def set_verts_and_codes(self, verts, codes): '''Sets 3D vertices with path codes''' # set vertices with closed=False to prevent PolyCollection from # setting path codes self.set_verts(verts, closed=False) # and set our own codes instead. self._codes3d = codes def set_3d_properties(self): # Force the collection to initialize the face and edgecolors # just in case it is a scalarmappable with a colormap. self.update_scalarmappable() self._sort_zpos = None self.set_zsort(True) self._facecolors3d = PolyCollection.get_facecolors(self) self._edgecolors3d = PolyCollection.get_edgecolors(self) self._alpha3d = PolyCollection.get_alpha(self) self.stale = True def set_sort_zpos(self,val): '''Set the position to use for z-sorting.''' self._sort_zpos = val self.stale = True def do_3d_projection(self, renderer): ''' Perform the 3D projection for this object. ''' # FIXME: This may no longer be needed? if self._A is not None: self.update_scalarmappable() self._facecolors3d = self._facecolors txs, tys, tzs = proj3d.proj_transform_vec(self._vec, renderer.M) xyzlist = [(txs[si:ei], tys[si:ei], tzs[si:ei]) for si, ei in self._segis] # This extra fuss is to re-order face / edge colors cface = self._facecolors3d cedge = self._edgecolors3d if len(cface) != len(xyzlist): cface = cface.repeat(len(xyzlist), axis=0) if len(cedge) != len(xyzlist): if len(cedge) == 0: cedge = cface else: cedge = cedge.repeat(len(xyzlist), axis=0) # if required sort by depth (furthest drawn first) if self._zsort: indices = range(len(xyzlist)) z_segments_2d = [(self._zsortfunc(zs), list(zip(xs, ys)), fc, ec, idx) for (xs, ys, zs), fc, ec, idx in zip(xyzlist, cface, cedge, indices)] z_segments_2d.sort(key=lambda x: x[0], reverse=True) else: raise ValueError("whoops") segments_2d = [s for z, s, fc, ec, idx in z_segments_2d] if self._codes3d is not None: codes = [self._codes3d[idx] for z, s, fc, ec, idx in z_segments_2d] PolyCollection.set_verts_and_codes(self, segments_2d, codes) else: PolyCollection.set_verts(self, segments_2d) self._facecolors2d = [fc for z, s, fc, ec, idx in z_segments_2d] if len(self._edgecolors3d) == len(cface): self._edgecolors2d = [ec for z, s, fc, ec, idx in z_segments_2d] else: self._edgecolors2d = self._edgecolors3d # Return zorder value if self._sort_zpos is not None: zvec = np.array([[0], [0], [self._sort_zpos], [1]]) ztrans = proj3d.proj_transform_vec(zvec, renderer.M) return ztrans[2][0] elif tzs.size > 0 : # FIXME: Some results still don't look quite right. # In particular, examine contourf3d_demo2.py # with az = -54 and elev = -45. return np.min(tzs) else : return np.nan def set_facecolor(self, colors): PolyCollection.set_facecolor(self, colors) self._facecolors3d = PolyCollection.get_facecolor(self) set_facecolors = set_facecolor def set_edgecolor(self, colors): PolyCollection.set_edgecolor(self, colors) self._edgecolors3d = PolyCollection.get_edgecolor(self) set_edgecolors = set_edgecolor def set_alpha(self, alpha): """ Set the alpha tranparencies of the collection. *alpha* must be a float or *None*. ACCEPTS: float or None """ if alpha is not None: try: float(alpha) except TypeError: raise TypeError('alpha must be a float or None') artist.Artist.set_alpha(self, alpha) try: self._facecolors = mcolors.to_rgba_array( self._facecolors3d, self._alpha) except (AttributeError, TypeError, IndexError): pass try: self._edgecolors = mcolors.to_rgba_array( self._edgecolors3d, self._alpha) except (AttributeError, TypeError, IndexError): pass self.stale = True def get_facecolors(self): return self._facecolors2d get_facecolor = get_facecolors def get_edgecolors(self): return self._edgecolors2d get_edgecolor = get_edgecolors def draw(self, renderer): return Collection.draw(self, renderer) def poly_collection_2d_to_3d(col, zs=0, zdir='z'): """Convert a PolyCollection to a Poly3DCollection object.""" segments_3d, codes = paths_to_3d_segments_with_codes(col.get_paths(), zs, zdir) col.__class__ = Poly3DCollection col.set_verts_and_codes(segments_3d, codes) col.set_3d_properties() def juggle_axes(xs, ys, zs, zdir): """ Reorder coordinates so that 2D xs, ys can be plotted in the plane orthogonal to zdir. zdir is normally x, y or z. However, if zdir starts with a '-' it is interpreted as a compensation for rotate_axes. """ if zdir == 'x': return zs, xs, ys elif zdir == 'y': return xs, zs, ys elif zdir[0] == '-': return rotate_axes(xs, ys, zs, zdir) else: return xs, ys, zs def rotate_axes(xs, ys, zs, zdir): """ Reorder coordinates so that the axes are rotated with zdir along the original z axis. Prepending the axis with a '-' does the inverse transform, so zdir can be x, -x, y, -y, z or -z """ if zdir == 'x': return ys, zs, xs elif zdir == '-x': return zs, xs, ys elif zdir == 'y': return zs, xs, ys elif zdir == '-y': return ys, zs, xs else: return xs, ys, zs def iscolor(c): try: if len(c) == 4 or len(c) == 3: if iterable(c[0]): return False if hasattr(c[0], '__float__'): return True except: return False return False def get_colors(c, num): """Stretch the color argument to provide the required number num""" if type(c) == type("string"): c = mcolors.to_rgba(c) if iscolor(c): return [c] * num if len(c) == num: return c elif iscolor(c): return [c] * num elif len(c) == 0: #if edgecolor or facecolor is specified as 'none' return [[0,0,0,0]] * num elif iscolor(c[0]): return [c[0]] * num else: raise ValueError('unknown color format %s' % c) def zalpha(colors, zs): """Modify the alphas of the color list according to depth""" # FIXME: This only works well if the points for *zs* are well-spaced # in all three dimensions. Otherwise, at certain orientations, # the min and max zs are very close together. # Should really normalize against the viewing depth. colors = get_colors(colors, len(zs)) if zs.size > 0 : norm = Normalize(min(zs), max(zs)) sats = 1 - norm(zs) * 0.7 colors = [(c[0], c[1], c[2], c[3] * s) for c, s in zip(colors, sats)] return colors
{ "repo_name": "unnikrishnankgs/va", "path": "venv/lib/python3.5/site-packages/mpl_toolkits/mplot3d/art3d.py", "copies": "10", "size": "25411", "license": "bsd-2-clause", "hash": -3191401277897537000, "line_mean": 31.0441361917, "line_max": 89, "alpha_frac": 0.5754200937, "autogenerated": false, "ratio": 3.431136916014043, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.001765485500724546, "num_lines": 793 }
"""art_app URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.9/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.conf.urls import url, include 2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls')) """ from django.conf import settings from django.conf.urls import url, include from django.conf.urls.static import static from django.contrib import admin from django.views.decorators.csrf import csrf_exempt from graphene_django.views import GraphQLView from .schema import schema urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^graphql', csrf_exempt(GraphQLView.as_view(graphiql=True))), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
{ "repo_name": "creimers/graphene-advent", "path": "src/config/urls.py", "copies": "1", "size": "1111", "license": "mit", "hash": -3796951876503669000, "line_mean": 37.3103448276, "line_max": 79, "alpha_frac": 0.7308730873, "autogenerated": false, "ratio": 3.493710691823899, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.4724583779123899, "avg_score": null, "num_lines": null }
ART = 'art-default.jpg' ICON = 'icon-default.png' SEARCH_ICON = 'icon-search.png' OPTIONS_ICON = 'icon-options.png' NEXT_ICON = 'icon-next.png' BACK_ICON = 'icon-back.png' ADD_ICON = 'icon-add.png' REMOVE_ICON = 'icon-remove.png' from plex_music_service import PlexMusicService def on_error(e): Log(e) return ObjectContainer(header='Results', message=unicode(e)) service = PlexMusicService(on_error) import common import albums import artists import collections import genres import audio_tracks def Start(): # Initialize the plug-in HTTP.CacheTime = CACHE_1HOUR common.validate_prefs() @handler('/music/music', 'Muzarbuz', thumb=ICON, art=ART) def MainMenu(complete=False, offline=False): oc = ObjectContainer(title1='Muzarbuz', art=R(ART)) oc.http_cookies = HTTP.CookiesForURL(service.API_URL) oc = ObjectContainer(title2=unicode(L('Music'))) oc.add(DirectoryObject(key=Callback(albums.GetAlbumsMenu, title=L('Albums')), title=unicode(L('Albums')))) oc.add(DirectoryObject(key=Callback(artists.GetArtistsMenu, title=L('Artists')), title=unicode(L('Artists')))) oc.add(DirectoryObject(key=Callback(collections.GetCollectionsMenu, title=L('Collections')), title=unicode(L('Collections')))) oc.add(DirectoryObject(key=Callback(genres.GetGenresMenu, title=L('Genres')), title=unicode(L('Genres')))) common.add_search_music(oc) return oc
{ "repo_name": "shvets/music-plex-plugin", "path": "src/lib/plex_plugin/Contents/Code/__init__.py", "copies": "1", "size": "1400", "license": "mit", "hash": 5043477883826753000, "line_mean": 29.4347826087, "line_max": 130, "alpha_frac": 0.7278571429, "autogenerated": false, "ratio": 3.0973451327433628, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.4325202275643363, "avg_score": null, "num_lines": null }
""" artemis_pcie Concrete interface for Nysa on the artemis_pcie board """ __author__ = 'you@example.com' import sys import os import time from collections import OrderedDict from array import array as Array from nysa.cbuilder.sdb import SDBError from nysa.host.nysa import Nysa from nysa.host.nysa import NysaError from nysa.host.nysa import NysaCommError from nysa.host.driver.utils import dword_to_array from nysa.host.driver.utils import array_to_dword from nysa.common.print_utils import print_32bit_hex_array IDWORD = 0xCD15DBE5 CMD_COMMAND_RESET = 0x0080 CMD_PERIPHERAL_WRITE = 0x0081 CMD_PERIPHERAL_WRITE_FIFO = 0x0082 CMD_PERIPHERAL_READ = 0x0083 CMD_PERIPHERAL_READ_FIFO = 0x0084 CMD_MEMORY_WRITE = 0x0085 CMD_MEMORY_READ = 0x0086 CMD_DMA_WRITE = 0x0087 CMD_DMA_READ = 0x0088 CMD_PING = 0x0089 CMD_READ_CONFIG = 0x008A BAR0_ADDR = 0x00000000 STATUS_BUFFER_ADDRESS = 0x01000000 WRITE_BUFFER_A_ADDRESS = 0x02000000 WRITE_BUFFER_B_ADDRESS = 0x03000000 READ_BUFFER_A_ADDRESS = 0x04000000 READ_BUFFER_B_ADDRESS = 0x05000000 BUFFER_SIZE = 0x00000400 MAX_PACKET_SIZE = 0x40 #Register Values HDR_STATUS_BUF_ADDR = "status_buf" HDR_BUFFER_READY = "hst_buffer_rdy" HDR_WRITE_BUF_A_ADDR = "write_buffer_a" HDR_WRITE_BUF_B_ADDR = "write_buffer_b" HDR_READ_BUF_A_ADDR = "read_buffer_a" HDR_READ_BUF_B_ADDR = "read_buffer_b" HDR_BUFFER_SIZE = "dword_buffer_size" HDR_INDEX_VALUEA = "index value a" HDR_INDEX_VALUEB = "index value b" HDR_DEV_ADDR = "device_addr" STS_DEV_STATUS = "device_status" STS_BUF_RDY = "dev_buffer_rdy" STS_BUF_POS = "hst_buf_addr" STS_INTERRUPT = "interrupt" HDR_AUX_BUFFER_READY = "hst_buffer_rdy" REGISTERS = OrderedDict([ (HDR_STATUS_BUF_ADDR , "Address of the Status Buffer on host computer" ), (HDR_BUFFER_READY , "Buffer Ready (Controlled by host)" ), (HDR_WRITE_BUF_A_ADDR , "Address of Write Buffer 0 on host computer" ), (HDR_WRITE_BUF_B_ADDR , "Address of Write Buffer 1 on host computer" ), (HDR_READ_BUF_A_ADDR , "Address of Read Buffer 0 on host computer" ), (HDR_READ_BUF_B_ADDR , "Address of Read Buffer 1 on host computer" ), (HDR_BUFFER_SIZE , "Size of the buffer on host computer" ), (HDR_INDEX_VALUEA , "Value of Index A" ), (HDR_INDEX_VALUEB , "Value of Index B" ), (HDR_DEV_ADDR , "Address to read from or write to on device" ), (STS_DEV_STATUS , "Device Status" ), (STS_BUF_RDY , "Buffer Ready Status (Controller from device)" ), (STS_BUF_POS , "Address on Host" ), (STS_INTERRUPT , "Interrupt Status" ), (HDR_AUX_BUFFER_READY , "Buffer Ready (Controlled by host)" ) ]) SB_READY = "ready" SB_WRITE = "write" SB_READ = "read" SB_FIFO = "flag_fifo" SB_PING = "ping" SB_READ_CFG = "read_cfg" SB_UNKNOWN_CMD = "unknown_cmd" SB_PPFIFO_STALL = "ppfifo_stall" SB_HOST_BUF_STALL = "host_buf_stall" SB_PERIPH = "flag_peripheral" SB_MEM = "flag_mem" SB_DMA = "flag_dma" SB_INTERRUPT = "interrupt" SB_RESET = "reset" SB_DONE = "done" SB_CMD_ERR = "error" STATUS_BITS = OrderedDict([ (SB_READY , "Ready for new commands" ), (SB_WRITE , "Write Command Enabled" ), (SB_READ , "Read Command Enabled" ), (SB_FIFO , "Flag: Read/Write FIFO" ), (SB_PING , "Ping Command" ), (SB_READ_CFG , "Read Config Request" ), (SB_UNKNOWN_CMD , "Unknown Command" ), (SB_PPFIFO_STALL , "Stall Due to Ping Pong FIFO" ), (SB_HOST_BUF_STALL , "Stall Due to Host Buffer" ), (SB_PERIPH , "Flag: Peripheral Bus" ), (SB_MEM , "Flag: Memory" ), (SB_DMA , "Flag: DMA" ), (SB_INTERRUPT , "Device Initiated Interrupt" ), (SB_RESET , "Reset Command" ), (SB_DONE , "Command Done" ), (SB_CMD_ERR , "Error executing command" ) ]) ARTEMIS_MEMORY_OFFSET = 0x0100000000 class ArtemisPcie(Nysa): def __init__(self, path, status = None): Nysa.__init__(self, status) self.path = path self.dev = None self.dev = os.open(path, os.O_RDWR) def set_command_mode(self): #XXX: Change this to a seperate file os.lseek(self.dev, 0, os.SEEK_END) def set_data_mode(self): #XXX: Change this to a seperate file os.lseek(self.dev, 0, os.SEEK_SET) def set_dev_addr(self, address): self.dev_addr = address reg = NysaPCIEConfig.get_config_reg(HDR_DEV_ADDR) self.write_pcie_reg(reg, address) def write_pcie_reg(self, address, data): d = Array('B') d.extend(dword_to_array(address)) d.extend(dword_to_array(data)) self.set_command_mode() #self.dev.write(d) os.write(self.dev, d) self.set_data_mode() def write_pcie_command(self, command, count, address): d = Array('B') d.extend(dword_to_array(command)) d.extend(dword_to_array(count)) d.extend(dword_to_array(address)) self.set_command_mode() #self.dev.write(d) os.write(self.dev, d) self.set_data_mode() def read(self, address, length = 1, disable_auto_inc = False): """read Generic read command used to read data from a Nysa image Args: length (int): Number of 32 bit words to read from the FPGA address (int): Address of the register/memory to read disable_auto_inc (bool): if true, auto increment feature will be disabled Returns: (Array of unsigned bytes): A byte array containtin the raw data returned from Nysa Raises: NysaCommError: When a failure of communication is detected """ #print "Read" d = Array('B') if length == 0: length = 1 command = 0x00000002 d.extend(dword_to_array(IDWORD)) if address >= ARTEMIS_MEMORY_OFFSET: address -= ARTEMIS_MEMORY_OFFSET command |= 0x10000 if disable_auto_inc: command |= 0x20000 d.extend(dword_to_array(command)) d.extend(dword_to_array(length)) d.extend(dword_to_array(address)) hdr_byte_len = len(d) hdr_dword_len = hdr_byte_len / 4 self.write_pcie_command(CMD_PERIPHERAL_WRITE, hdr_dword_len, 0x00) os.write(self.dev, d) self.write_pcie_command(CMD_PERIPHERAL_READ, length + hdr_dword_len, 0x00) #print "Read Command" #print_32bit_hex_array(d) data = Array('B', os.read(self.dev, ((length * 4) + hdr_byte_len))) #print "Data:" #print_32bit_hex_array(data) return data[hdr_byte_len:] def write(self, address, data, disable_auto_inc = False): """write Generic write command usd to write data to a Nysa image Args: address (int): Address of the register/memory to read data (array of unsigned bytes): Array of raw bytes to send to the device disable_auto_inc (bool): if true, auto increment feature will be disabled Returns: Nothing Raises: AssertionError: This function must be overriden by a board specific implementation """ while (len(data) % 4) != 0: data.append(0x00) length = len(data) / 4 d = Array('B') command = 0x00000001 d.extend(dword_to_array(IDWORD)) if address >= ARTEMIS_MEMORY_OFFSET: address -= ARTEMIS_MEMORY_OFFSET command |= 0x10000 if disable_auto_inc: command |= 0x20000 d.extend(dword_to_array(command)) d.extend(dword_to_array(length)) d.extend(dword_to_array(address)) d.extend(data) #print "Write Command" self.write_pcie_command(CMD_PERIPHERAL_WRITE, (len(d) / 4), 0x00) #print "Data:" #print_32bit_hex_array(d) os.write(self.dev, d) def ping(self): """ping Pings the Nysa image Args: Nothing Returns: Nothing Raises: NysaCommError: When a failure of communication is detected """ return #raise AssertionError("%s not implemented" % sys._getframe().f_code.co_name) def reset(self): """reset Software reset the Nysa FPGA Master, this may not actually reset the entire FPGA image Args: Nothing Returns: Nothing Raises: NysaCommError: A failure of communication is detected """ self.write_pcie_command(CMD_COMMAND_RESET, 0, 0) #raise AssertionError("%s not implemented" % sys._getframe().f_code.co_name) def is_programmed(self): """ Returns True if the FPGA is programmed Args: Nothing Returns (Boolean): True: FPGA is programmed False: FPGA is not programmed Raises: NysaCommError: A failure of communication is detected """ return True #raise AssertionError("%s not implemented" % sys._getframe().f_code.co_name) def get_sdb_base_address(self): """ Return the base address of the SDB (This is platform specific) Args: Nothing Returns: 32-bit unsigned integer of the address where the SDB can be read Raises: Nothing """ return 0x00000000 def wait_for_interrupts(self, wait_time = 1): """wait_for_interrupts listen for interrupts for the specified amount of time Args: wait_time (int): the amount of time in seconds to wait for an interrupt Returns: (boolean): True: Interrupts were detected False: No interrupts detected Raises: NysaCommError: A failure of communication is detected """ raise AssertionError("%s not implemented" % sys._getframe().f_code.co_name) def register_interrupt_callback(self, index, callback): """ register_interrupt Setup the thread to call the callback when an interrupt is detected Args: index (Integer): bit position of the device if the device is 1, then set index = 1 callback: a function to call when an interrupt is detected Returns: Nothing Raises: Nothing """ #raise AssertionError("%s not implemented" % sys._getframe().f_code.co_name) return def unregister_interrupt_callback(self, index, callback = None): """ unregister_interrupt_callback Removes an interrupt callback from the reader thread list Args: index (Integer): bit position of the associated device EX: if the device that will receive callbacks is 1, index = 1 callback: a function to remove from the callback list Returns: Nothing Raises: Nothing (This function fails quietly if ther callback is not found) """ #raise AssertionError("%s not implemented" % sys._getframe().f_code.co_name) return def get_board_name(self): return "artemis_pcie" def upload(self, filepath): """ Uploads an image to a board Args: filepath (String): path to the file to upload Returns: Nothing Raises: NysaError: Failed to upload data AssertionError: Not Implemented """ raise AssertionError("%s not implemented" % sys._getframe().f_code.co_name) def program (self): """ Initiate an FPGA program sequence, THIS DOES NOT UPLOAD AN IMAGE, use upload to upload an FPGA image Args: Nothing Returns: Nothing Raises: AssertionError: Not Implemented """ raise AssertionError("%s not implemented" % sys._getframe().f_code.co_name) def ioctl(self, name, arg = None): """ Platform specific functions to execute on a Nysa device implementation. For example a board may be capable of setting an external voltage or reading configuration data from an EEPROM. All these extra functions cannot be encompused in a generic driver Args: name (String): Name of the function to execute args (object): A generic object that can be used to pass an arbitrary or multiple arbitrary variables to the device Returns: (object) an object from the underlying function Raises: NysaError: An implementation specific error """ raise AssertionError("%s not implemented" % sys._getframe().f_code.co_name) def list_ioctl(self): """ Return a tuple of ioctl functions and argument types and descriptions in the following format: { [name, description, args_type_object], [name, description, args_type_object] ... } Args: Nothing Raises: AssertionError: Not Implemented """ raise AssertionError("%s not implemented" % sys._getframe().f_code.co_name)
{ "repo_name": "CospanDesign/nysa-artemis-pcie-platform", "path": "artemis_pcie/artemis_pcie.py", "copies": "1", "size": "14373", "license": "mit", "hash": 8163939004843837000, "line_mean": 30.5197368421, "line_max": 85, "alpha_frac": 0.5561817296, "autogenerated": false, "ratio": 3.792348284960422, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.48485300145604215, "avg_score": null, "num_lines": null }
""" Art Gatherer class module """ from collections import namedtuple from datetime import datetime from urllib import request import numpy as np from mtgsdk import Card, Set import cv2 from colorpie.image_processing import ImageProcessing MagicCard = namedtuple('MagicCard', [ 'card_id', 'name', 'set_code', 'set_name', 'color_identity', 'image', 'artwork' ]) class ArtGatherer: """ Wrapper class to fetch card information from mtgsdk """ def __init__(self): pass @staticmethod def _color_to_identity(colors): """ Returns the color identity based on a list of card colors Usefull to name colorless and Multicolor cards """ if not colors: return 'Colorless' if len(colors) > 1: return 'Multicolor' return colors[0] @staticmethod def _url_to_image(image_url='goo.gl/QBqtqE'): """ Returns a cv2 image object from a gatherer image_id """ resp = request.urlopen(image_url) image = np.asarray(bytearray(resp.read()), dtype="uint8") image = cv2.imdecode(image, cv2.IMREAD_COLOR) return image @staticmethod def _get_artwork(card, image): """ Crops image to fit artwork only.""" return ImageProcessing.crop_image(image) @classmethod def _build_magic_card(cls, card): identity = cls._color_to_identity(card.colors) image = cls._url_to_image(card.image_url) artwork = cls._get_artwork(card, image) return MagicCard( card.multiverse_id, card.name, card.set, card.set_name, identity, image, artwork ) @classmethod def get_card_info(cls, card_id=40545): """ Returns a cv2 image object from a multiverse id of a specific card """ card = Card.find(card_id) return cls._build_magic_card(card) @staticmethod def print_cardset_names(): all_sets = Set.all() for mtgset in all_sets: print(mtgset.code, mtgset.name) @classmethod def get_full_set(cls, code=None): """ Returns a card list for a full set based on set codename """ card_set = list() if code is None: return card_set print('[INFO]\tSearching for cards...') fullset = Card.where(set=code).all() print('[INFO]\tBuilding card set...') for card in fullset: # Skip lands. Too basic if 'Land' in card.types: continue magic_card = cls._build_magic_card(card) card_set.append(( magic_card.image, magic_card.color_identity, magic_card.artwork)) return card_set @classmethod def get_card_list(cls, card_id_list=None): """ Returns card list based on a list of multiverse ids """ cardlist = list() for cid in card_id_list: cardlist.append(cls.get_card_info(cid)) return cardlist
{ "repo_name": "valenc3x/colorpie", "path": "colorpie/art_gatherer.py", "copies": "1", "size": "3105", "license": "mit", "hash": -350704166996315600, "line_mean": 26.972972973, "line_max": 78, "alpha_frac": 0.5748792271, "autogenerated": false, "ratio": 3.9056603773584904, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.49805396044584904, "avg_score": null, "num_lines": null }
# Arthon by MohamadKh75 # 2017-10-05 # ******************** from pathlib import Path import linecache # Set the Alphabet folder path alphabet_folder_path = Path("Alphabet").resolve() number_folder_path = Path("Number").resolve() symbol_folder_path = Path("Symbol").resolve() # Find the Path of Symbol def pathFinder(letter): return { '!': str(symbol_folder_path) + str("\\") + "!.txt", '#': str(symbol_folder_path) + str("\\") + "#.txt", ',': str(symbol_folder_path) + str("\\") + ",.txt", '.': str(symbol_folder_path) + str("\\") + "." + ".txt", '-': str(symbol_folder_path) + str("\\") + "-.txt", '@': str(symbol_folder_path) + str("\\") + "@.txt", '_': str(symbol_folder_path) + str("\\") + "_.txt", '+': str(symbol_folder_path) + str("\\") + "+.txt", ':': str(symbol_folder_path) + str("\\") + "colon.txt", }[letter] # Create Pure Arthon [ Art + Python ] def arthonize(user_text): result = open("Result.txt", 'w') for line_number in range(1, 10): arr = list(user_text) for x in range(0, len(arr)): letter = arr[x] # if it's Capital - AA is Capital A if 65 <= ord(letter) <= 90: letter_file = str(alphabet_folder_path) + str("\\") + str(letter) + str(letter) + ".txt" letter_txt = linecache.getline(letter_file, line_number).strip('\n') result.write(letter_txt) # if it's small - a is small a elif 97 <= ord(letter) <= 122: letter_file = str(alphabet_folder_path) + str("\\") + str(letter) + ".txt" letter_txt = linecache.getline(letter_file, line_number).strip('\n') result.write(letter_txt) # if it's Number elif 48 <= ord(letter) <= 57: letter_file = str(number_folder_path) + str("\\") + str(letter) + ".txt" letter_txt = linecache.getline(letter_file, line_number).strip('\n') result.write(letter_txt) # if it's Space elif ord(letter) == 32: result.write(" ") # if it's Symbol elif ord(letter) == 33 or 35 or 44 or 46 or 45 or 64 or 95 or 46 or 58: letter_file = pathFinder(letter) letter_txt = linecache.getline(letter_file, line_number).strip('\n') result.write(letter_txt) # if it's some kind of special symbol # NOT SUPPORTED in Ver. 3.0 - Will Be Added in Ver. 3.1 Someday Maybe...! else: print("Sorry, Some Symbols are NOT supported yet :)\n" "Someday I'll Add them in next version, Maybe!") return result.write('\n') result.close() def lower(user_text): arr = list(user_text) arr = [element.lower() for element in arr] arthonize(arr) def upper(user_text): arr = list(user_text) arr = [element.upper() for element in arr] arthonize(arr) def toggle(user_text): arr = list(user_text) arr = [element.swapcase() for element in arr] arthonize(arr)
{ "repo_name": "MohamadKh75/Arthon", "path": "Arthon.py", "copies": "1", "size": "3164", "license": "mit", "hash": 2649466598983160000, "line_mean": 32.3052631579, "line_max": 104, "alpha_frac": 0.5252844501, "autogenerated": false, "ratio": 3.5510662177328842, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9570964337939205, "avg_score": 0.0010772659787359805, "num_lines": 95 }
""" Article class """ import os import re import subprocess import socket import smtplib import tempfile import datetime from builtins import input from email.mime.text import MIMEText import mistune import git from cmddocs.utils import * from cmddocs.rendering import md_to_ascii # Function definitions def list_articles(dir, extension): "lists all articles in current dir and below" try: DEVNULL = open(os.devnull, 'wb') listing = subprocess.check_output(["tree", dir], stderr=DEVNULL) listing = remove_fileextension(listing.decode('utf-8'), extension) print(listing) except OSError: print("Error: tree not installed") return False except subprocess.CalledProcessError: print("Error: File or Directory not found") def list_directories(dir): "lists all directories in current dir and below" try: DEVNULL = open(os.devnull, 'wb') listing = subprocess.check_output(["tree", "-d", dir], stderr=DEVNULL) print(listing.decode('utf-8')) except OSError: print("Error: tree not installed") return False except subprocess.CalledProcessError: print("Error: File or Directory not found") def change_directory(dir, datadir): "changes directory" d = os.path.join(os.getcwd(), dir) # dont cd out of datadir if datadir not in d: d = datadir # if empty, switch to datadir if not dir: d = datadir # switch to dir try: os.chdir(d) return d except OSError: print("Error: Directory %s not found" % dir) def edit_article(article, directory, editor, repo, default_commit_msg, extension, test, editorflags): """edit an article within your docs""" # set paths a = add_fileextension(article, extension) a = os.path.join(directory, a) d = os.path.dirname(a) # create dir(s) if not os.path.isdir(d): try: os.makedirs(d) except OSError: print("Error: Creation of path %s is not possible" % d) return False # start editor if test is False: try: if editorflags is False: subprocess.call([editor, a]) else: subprocess.call([editor, editorflags, a]) except OSError: print("Error: '%s' No such file or directory" % editor) return False else: try: with open(a, "a") as fp: content = "TEST CHANGE" fp.write(content) except OSError: print("Error: '%s' No such file or directory" % editor) # commit into git try: repo.git.add(a) if repo.is_dirty(): if test is False: try: msg = input("Commit message: ") if not msg: msg = default_commit_msg except OSError: print("Error: Could not create commit") else: msg = default_commit_msg print("automatic change done") try: repo.git.commit(m=msg) except OSError: print("Error: Could not create commit") else: print("Nothing to commit") except (OSError, git.exc.GitCommandError) as e: print("Error: Could not create commit") def info_article(article, dir, repo, extension): "get info for an article within your docs" a = add_fileextension(article, extension) a = os.path.join(dir, a) # Create commit list try: commits = repo.git.log(a, follow=True, format="%H") commits = commits.split() n = len(commits) except git.exc.GitCommandError: print("Error: File not found") return False # Article create date created = repo.git.show(commits[n-1], quiet=True, pretty="format:%ci") print("Created: %s" % created) # Article last updated updated = repo.git.show(commits[0], quiet=True, pretty="format:%ci") print("Updated: %s" % updated) # Number of commits print("Commits: %s" % n) # Collect textual informations num_lines = 0 num_words = 0 num_chars = 0 with open(a, 'r') as f: for line in f: words = line.split() num_lines += 1 num_words += len(words) num_chars += len(line) # Print textual informations print("Lines: %s" % num_lines) print("Words: %s" % num_words) print("Characters: %s" % num_chars) def mail_article(article, dir, mailfrom, extension): "mail an article to a friend" a = add_fileextension(article, extension) a = os.path.join(dir, a) # Create a text/plain message try: fp = open(a, 'r') msg = MIMEText(fp.read()) fp.close() except IOError: print("Error: Please specify a document") return False mailto = input("Recipient: ") msg['Subject'] = article msg['From'] = mailfrom msg['To'] = mailto # Send the message via our own SMTP server, but don't include the # envelope header. s = smtplib.SMTP() try: s.connect() s.sendmail(mailfrom, [mailto], msg.as_string()) s.quit() except socket.error: print("Error: Apparently no mailer running on your system.") print("Error: Could not connect to localhost:25") return False except smtplib.SMTPRecipientsRefused: print("Error: Invalid recipient or sender") return False def view_article(article, dir, pager, extension, pagerflags, colors): "view an article within your docs" a = add_fileextension(article, extension) a = os.path.join(dir, a) # read original file try: article = open(a, "r") except IOError: print("Error: Could not find %s" % article) return False content = article.read() article.close() # hand everything over to mistune lexer with tempfile.NamedTemporaryFile(delete=False, mode='w') as tmp: md = mistune.Markdown(renderer=md_to_ascii(colors)) tmp.write(md.render(content)) # start pager and cleanup tmp file afterwards # also parse flags for local pager try: if pagerflags is False: subprocess.call([pager, tmp.name]) else: subprocess.call([pager, pagerflags, tmp.name]) except OSError: print("Error: '%s' No such file or directory" % pager) try: os.remove(tmp.name) except OSError: print("Error: Could not remove %s" % tmp.name) def delete_article(article, dir, repo, extension): """ delete an article """ a = add_fileextension(article, extension) a = os.path.join(dir, a) try: repo.git.rm(a) repo.git.commit(m="%s deleted" % article) print("%s deleted" % article) except: if os.path.isdir(a): try: os.rmdir(a) print("Removed directory %s which was not under version control" % a) except OSError: print("Could not remove %s - its maybe not empty" % a) else: try: os.remove(a) print("Removed file %s which was not under version control" % a) except OSError: print("File %s could not be removed" % a) return def move_article(dir, args, repo, extension): "move an article from source to destination" args = args.split() if len(args) != 2: print("Invalid usage\nUse: mv source dest") return False a = os.path.join(dir, args[0]) a = add_fileextension(a, extension) e = os.path.join(dir, args[1]) e = add_fileextension(e, extension) d = os.path.dirname(e) # create dir(s) if not os.path.isdir(d): os.makedirs(d) # move file in git and commit try: repo.git.mv(a, e) repo.git.commit(m="Moved %s to %s" % (a, e)) print("Moved %s to %s" % (a, e)) except git.exc.GitCommandError: print("Error: File could not be moved") def search_article(keyword, directory, datadir, exclude): """ Search for a keyword in every article within your current directory and below. Much like recursive grep. """ c = 0 r = re.compile(keyword) print("Articles:") for dirpath, dirs, files in os.walk(directory): dirs[:] = [d for d in dirs if d not in exclude] for fname in files: path = os.path.join(dirpath, fname) if r.search(path) is not None: print("* \033[92m%s\033[39m" % os.path.relpath(path, datadir)) c = c + 1 print("Content:") for dirpath, dirs, files in os.walk(directory): dirs[:] = [d for d in dirs if d not in exclude] for fname in files: path = os.path.join(dirpath, fname) f = open(path, "rt") for i, line in enumerate(f): if r.search(line): c = c + 1 print("* \033[92m%s\033[39m: %s" % (os.path.relpath(path, datadir), line.rstrip('\n'))) return "Results: %s" % c def show_diff(args, repo, extension): """ Shows diffs for files or whole article directory """ colorization = "always" unifiedopt = "0" args = args.split() if len(args) > 1: if os.path.isfile(os.path.join(os.getcwd(), add_fileextension(args[1], extension))): # diff 7 article try: print(repo.git.diff('HEAD~'+args[0], add_fileextension(args[1], extension), unified=unifiedopt, color=colorization)) except git.exc.GitCommandError: print("Error: Not a valid git commit reference") else: print("Error: Wrong Usage. See help diff") elif len(args) == 1: # diff 7 try: print(repo.git.diff('HEAD~'+args[0], unified=unifiedopt, color=colorization)) except git.exc.GitCommandError: print("Error: Not a valid git commit reference") else: try: print(repo.git.diff('HEAD~1', unified="0", color="always")) except git.exc.GitCommandError: print("Error: Not a valid git commit reference") def show_log(args, repo, extension): """ Show latest git logs with specified number of entries and maybe for a specific file. """ args = args.split() format = "format:%C(blue)%h %Cgreen%C(bold)%ad %Creset%s" dateformat = "short" if len(args) >= 1: if os.path.isfile(os.path.join(os.getcwd(), add_fileextension(args[0], extension))): file = add_fileextension(args[0], extension) # Command: log Article 12 try: count = args[1] print("Last %s commits for %s" % (count, file)) print(repo.git.log(file, pretty=format, n=count, date=dateformat, follow=True)) # Command: log Article except IndexError: count = 10 print("Last %s commits for %s" % (count, file)) print(repo.git.log(file, pretty=format, n=count, date=dateformat, follow=True)) except git.exc.GitCommandError: print("Error: git command resulted in an error") else: count = args[0] # Command: log 12 Article try: file = add_fileextension(args[1], extension) print("Last %s commits for %s" % (count, file)) print(repo.git.log(file, pretty=format, n=count, date=dateformat, follow=True)) # Command: log 12 except IndexError: print("Last %s commits" % count) print(repo.git.log(pretty=format, n=count, date=dateformat)) except git.exc.GitCommandError: print("Error: git command resulted in an error") # Command: log elif len(args) == 0: count = 10 print("Last %s commits" % count) try: print(repo.git.log(pretty=format, n=count, date=dateformat)) except git.exc.GitCommandError: print("Error: git may not be configured on your system.") def undo_change(args, repo): """ You can revert your changes (use revert from git) """ args = args.split() if len(args) == 1: try: print(repo.git.show(args[0], '--oneline', '--patience')) msg = input("\nDo you really want to undo this? (y/n): ") if msg == "y": repo.git.revert(args[0], '--no-edit') except git.exc.GitCommandError: print("Error: Could not find given commit reference") def show_stats(args, repo, datadir): """ Show some statistics and other informations on your repos """ # get time series of commits commits = repo.git.log(format="%ci") commits = commits.split('\n') n = len(commits) print("Newest Commit: %s" % commits[0]) print("Oldest Commit: %s" % commits[n-1]) print("Number of Commits: %s" % n) # Calculate Repo age f = commits[n-1].split() today = datetime.datetime.today() first = datetime.datetime.strptime(f[0], "%Y-%m-%d") days = today - first print("Repository Age: %s" % days.days) # Calculate commits per day cpd = float(days.days) / n print("Average Commits per Day: %s" % cpd) # Calculate size of docs folder_size = 0 num_lines = 0 num_words = 0 num_chars = 0 num_files = 0 for (path, dirs, files) in os.walk(datadir): for file in files: filename = os.path.join(path, file) if ".git/" not in filename: num_files += 1 folder_size += os.path.getsize(filename) with open(filename, 'r') as f: for line in f: words = line.split() num_lines += 1 num_words += len(words) num_chars += len(line) print("Size of your Docs: %0.1f MB" % (folder_size/(1024*1024.0))) print("Total Articles: %s" % num_files) print("Total Lines: %s" % num_lines) print("Total Words: %s" % num_words) print("Total Characters: %s" % num_chars)
{ "repo_name": "noqqe/cmddocs", "path": "cmddocs/articles.py", "copies": "1", "size": "14598", "license": "mit", "hash": 7067981689918387000, "line_mean": 30.7347826087, "line_max": 101, "alpha_frac": 0.5571311139, "autogenerated": false, "ratio": 3.9199785177228788, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.49771096316228786, "avg_score": null, "num_lines": null }