def api_node_write_id(request): """Process write requests for the /api/nodes/{id} route.""" au = get_authenticated_user(request) try: node_id = request.matchdict['id'] payload = request.json_body s = '' for k,v in payload.items(): s+='{0}={1},'.format(k, v) log.info('Updating node_id: {0} params: {1}'.format(node_id, s.rstrip(','))) n = DBSession.query(Node) n = n.filter(Node.node_id==node_id) n = n.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 k,v in payload.items(): setattr(n ,k, v) n.updated_by=au['user_id'] DBSession.flush() except Exception as e: log.error('Error writing to nodes API={0},exception={1}'.format(request.url, e)) return Response(str(e), content_type='application/json', status_int=500) return n
def api_status_write(request): """Process write requests for /apistatusesnode_groups route.""" au = get_authenticated_user(request) try: payload = request.json_body status_name = payload['status_name'] description = payload['description'] log.debug('Searching for statuses status_name={0},description={1}'.format(status_name, description)) try: s = DBSession.query(Status.status_name==status_name) s = s.one() except NoResultFound: try: log.info('Creating new status status_name={0},description={1}'.format(status_name, description)) utcnow = datetime.utcnow() s = Status(status_name=status_name, description=description, updated_by=au['user_id'], created=utcnow, updated=utcnow) DBSession.add(s) DBSession.flush() except Exception, e: log.error('Error creating status status_name={0},description={1},exception={2}'.format(status_name, description, e)) raise else:
def view_operating_system(request): page_title = "Operating System" au = get_authenticated_user(request) uri = "/api/operating_systems/{0}".format(request.matchdict["id"]) operating_system = _api_get(request, uri) return {"page_title": page_title, "au": au, "operating_system": operating_system}
def view_status(request): page_title = 'Status' au = get_authenticated_user(request) uri = '/api/statuses/{0}'.format(request.matchdict['id']) status = _api_get(request, uri) return {'page_title': page_title, 'au': au, 'status': status, }
def api_node_groups_write(request): """Process write requests for /api/node_groups route.""" au = get_authenticated_user(request) try: payload = request.json_body node_group_name = payload['node_group_name'] node_group_owner = payload['node_group_owner'] node_group_description = payload['node_group_description'] log.debug('Searching for node_group node_group_name={0}'.format(node_group_name)) try: ng = DBSession.query(NodeGroup) ng = ng.filter(NodeGroup.node_group_name==node_group_name) ng = ng.one() except NoResultFound: try: log.info('Creating new node_group node_group_name={0},node_group_owner={1},description={2}'.format(node_group_name, node_group_owner, node_group_description)) utcnow = datetime.utcnow() ng = NodeGroup(node_group_name=node_group_name, node_group_owner=node_group_owner, description=node_group_description, updated_by=au['user_id'], created=utcnow, updated=utcnow) DBSession.add(ng) DBSession.flush() except Exception as e: log.error('Error creating new node_group node_group_name={0},node_group_owner={1},description={2},exception={3}'.format(node_group_name, node_group_owner, node_group_description, e)) raise else: try: log.info('Updating node_group node_group_name={0}'.format(node_group_name)) ng.node_group_name = node_group_name ng.node_group_owner = node_group_owner ng.description = node_group_description ng.updated_by=au['user_id'] DBSession.flush() except Exception as e: log.error('Error updating node_group node_group_name={0},node_group_owner={1},description={2},exception={3}'.format(node_group_name, node_group_owner, node_group_description, e)) raise return ng except Exception as e: log.error('Error writing to node_groups API={0},exception={1}'.format(request.url, e)) return Response(str(e), content_type='application/json', status_int=500)
def view_tag(request): page_title = 'Tag' au = get_authenticated_user(request) uri = '/api/tags/{0}'.format(request.matchdict['id']) tag = _api_get(request, uri) return {'page_title': page_title, 'au': au, 'tag': tag, }
def view_node(request): page_title = 'Node' au = get_authenticated_user(request) uri = '/api/nodes/{0}'.format(request.matchdict['id']) node = _api_get(request, uri) return {'page_title': page_title, 'au': au, 'node': node, }
def api_node_write(request): """Process write requests for the /api/nodes route.""" au = get_authenticated_user(request) try: payload = request.json_body # Manually created node via the client. try: node_name = payload['node_name'] unique_id = payload['unique_id'].lower() status_id = payload['node_status_id'] log.debug('Searching for node unique_id={0}'.format(unique_id)) n = DBSession.query(Node) n = n.filter(Node.unique_id==unique_id) n = n.one() except NoResultFound: try: log.info('Manually creating new node node_name={0},unique_id={1}'.format(node_name, unique_id)) utcnow = datetime.utcnow() n = Node(node_name=node_name, unique_id=unique_id, status_id=status_id, updated_by=au['user_id'], created=utcnow, updated=utcnow) DBSession.add(n) DBSession.flush() except Exception as e: log.error('Error creating new node node_name={0}unique_id={1},status_id={2},exception={3}'.format(node_name, unique_id, status_id, e)) raise else: try: log.info('Updating node node_name={0},unique_id={1}'.format(node_name, unique_id)) n.node_name = node_name n.status_id = status_id n.updated_by=au['user_id'] DBSession.flush() except Exception as e: log.error('Error updating node node_name={0},unique_id={1},exception={2}'.format(node_name, unique_id, e)) raise return n except Exception as e: log.error('Error writing to nodes API={0},exception={1}'.format(request.url, e)) return Response(str(e), content_type='application/json', status_int=500)
def api_ec2_object_write(request): """Process write requests for /api/ec2_objects route.""" au = get_authenticated_user(request) try: payload = request.json_body ec2_instance_id = payload['ec2_instance_id'] ec2_ami_id = payload['ec2_ami_id'] ec2_hostname = payload['ec2_hostname'] ec2_public_hostname = payload['ec2_public_hostname'] ec2_instance_type = payload['ec2_instance_type'] ec2_security_groups = payload['ec2_security_groups'] ec2_placement_availability_zone = payload['ec2_placement_availability_zone'] log.debug('Checking for ec2_object ec2_instance_id={0}'.format(ec2_instance_id)) try: ec2 = DBSession.query(Ec2) ec2 = ec2.filter(Ec2.ec2_instance_id==ec2_instance_id) ec2 = ec2.one() except NoResultFound: ec2 = create_ec2_object(ec2_instance_id, ec2_ami_id, ec2_hostname, ec2_public_hostname, ec2_instance_type, ec2_security_groups, ec2_placement_availability_zone, au['user_id']) else: try: log.info('Updating ec2_object ec2_instance_id={0}'.format(ec2_instance_id)) ec2.ec2_ami_id = ec2_ami_id ec2.ec2_hostname = ec2_hostname ec2.ec2_public_hostname = ec2_public_hostname ec2.ec2_instance_type = ec2_instance_type ec2.ec2_security_groups = ec2_security_groups ec2.ec2_placement_availability_zone = ec2_placement_availability_zone ec2.updated_by=au['user_id'] DBSession.flush() except Exception as e: log.error('Error updating ec2_object ec2_instance_id={0}'.format(ec2_instance_id, e)) raise return ec2 except Exception as e: log.error('Error writing to ec2_objects API={0},exception={1}'.format(request.url, e)) return Response(str(e), content_type='text/plain', status_int=500)
def view_hardware_profile(request): page_title_type = 'objects/' page_title_name = 'hardware_profile' au = get_authenticated_user(request) uri = '/api/hardware_profiles/{0}'.format(request.matchdict['id']) hardware_profile = _api_get(request, uri) return {'page_title_type': page_title_type, 'page_title_name': page_title_name, 'au': au, 'hardware_profile': hardware_profile, }
def view_home(request): au = get_authenticated_user(request) for key, value in request.POST.iteritems(): log.info("{0}: {1}".format(key, value)) url_base = "/{0}?".format(request.POST.get("object_type")) url_suffix = request.POST.get("search_terms") return_url = "{0}{1}".format(url_base, url_suffix) log.info("Search url is: {0}".format(return_url)) return HTTPFound(return_url)
def api_delete_by_params(request, model_type): """Process delete requests for /api/{object_type} route match. Iterates over passed parameters.""" # FIXME: Should we enforce required parameters here? # Will be used for auditing au = get_authenticated_user(request) # FIXME: Should we allow this to be set on the client, or hard code it to true, requiring an # exact match? Might make sense since there is no confirmation, it just deletes. exact_get = True c = camel_to_underscore(model_type) try: payload = request.json_body s = '' q = DBSession.query(globals()[model_type]) for k,v in payload.items(): # FIXME: This is sub-par. Need a better way to distinguish # meta params from search params without having to # pre-define everything. if k == 'exact_get': continue s+='{0}={1},'.format(k, v) if exact_get: log.debug('Exact filtering on {0}={1}'.format(k, v)) q = q.filter(getattr(globals()[model_type] ,k)==v) else: log.debug('Loose filtering on {0}={1}'.format(k, v)) q = q.filter(getattr(globals()[model_type] ,k).like('%{0}%'.format(v))) log.debug('Searching for {0} with params: {1}'.format(c, s.rstrip(','))) q = q.one() # FIXME: Need auditing log.info('Deleting {0} with params: {1}'.format(c, s.rstrip(','))) DBSession.delete(q) DBSession.flush() return True except NoResultFound: return Response(content_type='application/json', status_int=404) except Exception as e: log.error('Error deleting {0} with params: {1} exception: {2}'.format(c, s.rstrip(','), e)) return Response(str(e), content_type='application/json', status_int=500)
def api_hypervisor_vm_assignments_write(request): """Process write requests for the /api/hypervisor_vm_assignments route.""" au = get_authenticated_user(request) try: payload = request.json_body parent_node_id = payload['parent_node_id'] child_node_id = 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=au['user_id'], created=utcnow, updated=utcnow) DBSession.add(hva) DBSession.flush() except Exception as e: 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, e)) 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=au['user_id'] DBSession.flush() except Exception as e: log.error('Error updating hypervisor_vm_assignment parent_node_id={0},child_node_id={1},exception={2}'.format(parent_node_id, child_node_id, e)) raise except Exception as e: log.error('Error writing to hypervisor_vm_assignment API={0},exception={1}'.format(request.url, e)) return Response(str(e), content_type='application/json', status_int=500)
def view_test3(request): page_title = "test." au = get_authenticated_user(request) params = {"format": None, "type": "vir"} for p in params: try: params[p] = request.params[p] except: pass format = params["format"] type = params["type"] return {"layout": site_layout("max"), "page_title": page_title, "au": au}
def view_nodes(request): page_title_type = 'objects/' page_title_name = 'nodes' au = get_authenticated_user(request) (perpage, offset) = get_pag_params(request) payload = {} for k in request.GET: payload[k] = request.GET[k] uri = '/api/nodes' log.info('UI requesting data from API={0},payload={1}'.format(uri, payload)) if payload: r = _api_get(request, uri, payload) else: r = _api_get(request, uri) if r: total = r['meta']['total'] nodes = r['results'] else: total = 0 nodes = [] # Used by the columns menu to determine what to show/hide. column_selectors = [ {'name': 'node_id', 'pretty_name': 'Node ID' }, {'name': 'node_name', 'pretty_name': 'Node Name' }, {'name': 'unique_id', 'pretty_name': 'Unique Id' }, {'name': 'status', 'pretty_name': 'Status' }, {'name': 'node_groups', 'pretty_name': 'Node Groups' }, {'name': 'updated_by', 'pretty_name': 'Updated By' }, {'name': 'updated', 'pretty_name': 'Date Updated' }, {'name': 'created', 'pretty_name': 'Date Created' }, ] return {'layout': site_layout('max'), 'page_title_type': page_title_type, 'page_title_name': page_title_name, 'perpage': perpage, 'offset': offset, 'total': total, 'au': au, 'column_selectors': column_selectors, 'nodes': nodes, }
def view_test2(request): page_title_type = 'objects_' page_title_name = 'Statuses' au = get_authenticated_user(request) params = {'format': None, 'type': 'vir', } for p in params: try: params[p] = request.params[p] except: pass format = params['format'] type = params['type'] if format == 'json' or format == 'xml': return {'Hello':'world'} if type == 'ec2': host = 'aws1prdtcw1.opsprod.ctgrd.com' uniq_id = 'i-303a6c4a' ng = 'tcw' vhost = 'aws1' elif type == 'rds': host = 'aws1devcpd1.csqa.ctgrd.com' uniq_id = 'aws1devcpd1.cltftmkcg4dd.us-east-1.rds.amazonaws.com' ng = 'none' vhost = 'aws1' else: host = 'vir1prdpaw1.prod.cs' uniq_id = '6A:37:2A:68:E1:B0' ng = 'paw' vhost = 'vir1prdxen41.prod.cs' return {'layout': site_layout('max'), 'page_title_type': page_title_type, 'page_title_name': page_title_name, 'au': au, # 'results': results, 'type': type, 'host': host, 'uniq_id': uniq_id, 'ng': ng, 'vhost': vhost, }
def view_operating_systems(request): page_title_type = 'object/' page_title_name = 'operating_systems' au = get_authenticated_user(request) (perpage, offset) = get_pag_params(request) payload = {} for k in request.GET: payload[k] = request.GET[k] uri = '/api/operating_systems' log.info('UI requesting data from API={0},payload={1}'.format(uri, payload)) if payload: r = _api_get(request, uri, payload) else: r = _api_get(request, uri) if r: total = r['meta']['total'] operating_systems = r['results'] else: total = 0 operating_systems = [] # Used by the columns menu to determine what to show/hide. column_selectors = [ {'name': 'operating_system_id', 'pretty_name': 'Operating system ID' }, {'name': 'variant', 'pretty_name': 'Variant' }, {'name': 'version_number', 'pretty_name': 'Version Number' }, {'name': 'architecture', 'pretty_name': 'Architecture' }, {'name': 'description', 'pretty_name': 'Description' }, {'name': 'updated_by', 'pretty_name': 'Updated By' }, {'name': 'updated', 'pretty_name': 'Date Updated' }, {'name': 'created', 'pretty_name': 'Date Created' }, ] return {'layout': site_layout('max'), 'page_title_type': page_title_type, 'page_title_name': page_title_name, 'perpage': perpage, 'offset': offset, 'total': total, 'au': au, 'column_selectors': column_selectors, 'operating_systems': operating_systems, }
def view_hardware_profiles(request): page_title_type = 'objects/' page_title_name = 'hardware_profiles' au = get_authenticated_user(request) (perpage, offset) = get_pag_params(request) payload = {} for k in request.GET: payload[k] = request.GET[k] uri = '/api/hardware_profiles' log.info('UI requesting data from API={0},payload={1}'.format(uri, payload)) if payload: r = _api_get(request, uri, payload) else: r = _api_get(request, uri) if r: total = r['meta']['total'] hardware_profiles = r['results'] else: total = 0 hardware_profiles = [] # Used by the columns menu to determine what to show/hide. column_selectors = [ {'name': 'hardware_profile_id', 'pretty_name': 'Hardware Profile ID' }, {'name': 'manufacturer', 'pretty_name': 'Manufacturer' }, {'name': 'model', 'pretty_name': 'Model' }, {'name': 'updated_by', 'pretty_name': 'Updated By' }, {'name': 'updated', 'pretty_name': 'Date Updated' }, {'name': 'created', 'pretty_name': 'Date Created' }, ] return {'layout': site_layout('max'), 'page_title_type': page_title_type, 'page_title_name': page_title_name, 'perpage': perpage, 'offset': offset, 'total': total, 'au': au, 'column_selectors': column_selectors, 'hardware_profiles': hardware_profiles, }
def view_user(request): au = 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 != au['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))
def api_node_tags_write(request): """Process write requests for the /api/tags route.""" au = get_authenticated_user(request) try: payload = request.json_body tag_name = payload['tag_name'] tag_value = payload['tag_value'] log.info('Searching for tag tag_name={0}'.format(tag_name)) try: t = DBSession.query(Tag) t = t.filter(Tag.tag_name==tag_name) t = t.filter(Tag.tag_value==tag_value) t = t.one() except NoResultFound: try: log.info('Creating new tag tag_name={0},tag_value={1}'.format(tag_name, tag_value)) utcnow = datetime.utcnow() t = Tag(tag_name=tag_name, tag_value=tag_value, updated_by=au['user_id'], created=utcnow, updated=utcnow) DBSession.add(t) DBSession.flush() except Exception as e: log.error('Error creating new tag tag_name={0},tag_value={1},exception={2}'.format(tag_name, tag_value, e)) raise # 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. else: return Response(content_type='application/json', status_int=409) return t except Exception as e: log.error('Error writing to tags API={0},exception={1}'.format(request.url, e)) return Response(str(e), content_type='application/json', status_int=500)
def api_operating_system_write(request): """Process write requests for /api/operating_systems route.""" au = get_authenticated_user(request) try: payload = request.json_body variant = payload['variant'] version_number = payload['version_number'] architecture = payload['architecture'] description = payload['description'] log.info('Checking for operating_system variant={0},version_number={1},architecture={2}'.format(variant, version_number, architecture)) try: os = DBSession.query(OperatingSystem) os = os.filter(OperatingSystem.variant==variant) os = os.filter(OperatingSystem.version_number==version_number) os = os.filter(OperatingSystem.architecture==architecture) os = os.one() except NoResultFound: os = create_operating_system(variant, version_number, architecture, description, au['user_id']) else: try: log.info('Updating operating_system variant={0},version_number={1},architecture={2},description={3}'.format(variant, version_number, architecture, description)) os.variant = variant os.version_number = version_number os.architecture = architecture os.description = description os.updated_by=au['user_id'] DBSession.flush() except Exception as e: log.error('Error updating operating_system variant={0},version_number={1},architecture={2},description={3},exception={4}'.format(variant, version_number, architecture, description, e)) raise return os except Exception as e: log.error('Error writing to operating_systems API={0},exception={1}'.format(request.url, e)) return Response(str(e), content_type='text/plain', status_int=500)
def view_home(request): page_title_type = '_' page_title_name = 'Home' au = get_authenticated_user(request) # Used by the columns menu to determine what to show/hide. column_selectors = [ {'name': 'status_id', 'pretty_name': 'Status ID' }, {'name': 'status_name', 'pretty_name': 'Status Name' }, {'name': 'description', 'pretty_name': 'Description' }, {'name': 'updated_by', 'pretty_name': 'Updated By' }, {'name': 'updated', 'pretty_name': 'Date Update' }, {'name': 'created', 'pretty_name': 'Date Created' }, ] return {'layout': site_layout('max'), 'page_title_type': page_title_type, 'page_title_name': page_title_name, 'au': au, 'column_selectors': column_selectors, }
def api_node_group_assignments_write(request): """Process write requests for the /api/node_group_assignments route.""" au = get_authenticated_user(request) try: payload = request.json_body node_id = payload['node_id'] node_group_id = payload['node_group_id'] log.debug('Checking for node_group_assignment node_id={0},node_group_id={1}'.format(node_id, node_group_id)) try: nga = DBSession.query(NodeGroupAssignment) nga = nga.filter(NodeGroupAssignment.node_id==node_id) nga = nga.filter(NodeGroupAssignment.node_group_id==node_group_id) nga = nga.one() log.info('node_group_assignment already exists') return Response(content_type='application/json', status_int=409) except NoResultFound: try: log.debug('Creating new node_group_assignment for node_id={0},node_group_id={1}'.format(node_id, node_group_id)) utcnow = datetime.utcnow() nga = NodeGroupAssignment(node_id=node_id, node_group_id=node_group_id, updated_by=au['user_id'], created=utcnow, updated=utcnow) DBSession.add(nga) DBSession.flush() except Exception as e: log.error('Error creating new node_group_assignment node_id={0},node_group_id={1},exception={2}'.format(node_id, node_group_id, e)) raise except Exception as e: log.error('Error writing to node_group_assignment API={0},exception={1}'.format(request.url, e)) return Response(str(e), content_type='application/json', status_int=500)
def view_test(request): page_title = 'Test' au = get_authenticated_user(request) results = False params = {'type': 'vir', } for p in params: try: params[p] = request.params[p] except: pass type = params['type'] if type == 'ec2': host = 'aws1prdtcw1.opsprod.ctgrd.com' uniq_id = 'i-303a6c4a' ng = 'tcw' vhost = 'aws1' elif type == 'rds': host = 'aws1devcpd1.csqa.ctgrd.com' uniq_id = 'aws1devcpd1.cltftmkcg4dd.us-east-1.rds.amazonaws.com' ng = 'none' vhost = 'aws1' else: host = 'vir1prdpaw1.prod.cs' uniq_id = '6A:37:2A:68:E1:B0' ng = 'paw' vhost = 'vir1prdxen41.prod.cs' return {'layout': site_layout('max'), 'page_title': page_title, 'au': au, 'results': results, 'type': type, 'host': host, 'uniq_id': uniq_id, 'ng': ng, 'vhost': vhost, }
def api_tag_node_assignments_write(request): """Process write requests for the /api/tag_node_assignments route.""" au = get_authenticated_user(request) try: payload = request.json_body tag_id = payload['tag_id'] node_id = payload['node_id'] log.debug('Searching for tag_node_assignment tag_id={0}node_id={1}'.format(tag_id, node_id)) try: tna = DBSession.query(TagNodeAssignment) tna = tna.filter(TagNodeAssignment.tag_id==tag_id) tna = tna.filter(TagNodeAssignment.node_id==node_id) tna = tna.one() log.info('tag_node_assignment already exists') return Response(content_type='application/json', status_int=409) except NoResultFound: try: log.info('Creating new tag_node_assignment tag_id={0},node_id={1}'.format(tag_id, node_id)) utcnow = datetime.utcnow() ta = TagNodeAssignment(tag_id=tag_id, node_id=node_id, updated_by=au['user_id'], created=utcnow, updated=utcnow) DBSession.add(ta) DBSession.flush() except Exception as e: log.error('Error creating new tag_node_assignment tag_id={0},node_id={1},exception={2}'.format(tag_id, node_id, e)) raise except Exception as e: log.error('Error writing to tag_node_assignments API={0},exception={1}'.format(request.url, e)) return Response(str(e), content_type='application/json', status_int=500)
def api_hardware_profile_write(request): """Process write requests for /api/hardware_profiles route.""" au = get_authenticated_user(request) try: payload = request.json_body manufacturer = payload['manufacturer'] model = payload['model'] log.debug('Checking for hardware_profile manufacturer={0},model={1}'.format(manufacturer, model)) try: hp = DBSession.query(HardwareProfile) hp = hp.filter(HardwareProfile.manufacturer==manufacturer) hp = hp.filter(HardwareProfile.model==model) hp = hp.one() except NoResultFound: hp = create_hardware_profile(manufacturer, model, au['user_id']) else: try: log.info('Updating hardware_profile manufacturer={0},model={1}'.format(manufacturer, model)) hp.manufacturer = manufacturer hp.model = model hp.updated_by=au['user_id'] DBSession.flush() except Exception as e: log.error('Error updating hardware_profile manufacturer={0},model={1},exception={2}'.format(manufacturer, model, e)) raise return hp except Exception as e: log.error('Error writing to harware_profiles API={0},exception={1}'.format(request.url, e)) return Response(str(e), content_type='text/plain', status_int=500)
def api_delete_by_id(request, model_type): """Process delete requests for /api/{object_type}/{id} route match.""" # FIXME: Will be used for auditing eventually. Would be nice to use # request.authenticated_userid, but I think this gets ugly when it's # an AD user. Need to test. au = get_authenticated_user(request) resource_id = request.matchdict['id'] c = camel_to_underscore(model_type) c_id = c + '_id' c_name = c + '_name' try: log.debug('Checking for {0}={1}'.format(c_id, resource_id)) # FIXME: Something better here than globals? q = DBSession.query(globals()[model_type]) q = q.filter(getattr(globals()[model_type], c_id) == resource_id) q = q.one() object_name = getattr(q, c_name) # FIXME: Need auditing # FIXME: What about orphaned assigments? Should we clean them up? log.info('Deleting {0}={1},{2}={3}'.format(c_name, object_name, c_id, resource_id)) DBSession.delete(q) DBSession.flush() return True except NoResultFound: return Response(content_type='application/json', status_int=404) except Exception as e: log.error('Error deleting {0}={1},exception={2}'.format(c_id, resource_id, e)) return Response(str(e), content_type='application/json', status_int=500)
def login(request): page_title = 'Login' au = 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. Need a second condition to check for authenticated user if request.path_info.split('/')[1][:3] == 'api': logging.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 = '/' login = '' password = '' error = '' if 'form.submitted' in request.POST: login = request.POST['login'] password = request.POST['password'] # Try local first, ldap second data = local_authenticate(login, password) if data is None: connector = get_ldap_connector(request) data = connector.authenticate(login, password) if data is not None: dn = data[0] encrypted = signed_serialize(login, request.registry.settings['arsenal.cookie_token']) headers = remember(request, dn) 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' if 'api.client' in request.POST: return HTTPForbidden() 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' if 'api.client' in request.POST: return HTTPForbidden() return {'layout': site_layout('max'), 'page_title': page_title, 'au': au, 'return_url': return_url, 'login': login, 'password': password, 'error': error, }
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 au = get_authenticated_user(request) subtitle = au['first_last'] column_selectors = [] return {'layout': site_layout('max'), 'page_title_name': page_title_name, 'page_title_type': page_title_type, 'au': au, 'perpage': perpage, 'offset': offset, 'total': total, 'column_selectors': column_selectors, 'subtitle': subtitle, 'change_pw': change_pw, }
def api_node_register(request): """Process registration requests for the /api/register route.""" au = get_authenticated_user(request) log.info('Registering new node') try: payload = request.json_body # Get the hardware_profile_id or create if it doesn't exist. try: manufacturer = payload['hardware_profile']['manufacturer'] model = payload['hardware_profile']['model'] # FIXME: remove the http call uri = '/api/hardware_profiles' data = {'manufacturer': manufacturer, 'model': model } hardware_profile = _api_get(request, uri, data) try: hardware_profile_id = hardware_profile['results'][0]['hardware_profile_id'] except IndexError: log.debug('hardware_profile not found, creating') hardware_profile = create_hardware_profile(manufacturer, model, au['user_id']) hardware_profile_id = hardware_profile.hardware_profile_id log.debug('hardware_profile is: {0}'.format(hardware_profile)) except Exception as e: log.error('Unable to determine hardware_profile manufacturer={0},model={1},exception={2}'.format(manufacturer, model, e)) raise # Get the operating_system_id or create if it doesn't exist. try: variant = payload['operating_system']['variant'] version_number = payload['operating_system']['version_number'] architecture = payload['operating_system']['architecture'] description = payload['operating_system']['description'] # FIXME: remove the http call uri = '/api/operating_systems' data = {'variant': variant, 'version_number': version_number, 'architecture': architecture, 'description': description } operating_system = _api_get(request, uri, data) try: operating_system_id = operating_system['results'][0]['operating_system_id'] except IndexError: log.debug('operating_system not found, attempting to create') operating_system = create_operating_system(variant, version_number, architecture, description, au['user_id']) operating_system_id = operating_system.operating_system_id log.debug('operating_system is: {0}'.format(operating_system)) except Exception as e: log.error('Unable to determine operating_system variant={0},version_number={1},architecture={2},description={3},exception={4}'.format(variant, version_number, architecture, description, e)) raise # if sent, Get the ec2_object or create if it doesn't exist. ec2_id = None if payload['ec2']: try: ec2_instance_id = payload['ec2']['ec2_instance_id'] ec2_ami_id = payload['ec2']['ec2_ami_id'] ec2_hostname = payload['ec2']['ec2_hostname'] ec2_public_hostname = payload['ec2']['ec2_public_hostname'] ec2_instance_type = payload['ec2']['ec2_instance_type'] ec2_security_groups = payload['ec2']['ec2_security_groups'] ec2_placement_availability_zone = payload['ec2']['ec2_placement_availability_zone'] # FIXME: remove the http call uri = '/api/ec2_objects' data = {'ec2_instance_id': ec2_instance_id, 'exact_get': True, } ec2 = _api_get(request, uri, data) try: ec2_id = ec2['results'][0]['ec2_id'] except IndexError: log.debug('ec2_object not found, attempting to create') ec2 = create_ec2_object(ec2_instance_id, ec2_ami_id, ec2_hostname, ec2_public_hostname, ec2_instance_type, ec2_security_groups, ec2_placement_availability_zone, au['user_id']) ec2_id = ec2.ec2_id log.debug('ec2_object is: {0}'.format(ec2)) except Exception as e: log.error('Unable to determine ec2_object ec2_instance_id={0},exception={1}'.format(payload['ec2']['ec2_instance_id'], e)) raise try: unique_id = payload['unique_id'].lower() node_name = payload['node_name'] uptime = payload['uptime'] log.debug('Searching for node unique_id={0}'.format(unique_id)) n = DBSession.query(Node) n = n.filter(Node.unique_id==unique_id) n = n.one() except NoResultFound: try: log.info('Creating new node node_name={0},unique_id={1}'.format(node_name, unique_id)) utcnow = datetime.utcnow() n = Node(unique_id=unique_id, node_name=node_name, hardware_profile_id=hardware_profile_id, operating_system_id=operating_system_id, uptime=uptime, status_id=2, ec2_id=ec2_id, updated_by=au['user_id'], created=utcnow, updated=utcnow) DBSession.add(n) DBSession.flush() except Exception as e: log.error('Error creating new node node_name={0},unique_id={1},exception={2}'.format(node_name, unique_id, e)) raise else: try: log.info('Updating node: {0}'.format(unique_id)) n.node_name = node_name n.hardware_profile_id = hardware_profile_id n.operating_system_id = operating_system_id n.ec2_id = ec2_id n.uptime = uptime n.updated_by=au['user_id'] DBSession.flush() except Exception as e: log.error('Error updating node node_name={0},unique_id={1},exception={2}'.format(node_name, unique_id, e)) raise return n except Exception as e: log.error('Error registering new node API={0},exception={1}'.format(request.url, e)) return Response(str(e), content_type='application/json', status_int=500)