prompt
large_stringlengths
72
9.34k
completion
large_stringlengths
0
7.61k
<|file_name|>handler.py<|end_file_name|><|fim▁begin|># Copyright 2010 United States Government as represented by the # Administrator of the National Aeronautics and Space Administration. # All Rights Reserved. # # 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. """Metadata request handler.""" import hashlib import hmac import os from oslo_config import cfg from oslo_log import log as logging import six import webob.dec import webob.exc from nova.api.metadata import base from nova import conductor from nova import exception from nova.i18n import _ from nova.i18n import _LE from nova.i18n import _LW from nova.openstack.common import memorycache from nova import utils from nova import wsgi CACHE_EXPIRATION = 15 # in seconds CONF = cfg.CONF CONF.import_opt('use_forwarded_for', 'nova.api.auth') metadata_proxy_opts = [ cfg.BoolOpt( 'service_metadata_proxy', default=False, help='Set flag to indicate Neutron will proxy metadata requests and ' 'resolve instance ids.'), cfg.StrOpt( 'metadata_proxy_shared_secret', default='', secret=True, help='Shared secret to validate proxies Neutron metadata requests'), ] CONF.register_opts(metadata_proxy_opts, 'neutron') LOG = logging.getLogger(__name__) class MetadataRequestHandler(wsgi.Application): """Serve metadata.""" def __init__(self): self._cache = memorycache.get_client() self.conductor_api = conductor.API() def get_metadata_by_remote_address(self, address): if not address: raise exception.FixedIpNotFoundForAddress(address=address) cache_key = 'metadata-%s' % address data = self._cache.get(cache_key) if data: return data try: data = base.get_metadata_by_address(self.conductor_api, address) except exception.NotFound: return None self._cache.set(cache_key, data, CACHE_EXPIRATION) return data def get_metadata_by_instance_id(self, instance_id, address): cache_key = 'metadata-%s' % instance_id data = self._cache.get(cache_key) if data: return data try: data = base.get_metadata_by_instance_id(self.conductor_api, instance_id, address) except exception.NotFound: return None self._cache.set(cache_key, data, CACHE_EXPIRATION) return data @webob.dec.wsgify(RequestClass=wsgi.Request) def __call__(self, req): if os.path.normpath(req.path_info) == "/": resp = base.ec2_md_print(base.VERSIONS + ["latest"]) req.response.body = resp req.response.content_type = base.MIME_TYPE_TEXT_PLAIN return req.response if CONF.neutron.service_metadata_proxy: meta_data = self._handle_instance_id_request(req) else: if req.headers.get('X-Instance-ID'): LOG.warning( _LW("X-Instance-ID present in request headers. The " "'service_metadata_proxy' option must be " "enabled to process this header.")) meta_data = self._handle_remote_ip_request(req) if meta_data is None: raise webob.exc.HTTPNotFound() try: data = meta_data.lookup(req.path_info) except base.InvalidMetadataPath: raise webob.exc.HTTPNotFound() if callable(data): return data(req, meta_data) resp = base.ec2_md_print(data) if isinstance(resp, six.text_type): req.response.text = resp else: req.response.body = resp req.response.content_type = meta_data.get_mimetype() return req.response def _handle_remote_ip_request(self, req): remote_address = req.remote_addr if CONF.use_forwarded_for: remote_address = req.headers.get('X-Forwarded-For', remote_address) try: meta_data = self.get_metadata_by_remote_address(remote_address) except Exception: LOG.exception(_LE('Failed to get metadata for ip: %s'), remote_address) msg = _('An unknown error has occurred. ' 'Please try your request again.') raise webob.exc.HTTPInternalServerError( explanation=six.text_type(msg)) if meta_data is None: LOG.error(_LE('Failed to get metadata for ip: %s'), remote_address) return meta_data def _handle_instance_id_request(self, req): <|fim_middle|> <|fim▁end|>
instance_id = req.headers.get('X-Instance-ID') tenant_id = req.headers.get('X-Tenant-ID') signature = req.headers.get('X-Instance-ID-Signature') remote_address = req.headers.get('X-Forwarded-For') # Ensure that only one header was passed if instance_id is None: msg = _('X-Instance-ID header is missing from request.') elif signature is None: msg = _('X-Instance-ID-Signature header is missing from request.') elif tenant_id is None: msg = _('X-Tenant-ID header is missing from request.') elif not isinstance(instance_id, six.string_types): msg = _('Multiple X-Instance-ID headers found within request.') elif not isinstance(tenant_id, six.string_types): msg = _('Multiple X-Tenant-ID headers found within request.') else: msg = None if msg: raise webob.exc.HTTPBadRequest(explanation=msg) expected_signature = hmac.new( CONF.neutron.metadata_proxy_shared_secret, instance_id, hashlib.sha256).hexdigest() if not utils.constant_time_compare(expected_signature, signature): if instance_id: LOG.warning(_LW('X-Instance-ID-Signature: %(signature)s does ' 'not match the expected value: ' '%(expected_signature)s for id: ' '%(instance_id)s. Request From: ' '%(remote_address)s'), {'signature': signature, 'expected_signature': expected_signature, 'instance_id': instance_id, 'remote_address': remote_address}) msg = _('Invalid proxy request signature.') raise webob.exc.HTTPForbidden(explanation=msg) try: meta_data = self.get_metadata_by_instance_id(instance_id, remote_address) except Exception: LOG.exception(_LE('Failed to get metadata for instance id: %s'), instance_id) msg = _('An unknown error has occurred. ' 'Please try your request again.') raise webob.exc.HTTPInternalServerError( explanation=six.text_type(msg)) if meta_data is None: LOG.error(_LE('Failed to get metadata for instance id: %s'), instance_id) elif meta_data.instance.project_id != tenant_id: LOG.warning(_LW("Tenant_id %(tenant_id)s does not match tenant_id " "of instance %(instance_id)s."), {'tenant_id': tenant_id, 'instance_id': instance_id}) # causes a 404 to be raised meta_data = None return meta_data
<|file_name|>handler.py<|end_file_name|><|fim▁begin|># Copyright 2010 United States Government as represented by the # Administrator of the National Aeronautics and Space Administration. # All Rights Reserved. # # 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. """Metadata request handler.""" import hashlib import hmac import os from oslo_config import cfg from oslo_log import log as logging import six import webob.dec import webob.exc from nova.api.metadata import base from nova import conductor from nova import exception from nova.i18n import _ from nova.i18n import _LE from nova.i18n import _LW from nova.openstack.common import memorycache from nova import utils from nova import wsgi CACHE_EXPIRATION = 15 # in seconds CONF = cfg.CONF CONF.import_opt('use_forwarded_for', 'nova.api.auth') metadata_proxy_opts = [ cfg.BoolOpt( 'service_metadata_proxy', default=False, help='Set flag to indicate Neutron will proxy metadata requests and ' 'resolve instance ids.'), cfg.StrOpt( 'metadata_proxy_shared_secret', default='', secret=True, help='Shared secret to validate proxies Neutron metadata requests'), ] CONF.register_opts(metadata_proxy_opts, 'neutron') LOG = logging.getLogger(__name__) class MetadataRequestHandler(wsgi.Application): """Serve metadata.""" def __init__(self): self._cache = memorycache.get_client() self.conductor_api = conductor.API() def get_metadata_by_remote_address(self, address): if not address: <|fim_middle|> cache_key = 'metadata-%s' % address data = self._cache.get(cache_key) if data: return data try: data = base.get_metadata_by_address(self.conductor_api, address) except exception.NotFound: return None self._cache.set(cache_key, data, CACHE_EXPIRATION) return data def get_metadata_by_instance_id(self, instance_id, address): cache_key = 'metadata-%s' % instance_id data = self._cache.get(cache_key) if data: return data try: data = base.get_metadata_by_instance_id(self.conductor_api, instance_id, address) except exception.NotFound: return None self._cache.set(cache_key, data, CACHE_EXPIRATION) return data @webob.dec.wsgify(RequestClass=wsgi.Request) def __call__(self, req): if os.path.normpath(req.path_info) == "/": resp = base.ec2_md_print(base.VERSIONS + ["latest"]) req.response.body = resp req.response.content_type = base.MIME_TYPE_TEXT_PLAIN return req.response if CONF.neutron.service_metadata_proxy: meta_data = self._handle_instance_id_request(req) else: if req.headers.get('X-Instance-ID'): LOG.warning( _LW("X-Instance-ID present in request headers. The " "'service_metadata_proxy' option must be " "enabled to process this header.")) meta_data = self._handle_remote_ip_request(req) if meta_data is None: raise webob.exc.HTTPNotFound() try: data = meta_data.lookup(req.path_info) except base.InvalidMetadataPath: raise webob.exc.HTTPNotFound() if callable(data): return data(req, meta_data) resp = base.ec2_md_print(data) if isinstance(resp, six.text_type): req.response.text = resp else: req.response.body = resp req.response.content_type = meta_data.get_mimetype() return req.response def _handle_remote_ip_request(self, req): remote_address = req.remote_addr if CONF.use_forwarded_for: remote_address = req.headers.get('X-Forwarded-For', remote_address) try: meta_data = self.get_metadata_by_remote_address(remote_address) except Exception: LOG.exception(_LE('Failed to get metadata for ip: %s'), remote_address) msg = _('An unknown error has occurred. ' 'Please try your request again.') raise webob.exc.HTTPInternalServerError( explanation=six.text_type(msg)) if meta_data is None: LOG.error(_LE('Failed to get metadata for ip: %s'), remote_address) return meta_data def _handle_instance_id_request(self, req): instance_id = req.headers.get('X-Instance-ID') tenant_id = req.headers.get('X-Tenant-ID') signature = req.headers.get('X-Instance-ID-Signature') remote_address = req.headers.get('X-Forwarded-For') # Ensure that only one header was passed if instance_id is None: msg = _('X-Instance-ID header is missing from request.') elif signature is None: msg = _('X-Instance-ID-Signature header is missing from request.') elif tenant_id is None: msg = _('X-Tenant-ID header is missing from request.') elif not isinstance(instance_id, six.string_types): msg = _('Multiple X-Instance-ID headers found within request.') elif not isinstance(tenant_id, six.string_types): msg = _('Multiple X-Tenant-ID headers found within request.') else: msg = None if msg: raise webob.exc.HTTPBadRequest(explanation=msg) expected_signature = hmac.new( CONF.neutron.metadata_proxy_shared_secret, instance_id, hashlib.sha256).hexdigest() if not utils.constant_time_compare(expected_signature, signature): if instance_id: LOG.warning(_LW('X-Instance-ID-Signature: %(signature)s does ' 'not match the expected value: ' '%(expected_signature)s for id: ' '%(instance_id)s. Request From: ' '%(remote_address)s'), {'signature': signature, 'expected_signature': expected_signature, 'instance_id': instance_id, 'remote_address': remote_address}) msg = _('Invalid proxy request signature.') raise webob.exc.HTTPForbidden(explanation=msg) try: meta_data = self.get_metadata_by_instance_id(instance_id, remote_address) except Exception: LOG.exception(_LE('Failed to get metadata for instance id: %s'), instance_id) msg = _('An unknown error has occurred. ' 'Please try your request again.') raise webob.exc.HTTPInternalServerError( explanation=six.text_type(msg)) if meta_data is None: LOG.error(_LE('Failed to get metadata for instance id: %s'), instance_id) elif meta_data.instance.project_id != tenant_id: LOG.warning(_LW("Tenant_id %(tenant_id)s does not match tenant_id " "of instance %(instance_id)s."), {'tenant_id': tenant_id, 'instance_id': instance_id}) # causes a 404 to be raised meta_data = None return meta_data <|fim▁end|>
raise exception.FixedIpNotFoundForAddress(address=address)
<|file_name|>handler.py<|end_file_name|><|fim▁begin|># Copyright 2010 United States Government as represented by the # Administrator of the National Aeronautics and Space Administration. # All Rights Reserved. # # 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. """Metadata request handler.""" import hashlib import hmac import os from oslo_config import cfg from oslo_log import log as logging import six import webob.dec import webob.exc from nova.api.metadata import base from nova import conductor from nova import exception from nova.i18n import _ from nova.i18n import _LE from nova.i18n import _LW from nova.openstack.common import memorycache from nova import utils from nova import wsgi CACHE_EXPIRATION = 15 # in seconds CONF = cfg.CONF CONF.import_opt('use_forwarded_for', 'nova.api.auth') metadata_proxy_opts = [ cfg.BoolOpt( 'service_metadata_proxy', default=False, help='Set flag to indicate Neutron will proxy metadata requests and ' 'resolve instance ids.'), cfg.StrOpt( 'metadata_proxy_shared_secret', default='', secret=True, help='Shared secret to validate proxies Neutron metadata requests'), ] CONF.register_opts(metadata_proxy_opts, 'neutron') LOG = logging.getLogger(__name__) class MetadataRequestHandler(wsgi.Application): """Serve metadata.""" def __init__(self): self._cache = memorycache.get_client() self.conductor_api = conductor.API() def get_metadata_by_remote_address(self, address): if not address: raise exception.FixedIpNotFoundForAddress(address=address) cache_key = 'metadata-%s' % address data = self._cache.get(cache_key) if data: <|fim_middle|> try: data = base.get_metadata_by_address(self.conductor_api, address) except exception.NotFound: return None self._cache.set(cache_key, data, CACHE_EXPIRATION) return data def get_metadata_by_instance_id(self, instance_id, address): cache_key = 'metadata-%s' % instance_id data = self._cache.get(cache_key) if data: return data try: data = base.get_metadata_by_instance_id(self.conductor_api, instance_id, address) except exception.NotFound: return None self._cache.set(cache_key, data, CACHE_EXPIRATION) return data @webob.dec.wsgify(RequestClass=wsgi.Request) def __call__(self, req): if os.path.normpath(req.path_info) == "/": resp = base.ec2_md_print(base.VERSIONS + ["latest"]) req.response.body = resp req.response.content_type = base.MIME_TYPE_TEXT_PLAIN return req.response if CONF.neutron.service_metadata_proxy: meta_data = self._handle_instance_id_request(req) else: if req.headers.get('X-Instance-ID'): LOG.warning( _LW("X-Instance-ID present in request headers. The " "'service_metadata_proxy' option must be " "enabled to process this header.")) meta_data = self._handle_remote_ip_request(req) if meta_data is None: raise webob.exc.HTTPNotFound() try: data = meta_data.lookup(req.path_info) except base.InvalidMetadataPath: raise webob.exc.HTTPNotFound() if callable(data): return data(req, meta_data) resp = base.ec2_md_print(data) if isinstance(resp, six.text_type): req.response.text = resp else: req.response.body = resp req.response.content_type = meta_data.get_mimetype() return req.response def _handle_remote_ip_request(self, req): remote_address = req.remote_addr if CONF.use_forwarded_for: remote_address = req.headers.get('X-Forwarded-For', remote_address) try: meta_data = self.get_metadata_by_remote_address(remote_address) except Exception: LOG.exception(_LE('Failed to get metadata for ip: %s'), remote_address) msg = _('An unknown error has occurred. ' 'Please try your request again.') raise webob.exc.HTTPInternalServerError( explanation=six.text_type(msg)) if meta_data is None: LOG.error(_LE('Failed to get metadata for ip: %s'), remote_address) return meta_data def _handle_instance_id_request(self, req): instance_id = req.headers.get('X-Instance-ID') tenant_id = req.headers.get('X-Tenant-ID') signature = req.headers.get('X-Instance-ID-Signature') remote_address = req.headers.get('X-Forwarded-For') # Ensure that only one header was passed if instance_id is None: msg = _('X-Instance-ID header is missing from request.') elif signature is None: msg = _('X-Instance-ID-Signature header is missing from request.') elif tenant_id is None: msg = _('X-Tenant-ID header is missing from request.') elif not isinstance(instance_id, six.string_types): msg = _('Multiple X-Instance-ID headers found within request.') elif not isinstance(tenant_id, six.string_types): msg = _('Multiple X-Tenant-ID headers found within request.') else: msg = None if msg: raise webob.exc.HTTPBadRequest(explanation=msg) expected_signature = hmac.new( CONF.neutron.metadata_proxy_shared_secret, instance_id, hashlib.sha256).hexdigest() if not utils.constant_time_compare(expected_signature, signature): if instance_id: LOG.warning(_LW('X-Instance-ID-Signature: %(signature)s does ' 'not match the expected value: ' '%(expected_signature)s for id: ' '%(instance_id)s. Request From: ' '%(remote_address)s'), {'signature': signature, 'expected_signature': expected_signature, 'instance_id': instance_id, 'remote_address': remote_address}) msg = _('Invalid proxy request signature.') raise webob.exc.HTTPForbidden(explanation=msg) try: meta_data = self.get_metadata_by_instance_id(instance_id, remote_address) except Exception: LOG.exception(_LE('Failed to get metadata for instance id: %s'), instance_id) msg = _('An unknown error has occurred. ' 'Please try your request again.') raise webob.exc.HTTPInternalServerError( explanation=six.text_type(msg)) if meta_data is None: LOG.error(_LE('Failed to get metadata for instance id: %s'), instance_id) elif meta_data.instance.project_id != tenant_id: LOG.warning(_LW("Tenant_id %(tenant_id)s does not match tenant_id " "of instance %(instance_id)s."), {'tenant_id': tenant_id, 'instance_id': instance_id}) # causes a 404 to be raised meta_data = None return meta_data <|fim▁end|>
return data
<|file_name|>handler.py<|end_file_name|><|fim▁begin|># Copyright 2010 United States Government as represented by the # Administrator of the National Aeronautics and Space Administration. # All Rights Reserved. # # 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. """Metadata request handler.""" import hashlib import hmac import os from oslo_config import cfg from oslo_log import log as logging import six import webob.dec import webob.exc from nova.api.metadata import base from nova import conductor from nova import exception from nova.i18n import _ from nova.i18n import _LE from nova.i18n import _LW from nova.openstack.common import memorycache from nova import utils from nova import wsgi CACHE_EXPIRATION = 15 # in seconds CONF = cfg.CONF CONF.import_opt('use_forwarded_for', 'nova.api.auth') metadata_proxy_opts = [ cfg.BoolOpt( 'service_metadata_proxy', default=False, help='Set flag to indicate Neutron will proxy metadata requests and ' 'resolve instance ids.'), cfg.StrOpt( 'metadata_proxy_shared_secret', default='', secret=True, help='Shared secret to validate proxies Neutron metadata requests'), ] CONF.register_opts(metadata_proxy_opts, 'neutron') LOG = logging.getLogger(__name__) class MetadataRequestHandler(wsgi.Application): """Serve metadata.""" def __init__(self): self._cache = memorycache.get_client() self.conductor_api = conductor.API() def get_metadata_by_remote_address(self, address): if not address: raise exception.FixedIpNotFoundForAddress(address=address) cache_key = 'metadata-%s' % address data = self._cache.get(cache_key) if data: return data try: data = base.get_metadata_by_address(self.conductor_api, address) except exception.NotFound: return None self._cache.set(cache_key, data, CACHE_EXPIRATION) return data def get_metadata_by_instance_id(self, instance_id, address): cache_key = 'metadata-%s' % instance_id data = self._cache.get(cache_key) if data: <|fim_middle|> try: data = base.get_metadata_by_instance_id(self.conductor_api, instance_id, address) except exception.NotFound: return None self._cache.set(cache_key, data, CACHE_EXPIRATION) return data @webob.dec.wsgify(RequestClass=wsgi.Request) def __call__(self, req): if os.path.normpath(req.path_info) == "/": resp = base.ec2_md_print(base.VERSIONS + ["latest"]) req.response.body = resp req.response.content_type = base.MIME_TYPE_TEXT_PLAIN return req.response if CONF.neutron.service_metadata_proxy: meta_data = self._handle_instance_id_request(req) else: if req.headers.get('X-Instance-ID'): LOG.warning( _LW("X-Instance-ID present in request headers. The " "'service_metadata_proxy' option must be " "enabled to process this header.")) meta_data = self._handle_remote_ip_request(req) if meta_data is None: raise webob.exc.HTTPNotFound() try: data = meta_data.lookup(req.path_info) except base.InvalidMetadataPath: raise webob.exc.HTTPNotFound() if callable(data): return data(req, meta_data) resp = base.ec2_md_print(data) if isinstance(resp, six.text_type): req.response.text = resp else: req.response.body = resp req.response.content_type = meta_data.get_mimetype() return req.response def _handle_remote_ip_request(self, req): remote_address = req.remote_addr if CONF.use_forwarded_for: remote_address = req.headers.get('X-Forwarded-For', remote_address) try: meta_data = self.get_metadata_by_remote_address(remote_address) except Exception: LOG.exception(_LE('Failed to get metadata for ip: %s'), remote_address) msg = _('An unknown error has occurred. ' 'Please try your request again.') raise webob.exc.HTTPInternalServerError( explanation=six.text_type(msg)) if meta_data is None: LOG.error(_LE('Failed to get metadata for ip: %s'), remote_address) return meta_data def _handle_instance_id_request(self, req): instance_id = req.headers.get('X-Instance-ID') tenant_id = req.headers.get('X-Tenant-ID') signature = req.headers.get('X-Instance-ID-Signature') remote_address = req.headers.get('X-Forwarded-For') # Ensure that only one header was passed if instance_id is None: msg = _('X-Instance-ID header is missing from request.') elif signature is None: msg = _('X-Instance-ID-Signature header is missing from request.') elif tenant_id is None: msg = _('X-Tenant-ID header is missing from request.') elif not isinstance(instance_id, six.string_types): msg = _('Multiple X-Instance-ID headers found within request.') elif not isinstance(tenant_id, six.string_types): msg = _('Multiple X-Tenant-ID headers found within request.') else: msg = None if msg: raise webob.exc.HTTPBadRequest(explanation=msg) expected_signature = hmac.new( CONF.neutron.metadata_proxy_shared_secret, instance_id, hashlib.sha256).hexdigest() if not utils.constant_time_compare(expected_signature, signature): if instance_id: LOG.warning(_LW('X-Instance-ID-Signature: %(signature)s does ' 'not match the expected value: ' '%(expected_signature)s for id: ' '%(instance_id)s. Request From: ' '%(remote_address)s'), {'signature': signature, 'expected_signature': expected_signature, 'instance_id': instance_id, 'remote_address': remote_address}) msg = _('Invalid proxy request signature.') raise webob.exc.HTTPForbidden(explanation=msg) try: meta_data = self.get_metadata_by_instance_id(instance_id, remote_address) except Exception: LOG.exception(_LE('Failed to get metadata for instance id: %s'), instance_id) msg = _('An unknown error has occurred. ' 'Please try your request again.') raise webob.exc.HTTPInternalServerError( explanation=six.text_type(msg)) if meta_data is None: LOG.error(_LE('Failed to get metadata for instance id: %s'), instance_id) elif meta_data.instance.project_id != tenant_id: LOG.warning(_LW("Tenant_id %(tenant_id)s does not match tenant_id " "of instance %(instance_id)s."), {'tenant_id': tenant_id, 'instance_id': instance_id}) # causes a 404 to be raised meta_data = None return meta_data <|fim▁end|>
return data
<|file_name|>handler.py<|end_file_name|><|fim▁begin|># Copyright 2010 United States Government as represented by the # Administrator of the National Aeronautics and Space Administration. # All Rights Reserved. # # 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. """Metadata request handler.""" import hashlib import hmac import os from oslo_config import cfg from oslo_log import log as logging import six import webob.dec import webob.exc from nova.api.metadata import base from nova import conductor from nova import exception from nova.i18n import _ from nova.i18n import _LE from nova.i18n import _LW from nova.openstack.common import memorycache from nova import utils from nova import wsgi CACHE_EXPIRATION = 15 # in seconds CONF = cfg.CONF CONF.import_opt('use_forwarded_for', 'nova.api.auth') metadata_proxy_opts = [ cfg.BoolOpt( 'service_metadata_proxy', default=False, help='Set flag to indicate Neutron will proxy metadata requests and ' 'resolve instance ids.'), cfg.StrOpt( 'metadata_proxy_shared_secret', default='', secret=True, help='Shared secret to validate proxies Neutron metadata requests'), ] CONF.register_opts(metadata_proxy_opts, 'neutron') LOG = logging.getLogger(__name__) class MetadataRequestHandler(wsgi.Application): """Serve metadata.""" def __init__(self): self._cache = memorycache.get_client() self.conductor_api = conductor.API() def get_metadata_by_remote_address(self, address): if not address: raise exception.FixedIpNotFoundForAddress(address=address) cache_key = 'metadata-%s' % address data = self._cache.get(cache_key) if data: return data try: data = base.get_metadata_by_address(self.conductor_api, address) except exception.NotFound: return None self._cache.set(cache_key, data, CACHE_EXPIRATION) return data def get_metadata_by_instance_id(self, instance_id, address): cache_key = 'metadata-%s' % instance_id data = self._cache.get(cache_key) if data: return data try: data = base.get_metadata_by_instance_id(self.conductor_api, instance_id, address) except exception.NotFound: return None self._cache.set(cache_key, data, CACHE_EXPIRATION) return data @webob.dec.wsgify(RequestClass=wsgi.Request) def __call__(self, req): if os.path.normpath(req.path_info) == "/": <|fim_middle|> if CONF.neutron.service_metadata_proxy: meta_data = self._handle_instance_id_request(req) else: if req.headers.get('X-Instance-ID'): LOG.warning( _LW("X-Instance-ID present in request headers. The " "'service_metadata_proxy' option must be " "enabled to process this header.")) meta_data = self._handle_remote_ip_request(req) if meta_data is None: raise webob.exc.HTTPNotFound() try: data = meta_data.lookup(req.path_info) except base.InvalidMetadataPath: raise webob.exc.HTTPNotFound() if callable(data): return data(req, meta_data) resp = base.ec2_md_print(data) if isinstance(resp, six.text_type): req.response.text = resp else: req.response.body = resp req.response.content_type = meta_data.get_mimetype() return req.response def _handle_remote_ip_request(self, req): remote_address = req.remote_addr if CONF.use_forwarded_for: remote_address = req.headers.get('X-Forwarded-For', remote_address) try: meta_data = self.get_metadata_by_remote_address(remote_address) except Exception: LOG.exception(_LE('Failed to get metadata for ip: %s'), remote_address) msg = _('An unknown error has occurred. ' 'Please try your request again.') raise webob.exc.HTTPInternalServerError( explanation=six.text_type(msg)) if meta_data is None: LOG.error(_LE('Failed to get metadata for ip: %s'), remote_address) return meta_data def _handle_instance_id_request(self, req): instance_id = req.headers.get('X-Instance-ID') tenant_id = req.headers.get('X-Tenant-ID') signature = req.headers.get('X-Instance-ID-Signature') remote_address = req.headers.get('X-Forwarded-For') # Ensure that only one header was passed if instance_id is None: msg = _('X-Instance-ID header is missing from request.') elif signature is None: msg = _('X-Instance-ID-Signature header is missing from request.') elif tenant_id is None: msg = _('X-Tenant-ID header is missing from request.') elif not isinstance(instance_id, six.string_types): msg = _('Multiple X-Instance-ID headers found within request.') elif not isinstance(tenant_id, six.string_types): msg = _('Multiple X-Tenant-ID headers found within request.') else: msg = None if msg: raise webob.exc.HTTPBadRequest(explanation=msg) expected_signature = hmac.new( CONF.neutron.metadata_proxy_shared_secret, instance_id, hashlib.sha256).hexdigest() if not utils.constant_time_compare(expected_signature, signature): if instance_id: LOG.warning(_LW('X-Instance-ID-Signature: %(signature)s does ' 'not match the expected value: ' '%(expected_signature)s for id: ' '%(instance_id)s. Request From: ' '%(remote_address)s'), {'signature': signature, 'expected_signature': expected_signature, 'instance_id': instance_id, 'remote_address': remote_address}) msg = _('Invalid proxy request signature.') raise webob.exc.HTTPForbidden(explanation=msg) try: meta_data = self.get_metadata_by_instance_id(instance_id, remote_address) except Exception: LOG.exception(_LE('Failed to get metadata for instance id: %s'), instance_id) msg = _('An unknown error has occurred. ' 'Please try your request again.') raise webob.exc.HTTPInternalServerError( explanation=six.text_type(msg)) if meta_data is None: LOG.error(_LE('Failed to get metadata for instance id: %s'), instance_id) elif meta_data.instance.project_id != tenant_id: LOG.warning(_LW("Tenant_id %(tenant_id)s does not match tenant_id " "of instance %(instance_id)s."), {'tenant_id': tenant_id, 'instance_id': instance_id}) # causes a 404 to be raised meta_data = None return meta_data <|fim▁end|>
resp = base.ec2_md_print(base.VERSIONS + ["latest"]) req.response.body = resp req.response.content_type = base.MIME_TYPE_TEXT_PLAIN return req.response
<|file_name|>handler.py<|end_file_name|><|fim▁begin|># Copyright 2010 United States Government as represented by the # Administrator of the National Aeronautics and Space Administration. # All Rights Reserved. # # 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. """Metadata request handler.""" import hashlib import hmac import os from oslo_config import cfg from oslo_log import log as logging import six import webob.dec import webob.exc from nova.api.metadata import base from nova import conductor from nova import exception from nova.i18n import _ from nova.i18n import _LE from nova.i18n import _LW from nova.openstack.common import memorycache from nova import utils from nova import wsgi CACHE_EXPIRATION = 15 # in seconds CONF = cfg.CONF CONF.import_opt('use_forwarded_for', 'nova.api.auth') metadata_proxy_opts = [ cfg.BoolOpt( 'service_metadata_proxy', default=False, help='Set flag to indicate Neutron will proxy metadata requests and ' 'resolve instance ids.'), cfg.StrOpt( 'metadata_proxy_shared_secret', default='', secret=True, help='Shared secret to validate proxies Neutron metadata requests'), ] CONF.register_opts(metadata_proxy_opts, 'neutron') LOG = logging.getLogger(__name__) class MetadataRequestHandler(wsgi.Application): """Serve metadata.""" def __init__(self): self._cache = memorycache.get_client() self.conductor_api = conductor.API() def get_metadata_by_remote_address(self, address): if not address: raise exception.FixedIpNotFoundForAddress(address=address) cache_key = 'metadata-%s' % address data = self._cache.get(cache_key) if data: return data try: data = base.get_metadata_by_address(self.conductor_api, address) except exception.NotFound: return None self._cache.set(cache_key, data, CACHE_EXPIRATION) return data def get_metadata_by_instance_id(self, instance_id, address): cache_key = 'metadata-%s' % instance_id data = self._cache.get(cache_key) if data: return data try: data = base.get_metadata_by_instance_id(self.conductor_api, instance_id, address) except exception.NotFound: return None self._cache.set(cache_key, data, CACHE_EXPIRATION) return data @webob.dec.wsgify(RequestClass=wsgi.Request) def __call__(self, req): if os.path.normpath(req.path_info) == "/": resp = base.ec2_md_print(base.VERSIONS + ["latest"]) req.response.body = resp req.response.content_type = base.MIME_TYPE_TEXT_PLAIN return req.response if CONF.neutron.service_metadata_proxy: <|fim_middle|> else: if req.headers.get('X-Instance-ID'): LOG.warning( _LW("X-Instance-ID present in request headers. The " "'service_metadata_proxy' option must be " "enabled to process this header.")) meta_data = self._handle_remote_ip_request(req) if meta_data is None: raise webob.exc.HTTPNotFound() try: data = meta_data.lookup(req.path_info) except base.InvalidMetadataPath: raise webob.exc.HTTPNotFound() if callable(data): return data(req, meta_data) resp = base.ec2_md_print(data) if isinstance(resp, six.text_type): req.response.text = resp else: req.response.body = resp req.response.content_type = meta_data.get_mimetype() return req.response def _handle_remote_ip_request(self, req): remote_address = req.remote_addr if CONF.use_forwarded_for: remote_address = req.headers.get('X-Forwarded-For', remote_address) try: meta_data = self.get_metadata_by_remote_address(remote_address) except Exception: LOG.exception(_LE('Failed to get metadata for ip: %s'), remote_address) msg = _('An unknown error has occurred. ' 'Please try your request again.') raise webob.exc.HTTPInternalServerError( explanation=six.text_type(msg)) if meta_data is None: LOG.error(_LE('Failed to get metadata for ip: %s'), remote_address) return meta_data def _handle_instance_id_request(self, req): instance_id = req.headers.get('X-Instance-ID') tenant_id = req.headers.get('X-Tenant-ID') signature = req.headers.get('X-Instance-ID-Signature') remote_address = req.headers.get('X-Forwarded-For') # Ensure that only one header was passed if instance_id is None: msg = _('X-Instance-ID header is missing from request.') elif signature is None: msg = _('X-Instance-ID-Signature header is missing from request.') elif tenant_id is None: msg = _('X-Tenant-ID header is missing from request.') elif not isinstance(instance_id, six.string_types): msg = _('Multiple X-Instance-ID headers found within request.') elif not isinstance(tenant_id, six.string_types): msg = _('Multiple X-Tenant-ID headers found within request.') else: msg = None if msg: raise webob.exc.HTTPBadRequest(explanation=msg) expected_signature = hmac.new( CONF.neutron.metadata_proxy_shared_secret, instance_id, hashlib.sha256).hexdigest() if not utils.constant_time_compare(expected_signature, signature): if instance_id: LOG.warning(_LW('X-Instance-ID-Signature: %(signature)s does ' 'not match the expected value: ' '%(expected_signature)s for id: ' '%(instance_id)s. Request From: ' '%(remote_address)s'), {'signature': signature, 'expected_signature': expected_signature, 'instance_id': instance_id, 'remote_address': remote_address}) msg = _('Invalid proxy request signature.') raise webob.exc.HTTPForbidden(explanation=msg) try: meta_data = self.get_metadata_by_instance_id(instance_id, remote_address) except Exception: LOG.exception(_LE('Failed to get metadata for instance id: %s'), instance_id) msg = _('An unknown error has occurred. ' 'Please try your request again.') raise webob.exc.HTTPInternalServerError( explanation=six.text_type(msg)) if meta_data is None: LOG.error(_LE('Failed to get metadata for instance id: %s'), instance_id) elif meta_data.instance.project_id != tenant_id: LOG.warning(_LW("Tenant_id %(tenant_id)s does not match tenant_id " "of instance %(instance_id)s."), {'tenant_id': tenant_id, 'instance_id': instance_id}) # causes a 404 to be raised meta_data = None return meta_data <|fim▁end|>
meta_data = self._handle_instance_id_request(req)
<|file_name|>handler.py<|end_file_name|><|fim▁begin|># Copyright 2010 United States Government as represented by the # Administrator of the National Aeronautics and Space Administration. # All Rights Reserved. # # 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. """Metadata request handler.""" import hashlib import hmac import os from oslo_config import cfg from oslo_log import log as logging import six import webob.dec import webob.exc from nova.api.metadata import base from nova import conductor from nova import exception from nova.i18n import _ from nova.i18n import _LE from nova.i18n import _LW from nova.openstack.common import memorycache from nova import utils from nova import wsgi CACHE_EXPIRATION = 15 # in seconds CONF = cfg.CONF CONF.import_opt('use_forwarded_for', 'nova.api.auth') metadata_proxy_opts = [ cfg.BoolOpt( 'service_metadata_proxy', default=False, help='Set flag to indicate Neutron will proxy metadata requests and ' 'resolve instance ids.'), cfg.StrOpt( 'metadata_proxy_shared_secret', default='', secret=True, help='Shared secret to validate proxies Neutron metadata requests'), ] CONF.register_opts(metadata_proxy_opts, 'neutron') LOG = logging.getLogger(__name__) class MetadataRequestHandler(wsgi.Application): """Serve metadata.""" def __init__(self): self._cache = memorycache.get_client() self.conductor_api = conductor.API() def get_metadata_by_remote_address(self, address): if not address: raise exception.FixedIpNotFoundForAddress(address=address) cache_key = 'metadata-%s' % address data = self._cache.get(cache_key) if data: return data try: data = base.get_metadata_by_address(self.conductor_api, address) except exception.NotFound: return None self._cache.set(cache_key, data, CACHE_EXPIRATION) return data def get_metadata_by_instance_id(self, instance_id, address): cache_key = 'metadata-%s' % instance_id data = self._cache.get(cache_key) if data: return data try: data = base.get_metadata_by_instance_id(self.conductor_api, instance_id, address) except exception.NotFound: return None self._cache.set(cache_key, data, CACHE_EXPIRATION) return data @webob.dec.wsgify(RequestClass=wsgi.Request) def __call__(self, req): if os.path.normpath(req.path_info) == "/": resp = base.ec2_md_print(base.VERSIONS + ["latest"]) req.response.body = resp req.response.content_type = base.MIME_TYPE_TEXT_PLAIN return req.response if CONF.neutron.service_metadata_proxy: meta_data = self._handle_instance_id_request(req) else: <|fim_middle|> if meta_data is None: raise webob.exc.HTTPNotFound() try: data = meta_data.lookup(req.path_info) except base.InvalidMetadataPath: raise webob.exc.HTTPNotFound() if callable(data): return data(req, meta_data) resp = base.ec2_md_print(data) if isinstance(resp, six.text_type): req.response.text = resp else: req.response.body = resp req.response.content_type = meta_data.get_mimetype() return req.response def _handle_remote_ip_request(self, req): remote_address = req.remote_addr if CONF.use_forwarded_for: remote_address = req.headers.get('X-Forwarded-For', remote_address) try: meta_data = self.get_metadata_by_remote_address(remote_address) except Exception: LOG.exception(_LE('Failed to get metadata for ip: %s'), remote_address) msg = _('An unknown error has occurred. ' 'Please try your request again.') raise webob.exc.HTTPInternalServerError( explanation=six.text_type(msg)) if meta_data is None: LOG.error(_LE('Failed to get metadata for ip: %s'), remote_address) return meta_data def _handle_instance_id_request(self, req): instance_id = req.headers.get('X-Instance-ID') tenant_id = req.headers.get('X-Tenant-ID') signature = req.headers.get('X-Instance-ID-Signature') remote_address = req.headers.get('X-Forwarded-For') # Ensure that only one header was passed if instance_id is None: msg = _('X-Instance-ID header is missing from request.') elif signature is None: msg = _('X-Instance-ID-Signature header is missing from request.') elif tenant_id is None: msg = _('X-Tenant-ID header is missing from request.') elif not isinstance(instance_id, six.string_types): msg = _('Multiple X-Instance-ID headers found within request.') elif not isinstance(tenant_id, six.string_types): msg = _('Multiple X-Tenant-ID headers found within request.') else: msg = None if msg: raise webob.exc.HTTPBadRequest(explanation=msg) expected_signature = hmac.new( CONF.neutron.metadata_proxy_shared_secret, instance_id, hashlib.sha256).hexdigest() if not utils.constant_time_compare(expected_signature, signature): if instance_id: LOG.warning(_LW('X-Instance-ID-Signature: %(signature)s does ' 'not match the expected value: ' '%(expected_signature)s for id: ' '%(instance_id)s. Request From: ' '%(remote_address)s'), {'signature': signature, 'expected_signature': expected_signature, 'instance_id': instance_id, 'remote_address': remote_address}) msg = _('Invalid proxy request signature.') raise webob.exc.HTTPForbidden(explanation=msg) try: meta_data = self.get_metadata_by_instance_id(instance_id, remote_address) except Exception: LOG.exception(_LE('Failed to get metadata for instance id: %s'), instance_id) msg = _('An unknown error has occurred. ' 'Please try your request again.') raise webob.exc.HTTPInternalServerError( explanation=six.text_type(msg)) if meta_data is None: LOG.error(_LE('Failed to get metadata for instance id: %s'), instance_id) elif meta_data.instance.project_id != tenant_id: LOG.warning(_LW("Tenant_id %(tenant_id)s does not match tenant_id " "of instance %(instance_id)s."), {'tenant_id': tenant_id, 'instance_id': instance_id}) # causes a 404 to be raised meta_data = None return meta_data <|fim▁end|>
if req.headers.get('X-Instance-ID'): LOG.warning( _LW("X-Instance-ID present in request headers. The " "'service_metadata_proxy' option must be " "enabled to process this header.")) meta_data = self._handle_remote_ip_request(req)
<|file_name|>handler.py<|end_file_name|><|fim▁begin|># Copyright 2010 United States Government as represented by the # Administrator of the National Aeronautics and Space Administration. # All Rights Reserved. # # 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. """Metadata request handler.""" import hashlib import hmac import os from oslo_config import cfg from oslo_log import log as logging import six import webob.dec import webob.exc from nova.api.metadata import base from nova import conductor from nova import exception from nova.i18n import _ from nova.i18n import _LE from nova.i18n import _LW from nova.openstack.common import memorycache from nova import utils from nova import wsgi CACHE_EXPIRATION = 15 # in seconds CONF = cfg.CONF CONF.import_opt('use_forwarded_for', 'nova.api.auth') metadata_proxy_opts = [ cfg.BoolOpt( 'service_metadata_proxy', default=False, help='Set flag to indicate Neutron will proxy metadata requests and ' 'resolve instance ids.'), cfg.StrOpt( 'metadata_proxy_shared_secret', default='', secret=True, help='Shared secret to validate proxies Neutron metadata requests'), ] CONF.register_opts(metadata_proxy_opts, 'neutron') LOG = logging.getLogger(__name__) class MetadataRequestHandler(wsgi.Application): """Serve metadata.""" def __init__(self): self._cache = memorycache.get_client() self.conductor_api = conductor.API() def get_metadata_by_remote_address(self, address): if not address: raise exception.FixedIpNotFoundForAddress(address=address) cache_key = 'metadata-%s' % address data = self._cache.get(cache_key) if data: return data try: data = base.get_metadata_by_address(self.conductor_api, address) except exception.NotFound: return None self._cache.set(cache_key, data, CACHE_EXPIRATION) return data def get_metadata_by_instance_id(self, instance_id, address): cache_key = 'metadata-%s' % instance_id data = self._cache.get(cache_key) if data: return data try: data = base.get_metadata_by_instance_id(self.conductor_api, instance_id, address) except exception.NotFound: return None self._cache.set(cache_key, data, CACHE_EXPIRATION) return data @webob.dec.wsgify(RequestClass=wsgi.Request) def __call__(self, req): if os.path.normpath(req.path_info) == "/": resp = base.ec2_md_print(base.VERSIONS + ["latest"]) req.response.body = resp req.response.content_type = base.MIME_TYPE_TEXT_PLAIN return req.response if CONF.neutron.service_metadata_proxy: meta_data = self._handle_instance_id_request(req) else: if req.headers.get('X-Instance-ID'): <|fim_middle|> meta_data = self._handle_remote_ip_request(req) if meta_data is None: raise webob.exc.HTTPNotFound() try: data = meta_data.lookup(req.path_info) except base.InvalidMetadataPath: raise webob.exc.HTTPNotFound() if callable(data): return data(req, meta_data) resp = base.ec2_md_print(data) if isinstance(resp, six.text_type): req.response.text = resp else: req.response.body = resp req.response.content_type = meta_data.get_mimetype() return req.response def _handle_remote_ip_request(self, req): remote_address = req.remote_addr if CONF.use_forwarded_for: remote_address = req.headers.get('X-Forwarded-For', remote_address) try: meta_data = self.get_metadata_by_remote_address(remote_address) except Exception: LOG.exception(_LE('Failed to get metadata for ip: %s'), remote_address) msg = _('An unknown error has occurred. ' 'Please try your request again.') raise webob.exc.HTTPInternalServerError( explanation=six.text_type(msg)) if meta_data is None: LOG.error(_LE('Failed to get metadata for ip: %s'), remote_address) return meta_data def _handle_instance_id_request(self, req): instance_id = req.headers.get('X-Instance-ID') tenant_id = req.headers.get('X-Tenant-ID') signature = req.headers.get('X-Instance-ID-Signature') remote_address = req.headers.get('X-Forwarded-For') # Ensure that only one header was passed if instance_id is None: msg = _('X-Instance-ID header is missing from request.') elif signature is None: msg = _('X-Instance-ID-Signature header is missing from request.') elif tenant_id is None: msg = _('X-Tenant-ID header is missing from request.') elif not isinstance(instance_id, six.string_types): msg = _('Multiple X-Instance-ID headers found within request.') elif not isinstance(tenant_id, six.string_types): msg = _('Multiple X-Tenant-ID headers found within request.') else: msg = None if msg: raise webob.exc.HTTPBadRequest(explanation=msg) expected_signature = hmac.new( CONF.neutron.metadata_proxy_shared_secret, instance_id, hashlib.sha256).hexdigest() if not utils.constant_time_compare(expected_signature, signature): if instance_id: LOG.warning(_LW('X-Instance-ID-Signature: %(signature)s does ' 'not match the expected value: ' '%(expected_signature)s for id: ' '%(instance_id)s. Request From: ' '%(remote_address)s'), {'signature': signature, 'expected_signature': expected_signature, 'instance_id': instance_id, 'remote_address': remote_address}) msg = _('Invalid proxy request signature.') raise webob.exc.HTTPForbidden(explanation=msg) try: meta_data = self.get_metadata_by_instance_id(instance_id, remote_address) except Exception: LOG.exception(_LE('Failed to get metadata for instance id: %s'), instance_id) msg = _('An unknown error has occurred. ' 'Please try your request again.') raise webob.exc.HTTPInternalServerError( explanation=six.text_type(msg)) if meta_data is None: LOG.error(_LE('Failed to get metadata for instance id: %s'), instance_id) elif meta_data.instance.project_id != tenant_id: LOG.warning(_LW("Tenant_id %(tenant_id)s does not match tenant_id " "of instance %(instance_id)s."), {'tenant_id': tenant_id, 'instance_id': instance_id}) # causes a 404 to be raised meta_data = None return meta_data <|fim▁end|>
LOG.warning( _LW("X-Instance-ID present in request headers. The " "'service_metadata_proxy' option must be " "enabled to process this header."))
<|file_name|>handler.py<|end_file_name|><|fim▁begin|># Copyright 2010 United States Government as represented by the # Administrator of the National Aeronautics and Space Administration. # All Rights Reserved. # # 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. """Metadata request handler.""" import hashlib import hmac import os from oslo_config import cfg from oslo_log import log as logging import six import webob.dec import webob.exc from nova.api.metadata import base from nova import conductor from nova import exception from nova.i18n import _ from nova.i18n import _LE from nova.i18n import _LW from nova.openstack.common import memorycache from nova import utils from nova import wsgi CACHE_EXPIRATION = 15 # in seconds CONF = cfg.CONF CONF.import_opt('use_forwarded_for', 'nova.api.auth') metadata_proxy_opts = [ cfg.BoolOpt( 'service_metadata_proxy', default=False, help='Set flag to indicate Neutron will proxy metadata requests and ' 'resolve instance ids.'), cfg.StrOpt( 'metadata_proxy_shared_secret', default='', secret=True, help='Shared secret to validate proxies Neutron metadata requests'), ] CONF.register_opts(metadata_proxy_opts, 'neutron') LOG = logging.getLogger(__name__) class MetadataRequestHandler(wsgi.Application): """Serve metadata.""" def __init__(self): self._cache = memorycache.get_client() self.conductor_api = conductor.API() def get_metadata_by_remote_address(self, address): if not address: raise exception.FixedIpNotFoundForAddress(address=address) cache_key = 'metadata-%s' % address data = self._cache.get(cache_key) if data: return data try: data = base.get_metadata_by_address(self.conductor_api, address) except exception.NotFound: return None self._cache.set(cache_key, data, CACHE_EXPIRATION) return data def get_metadata_by_instance_id(self, instance_id, address): cache_key = 'metadata-%s' % instance_id data = self._cache.get(cache_key) if data: return data try: data = base.get_metadata_by_instance_id(self.conductor_api, instance_id, address) except exception.NotFound: return None self._cache.set(cache_key, data, CACHE_EXPIRATION) return data @webob.dec.wsgify(RequestClass=wsgi.Request) def __call__(self, req): if os.path.normpath(req.path_info) == "/": resp = base.ec2_md_print(base.VERSIONS + ["latest"]) req.response.body = resp req.response.content_type = base.MIME_TYPE_TEXT_PLAIN return req.response if CONF.neutron.service_metadata_proxy: meta_data = self._handle_instance_id_request(req) else: if req.headers.get('X-Instance-ID'): LOG.warning( _LW("X-Instance-ID present in request headers. The " "'service_metadata_proxy' option must be " "enabled to process this header.")) meta_data = self._handle_remote_ip_request(req) if meta_data is None: <|fim_middle|> try: data = meta_data.lookup(req.path_info) except base.InvalidMetadataPath: raise webob.exc.HTTPNotFound() if callable(data): return data(req, meta_data) resp = base.ec2_md_print(data) if isinstance(resp, six.text_type): req.response.text = resp else: req.response.body = resp req.response.content_type = meta_data.get_mimetype() return req.response def _handle_remote_ip_request(self, req): remote_address = req.remote_addr if CONF.use_forwarded_for: remote_address = req.headers.get('X-Forwarded-For', remote_address) try: meta_data = self.get_metadata_by_remote_address(remote_address) except Exception: LOG.exception(_LE('Failed to get metadata for ip: %s'), remote_address) msg = _('An unknown error has occurred. ' 'Please try your request again.') raise webob.exc.HTTPInternalServerError( explanation=six.text_type(msg)) if meta_data is None: LOG.error(_LE('Failed to get metadata for ip: %s'), remote_address) return meta_data def _handle_instance_id_request(self, req): instance_id = req.headers.get('X-Instance-ID') tenant_id = req.headers.get('X-Tenant-ID') signature = req.headers.get('X-Instance-ID-Signature') remote_address = req.headers.get('X-Forwarded-For') # Ensure that only one header was passed if instance_id is None: msg = _('X-Instance-ID header is missing from request.') elif signature is None: msg = _('X-Instance-ID-Signature header is missing from request.') elif tenant_id is None: msg = _('X-Tenant-ID header is missing from request.') elif not isinstance(instance_id, six.string_types): msg = _('Multiple X-Instance-ID headers found within request.') elif not isinstance(tenant_id, six.string_types): msg = _('Multiple X-Tenant-ID headers found within request.') else: msg = None if msg: raise webob.exc.HTTPBadRequest(explanation=msg) expected_signature = hmac.new( CONF.neutron.metadata_proxy_shared_secret, instance_id, hashlib.sha256).hexdigest() if not utils.constant_time_compare(expected_signature, signature): if instance_id: LOG.warning(_LW('X-Instance-ID-Signature: %(signature)s does ' 'not match the expected value: ' '%(expected_signature)s for id: ' '%(instance_id)s. Request From: ' '%(remote_address)s'), {'signature': signature, 'expected_signature': expected_signature, 'instance_id': instance_id, 'remote_address': remote_address}) msg = _('Invalid proxy request signature.') raise webob.exc.HTTPForbidden(explanation=msg) try: meta_data = self.get_metadata_by_instance_id(instance_id, remote_address) except Exception: LOG.exception(_LE('Failed to get metadata for instance id: %s'), instance_id) msg = _('An unknown error has occurred. ' 'Please try your request again.') raise webob.exc.HTTPInternalServerError( explanation=six.text_type(msg)) if meta_data is None: LOG.error(_LE('Failed to get metadata for instance id: %s'), instance_id) elif meta_data.instance.project_id != tenant_id: LOG.warning(_LW("Tenant_id %(tenant_id)s does not match tenant_id " "of instance %(instance_id)s."), {'tenant_id': tenant_id, 'instance_id': instance_id}) # causes a 404 to be raised meta_data = None return meta_data <|fim▁end|>
raise webob.exc.HTTPNotFound()
<|file_name|>handler.py<|end_file_name|><|fim▁begin|># Copyright 2010 United States Government as represented by the # Administrator of the National Aeronautics and Space Administration. # All Rights Reserved. # # 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. """Metadata request handler.""" import hashlib import hmac import os from oslo_config import cfg from oslo_log import log as logging import six import webob.dec import webob.exc from nova.api.metadata import base from nova import conductor from nova import exception from nova.i18n import _ from nova.i18n import _LE from nova.i18n import _LW from nova.openstack.common import memorycache from nova import utils from nova import wsgi CACHE_EXPIRATION = 15 # in seconds CONF = cfg.CONF CONF.import_opt('use_forwarded_for', 'nova.api.auth') metadata_proxy_opts = [ cfg.BoolOpt( 'service_metadata_proxy', default=False, help='Set flag to indicate Neutron will proxy metadata requests and ' 'resolve instance ids.'), cfg.StrOpt( 'metadata_proxy_shared_secret', default='', secret=True, help='Shared secret to validate proxies Neutron metadata requests'), ] CONF.register_opts(metadata_proxy_opts, 'neutron') LOG = logging.getLogger(__name__) class MetadataRequestHandler(wsgi.Application): """Serve metadata.""" def __init__(self): self._cache = memorycache.get_client() self.conductor_api = conductor.API() def get_metadata_by_remote_address(self, address): if not address: raise exception.FixedIpNotFoundForAddress(address=address) cache_key = 'metadata-%s' % address data = self._cache.get(cache_key) if data: return data try: data = base.get_metadata_by_address(self.conductor_api, address) except exception.NotFound: return None self._cache.set(cache_key, data, CACHE_EXPIRATION) return data def get_metadata_by_instance_id(self, instance_id, address): cache_key = 'metadata-%s' % instance_id data = self._cache.get(cache_key) if data: return data try: data = base.get_metadata_by_instance_id(self.conductor_api, instance_id, address) except exception.NotFound: return None self._cache.set(cache_key, data, CACHE_EXPIRATION) return data @webob.dec.wsgify(RequestClass=wsgi.Request) def __call__(self, req): if os.path.normpath(req.path_info) == "/": resp = base.ec2_md_print(base.VERSIONS + ["latest"]) req.response.body = resp req.response.content_type = base.MIME_TYPE_TEXT_PLAIN return req.response if CONF.neutron.service_metadata_proxy: meta_data = self._handle_instance_id_request(req) else: if req.headers.get('X-Instance-ID'): LOG.warning( _LW("X-Instance-ID present in request headers. The " "'service_metadata_proxy' option must be " "enabled to process this header.")) meta_data = self._handle_remote_ip_request(req) if meta_data is None: raise webob.exc.HTTPNotFound() try: data = meta_data.lookup(req.path_info) except base.InvalidMetadataPath: raise webob.exc.HTTPNotFound() if callable(data): <|fim_middle|> resp = base.ec2_md_print(data) if isinstance(resp, six.text_type): req.response.text = resp else: req.response.body = resp req.response.content_type = meta_data.get_mimetype() return req.response def _handle_remote_ip_request(self, req): remote_address = req.remote_addr if CONF.use_forwarded_for: remote_address = req.headers.get('X-Forwarded-For', remote_address) try: meta_data = self.get_metadata_by_remote_address(remote_address) except Exception: LOG.exception(_LE('Failed to get metadata for ip: %s'), remote_address) msg = _('An unknown error has occurred. ' 'Please try your request again.') raise webob.exc.HTTPInternalServerError( explanation=six.text_type(msg)) if meta_data is None: LOG.error(_LE('Failed to get metadata for ip: %s'), remote_address) return meta_data def _handle_instance_id_request(self, req): instance_id = req.headers.get('X-Instance-ID') tenant_id = req.headers.get('X-Tenant-ID') signature = req.headers.get('X-Instance-ID-Signature') remote_address = req.headers.get('X-Forwarded-For') # Ensure that only one header was passed if instance_id is None: msg = _('X-Instance-ID header is missing from request.') elif signature is None: msg = _('X-Instance-ID-Signature header is missing from request.') elif tenant_id is None: msg = _('X-Tenant-ID header is missing from request.') elif not isinstance(instance_id, six.string_types): msg = _('Multiple X-Instance-ID headers found within request.') elif not isinstance(tenant_id, six.string_types): msg = _('Multiple X-Tenant-ID headers found within request.') else: msg = None if msg: raise webob.exc.HTTPBadRequest(explanation=msg) expected_signature = hmac.new( CONF.neutron.metadata_proxy_shared_secret, instance_id, hashlib.sha256).hexdigest() if not utils.constant_time_compare(expected_signature, signature): if instance_id: LOG.warning(_LW('X-Instance-ID-Signature: %(signature)s does ' 'not match the expected value: ' '%(expected_signature)s for id: ' '%(instance_id)s. Request From: ' '%(remote_address)s'), {'signature': signature, 'expected_signature': expected_signature, 'instance_id': instance_id, 'remote_address': remote_address}) msg = _('Invalid proxy request signature.') raise webob.exc.HTTPForbidden(explanation=msg) try: meta_data = self.get_metadata_by_instance_id(instance_id, remote_address) except Exception: LOG.exception(_LE('Failed to get metadata for instance id: %s'), instance_id) msg = _('An unknown error has occurred. ' 'Please try your request again.') raise webob.exc.HTTPInternalServerError( explanation=six.text_type(msg)) if meta_data is None: LOG.error(_LE('Failed to get metadata for instance id: %s'), instance_id) elif meta_data.instance.project_id != tenant_id: LOG.warning(_LW("Tenant_id %(tenant_id)s does not match tenant_id " "of instance %(instance_id)s."), {'tenant_id': tenant_id, 'instance_id': instance_id}) # causes a 404 to be raised meta_data = None return meta_data <|fim▁end|>
return data(req, meta_data)
<|file_name|>handler.py<|end_file_name|><|fim▁begin|># Copyright 2010 United States Government as represented by the # Administrator of the National Aeronautics and Space Administration. # All Rights Reserved. # # 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. """Metadata request handler.""" import hashlib import hmac import os from oslo_config import cfg from oslo_log import log as logging import six import webob.dec import webob.exc from nova.api.metadata import base from nova import conductor from nova import exception from nova.i18n import _ from nova.i18n import _LE from nova.i18n import _LW from nova.openstack.common import memorycache from nova import utils from nova import wsgi CACHE_EXPIRATION = 15 # in seconds CONF = cfg.CONF CONF.import_opt('use_forwarded_for', 'nova.api.auth') metadata_proxy_opts = [ cfg.BoolOpt( 'service_metadata_proxy', default=False, help='Set flag to indicate Neutron will proxy metadata requests and ' 'resolve instance ids.'), cfg.StrOpt( 'metadata_proxy_shared_secret', default='', secret=True, help='Shared secret to validate proxies Neutron metadata requests'), ] CONF.register_opts(metadata_proxy_opts, 'neutron') LOG = logging.getLogger(__name__) class MetadataRequestHandler(wsgi.Application): """Serve metadata.""" def __init__(self): self._cache = memorycache.get_client() self.conductor_api = conductor.API() def get_metadata_by_remote_address(self, address): if not address: raise exception.FixedIpNotFoundForAddress(address=address) cache_key = 'metadata-%s' % address data = self._cache.get(cache_key) if data: return data try: data = base.get_metadata_by_address(self.conductor_api, address) except exception.NotFound: return None self._cache.set(cache_key, data, CACHE_EXPIRATION) return data def get_metadata_by_instance_id(self, instance_id, address): cache_key = 'metadata-%s' % instance_id data = self._cache.get(cache_key) if data: return data try: data = base.get_metadata_by_instance_id(self.conductor_api, instance_id, address) except exception.NotFound: return None self._cache.set(cache_key, data, CACHE_EXPIRATION) return data @webob.dec.wsgify(RequestClass=wsgi.Request) def __call__(self, req): if os.path.normpath(req.path_info) == "/": resp = base.ec2_md_print(base.VERSIONS + ["latest"]) req.response.body = resp req.response.content_type = base.MIME_TYPE_TEXT_PLAIN return req.response if CONF.neutron.service_metadata_proxy: meta_data = self._handle_instance_id_request(req) else: if req.headers.get('X-Instance-ID'): LOG.warning( _LW("X-Instance-ID present in request headers. The " "'service_metadata_proxy' option must be " "enabled to process this header.")) meta_data = self._handle_remote_ip_request(req) if meta_data is None: raise webob.exc.HTTPNotFound() try: data = meta_data.lookup(req.path_info) except base.InvalidMetadataPath: raise webob.exc.HTTPNotFound() if callable(data): return data(req, meta_data) resp = base.ec2_md_print(data) if isinstance(resp, six.text_type): <|fim_middle|> else: req.response.body = resp req.response.content_type = meta_data.get_mimetype() return req.response def _handle_remote_ip_request(self, req): remote_address = req.remote_addr if CONF.use_forwarded_for: remote_address = req.headers.get('X-Forwarded-For', remote_address) try: meta_data = self.get_metadata_by_remote_address(remote_address) except Exception: LOG.exception(_LE('Failed to get metadata for ip: %s'), remote_address) msg = _('An unknown error has occurred. ' 'Please try your request again.') raise webob.exc.HTTPInternalServerError( explanation=six.text_type(msg)) if meta_data is None: LOG.error(_LE('Failed to get metadata for ip: %s'), remote_address) return meta_data def _handle_instance_id_request(self, req): instance_id = req.headers.get('X-Instance-ID') tenant_id = req.headers.get('X-Tenant-ID') signature = req.headers.get('X-Instance-ID-Signature') remote_address = req.headers.get('X-Forwarded-For') # Ensure that only one header was passed if instance_id is None: msg = _('X-Instance-ID header is missing from request.') elif signature is None: msg = _('X-Instance-ID-Signature header is missing from request.') elif tenant_id is None: msg = _('X-Tenant-ID header is missing from request.') elif not isinstance(instance_id, six.string_types): msg = _('Multiple X-Instance-ID headers found within request.') elif not isinstance(tenant_id, six.string_types): msg = _('Multiple X-Tenant-ID headers found within request.') else: msg = None if msg: raise webob.exc.HTTPBadRequest(explanation=msg) expected_signature = hmac.new( CONF.neutron.metadata_proxy_shared_secret, instance_id, hashlib.sha256).hexdigest() if not utils.constant_time_compare(expected_signature, signature): if instance_id: LOG.warning(_LW('X-Instance-ID-Signature: %(signature)s does ' 'not match the expected value: ' '%(expected_signature)s for id: ' '%(instance_id)s. Request From: ' '%(remote_address)s'), {'signature': signature, 'expected_signature': expected_signature, 'instance_id': instance_id, 'remote_address': remote_address}) msg = _('Invalid proxy request signature.') raise webob.exc.HTTPForbidden(explanation=msg) try: meta_data = self.get_metadata_by_instance_id(instance_id, remote_address) except Exception: LOG.exception(_LE('Failed to get metadata for instance id: %s'), instance_id) msg = _('An unknown error has occurred. ' 'Please try your request again.') raise webob.exc.HTTPInternalServerError( explanation=six.text_type(msg)) if meta_data is None: LOG.error(_LE('Failed to get metadata for instance id: %s'), instance_id) elif meta_data.instance.project_id != tenant_id: LOG.warning(_LW("Tenant_id %(tenant_id)s does not match tenant_id " "of instance %(instance_id)s."), {'tenant_id': tenant_id, 'instance_id': instance_id}) # causes a 404 to be raised meta_data = None return meta_data <|fim▁end|>
req.response.text = resp
<|file_name|>handler.py<|end_file_name|><|fim▁begin|># Copyright 2010 United States Government as represented by the # Administrator of the National Aeronautics and Space Administration. # All Rights Reserved. # # 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. """Metadata request handler.""" import hashlib import hmac import os from oslo_config import cfg from oslo_log import log as logging import six import webob.dec import webob.exc from nova.api.metadata import base from nova import conductor from nova import exception from nova.i18n import _ from nova.i18n import _LE from nova.i18n import _LW from nova.openstack.common import memorycache from nova import utils from nova import wsgi CACHE_EXPIRATION = 15 # in seconds CONF = cfg.CONF CONF.import_opt('use_forwarded_for', 'nova.api.auth') metadata_proxy_opts = [ cfg.BoolOpt( 'service_metadata_proxy', default=False, help='Set flag to indicate Neutron will proxy metadata requests and ' 'resolve instance ids.'), cfg.StrOpt( 'metadata_proxy_shared_secret', default='', secret=True, help='Shared secret to validate proxies Neutron metadata requests'), ] CONF.register_opts(metadata_proxy_opts, 'neutron') LOG = logging.getLogger(__name__) class MetadataRequestHandler(wsgi.Application): """Serve metadata.""" def __init__(self): self._cache = memorycache.get_client() self.conductor_api = conductor.API() def get_metadata_by_remote_address(self, address): if not address: raise exception.FixedIpNotFoundForAddress(address=address) cache_key = 'metadata-%s' % address data = self._cache.get(cache_key) if data: return data try: data = base.get_metadata_by_address(self.conductor_api, address) except exception.NotFound: return None self._cache.set(cache_key, data, CACHE_EXPIRATION) return data def get_metadata_by_instance_id(self, instance_id, address): cache_key = 'metadata-%s' % instance_id data = self._cache.get(cache_key) if data: return data try: data = base.get_metadata_by_instance_id(self.conductor_api, instance_id, address) except exception.NotFound: return None self._cache.set(cache_key, data, CACHE_EXPIRATION) return data @webob.dec.wsgify(RequestClass=wsgi.Request) def __call__(self, req): if os.path.normpath(req.path_info) == "/": resp = base.ec2_md_print(base.VERSIONS + ["latest"]) req.response.body = resp req.response.content_type = base.MIME_TYPE_TEXT_PLAIN return req.response if CONF.neutron.service_metadata_proxy: meta_data = self._handle_instance_id_request(req) else: if req.headers.get('X-Instance-ID'): LOG.warning( _LW("X-Instance-ID present in request headers. The " "'service_metadata_proxy' option must be " "enabled to process this header.")) meta_data = self._handle_remote_ip_request(req) if meta_data is None: raise webob.exc.HTTPNotFound() try: data = meta_data.lookup(req.path_info) except base.InvalidMetadataPath: raise webob.exc.HTTPNotFound() if callable(data): return data(req, meta_data) resp = base.ec2_md_print(data) if isinstance(resp, six.text_type): req.response.text = resp else: <|fim_middle|> req.response.content_type = meta_data.get_mimetype() return req.response def _handle_remote_ip_request(self, req): remote_address = req.remote_addr if CONF.use_forwarded_for: remote_address = req.headers.get('X-Forwarded-For', remote_address) try: meta_data = self.get_metadata_by_remote_address(remote_address) except Exception: LOG.exception(_LE('Failed to get metadata for ip: %s'), remote_address) msg = _('An unknown error has occurred. ' 'Please try your request again.') raise webob.exc.HTTPInternalServerError( explanation=six.text_type(msg)) if meta_data is None: LOG.error(_LE('Failed to get metadata for ip: %s'), remote_address) return meta_data def _handle_instance_id_request(self, req): instance_id = req.headers.get('X-Instance-ID') tenant_id = req.headers.get('X-Tenant-ID') signature = req.headers.get('X-Instance-ID-Signature') remote_address = req.headers.get('X-Forwarded-For') # Ensure that only one header was passed if instance_id is None: msg = _('X-Instance-ID header is missing from request.') elif signature is None: msg = _('X-Instance-ID-Signature header is missing from request.') elif tenant_id is None: msg = _('X-Tenant-ID header is missing from request.') elif not isinstance(instance_id, six.string_types): msg = _('Multiple X-Instance-ID headers found within request.') elif not isinstance(tenant_id, six.string_types): msg = _('Multiple X-Tenant-ID headers found within request.') else: msg = None if msg: raise webob.exc.HTTPBadRequest(explanation=msg) expected_signature = hmac.new( CONF.neutron.metadata_proxy_shared_secret, instance_id, hashlib.sha256).hexdigest() if not utils.constant_time_compare(expected_signature, signature): if instance_id: LOG.warning(_LW('X-Instance-ID-Signature: %(signature)s does ' 'not match the expected value: ' '%(expected_signature)s for id: ' '%(instance_id)s. Request From: ' '%(remote_address)s'), {'signature': signature, 'expected_signature': expected_signature, 'instance_id': instance_id, 'remote_address': remote_address}) msg = _('Invalid proxy request signature.') raise webob.exc.HTTPForbidden(explanation=msg) try: meta_data = self.get_metadata_by_instance_id(instance_id, remote_address) except Exception: LOG.exception(_LE('Failed to get metadata for instance id: %s'), instance_id) msg = _('An unknown error has occurred. ' 'Please try your request again.') raise webob.exc.HTTPInternalServerError( explanation=six.text_type(msg)) if meta_data is None: LOG.error(_LE('Failed to get metadata for instance id: %s'), instance_id) elif meta_data.instance.project_id != tenant_id: LOG.warning(_LW("Tenant_id %(tenant_id)s does not match tenant_id " "of instance %(instance_id)s."), {'tenant_id': tenant_id, 'instance_id': instance_id}) # causes a 404 to be raised meta_data = None return meta_data <|fim▁end|>
req.response.body = resp
<|file_name|>handler.py<|end_file_name|><|fim▁begin|># Copyright 2010 United States Government as represented by the # Administrator of the National Aeronautics and Space Administration. # All Rights Reserved. # # 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. """Metadata request handler.""" import hashlib import hmac import os from oslo_config import cfg from oslo_log import log as logging import six import webob.dec import webob.exc from nova.api.metadata import base from nova import conductor from nova import exception from nova.i18n import _ from nova.i18n import _LE from nova.i18n import _LW from nova.openstack.common import memorycache from nova import utils from nova import wsgi CACHE_EXPIRATION = 15 # in seconds CONF = cfg.CONF CONF.import_opt('use_forwarded_for', 'nova.api.auth') metadata_proxy_opts = [ cfg.BoolOpt( 'service_metadata_proxy', default=False, help='Set flag to indicate Neutron will proxy metadata requests and ' 'resolve instance ids.'), cfg.StrOpt( 'metadata_proxy_shared_secret', default='', secret=True, help='Shared secret to validate proxies Neutron metadata requests'), ] CONF.register_opts(metadata_proxy_opts, 'neutron') LOG = logging.getLogger(__name__) class MetadataRequestHandler(wsgi.Application): """Serve metadata.""" def __init__(self): self._cache = memorycache.get_client() self.conductor_api = conductor.API() def get_metadata_by_remote_address(self, address): if not address: raise exception.FixedIpNotFoundForAddress(address=address) cache_key = 'metadata-%s' % address data = self._cache.get(cache_key) if data: return data try: data = base.get_metadata_by_address(self.conductor_api, address) except exception.NotFound: return None self._cache.set(cache_key, data, CACHE_EXPIRATION) return data def get_metadata_by_instance_id(self, instance_id, address): cache_key = 'metadata-%s' % instance_id data = self._cache.get(cache_key) if data: return data try: data = base.get_metadata_by_instance_id(self.conductor_api, instance_id, address) except exception.NotFound: return None self._cache.set(cache_key, data, CACHE_EXPIRATION) return data @webob.dec.wsgify(RequestClass=wsgi.Request) def __call__(self, req): if os.path.normpath(req.path_info) == "/": resp = base.ec2_md_print(base.VERSIONS + ["latest"]) req.response.body = resp req.response.content_type = base.MIME_TYPE_TEXT_PLAIN return req.response if CONF.neutron.service_metadata_proxy: meta_data = self._handle_instance_id_request(req) else: if req.headers.get('X-Instance-ID'): LOG.warning( _LW("X-Instance-ID present in request headers. The " "'service_metadata_proxy' option must be " "enabled to process this header.")) meta_data = self._handle_remote_ip_request(req) if meta_data is None: raise webob.exc.HTTPNotFound() try: data = meta_data.lookup(req.path_info) except base.InvalidMetadataPath: raise webob.exc.HTTPNotFound() if callable(data): return data(req, meta_data) resp = base.ec2_md_print(data) if isinstance(resp, six.text_type): req.response.text = resp else: req.response.body = resp req.response.content_type = meta_data.get_mimetype() return req.response def _handle_remote_ip_request(self, req): remote_address = req.remote_addr if CONF.use_forwarded_for: <|fim_middle|> try: meta_data = self.get_metadata_by_remote_address(remote_address) except Exception: LOG.exception(_LE('Failed to get metadata for ip: %s'), remote_address) msg = _('An unknown error has occurred. ' 'Please try your request again.') raise webob.exc.HTTPInternalServerError( explanation=six.text_type(msg)) if meta_data is None: LOG.error(_LE('Failed to get metadata for ip: %s'), remote_address) return meta_data def _handle_instance_id_request(self, req): instance_id = req.headers.get('X-Instance-ID') tenant_id = req.headers.get('X-Tenant-ID') signature = req.headers.get('X-Instance-ID-Signature') remote_address = req.headers.get('X-Forwarded-For') # Ensure that only one header was passed if instance_id is None: msg = _('X-Instance-ID header is missing from request.') elif signature is None: msg = _('X-Instance-ID-Signature header is missing from request.') elif tenant_id is None: msg = _('X-Tenant-ID header is missing from request.') elif not isinstance(instance_id, six.string_types): msg = _('Multiple X-Instance-ID headers found within request.') elif not isinstance(tenant_id, six.string_types): msg = _('Multiple X-Tenant-ID headers found within request.') else: msg = None if msg: raise webob.exc.HTTPBadRequest(explanation=msg) expected_signature = hmac.new( CONF.neutron.metadata_proxy_shared_secret, instance_id, hashlib.sha256).hexdigest() if not utils.constant_time_compare(expected_signature, signature): if instance_id: LOG.warning(_LW('X-Instance-ID-Signature: %(signature)s does ' 'not match the expected value: ' '%(expected_signature)s for id: ' '%(instance_id)s. Request From: ' '%(remote_address)s'), {'signature': signature, 'expected_signature': expected_signature, 'instance_id': instance_id, 'remote_address': remote_address}) msg = _('Invalid proxy request signature.') raise webob.exc.HTTPForbidden(explanation=msg) try: meta_data = self.get_metadata_by_instance_id(instance_id, remote_address) except Exception: LOG.exception(_LE('Failed to get metadata for instance id: %s'), instance_id) msg = _('An unknown error has occurred. ' 'Please try your request again.') raise webob.exc.HTTPInternalServerError( explanation=six.text_type(msg)) if meta_data is None: LOG.error(_LE('Failed to get metadata for instance id: %s'), instance_id) elif meta_data.instance.project_id != tenant_id: LOG.warning(_LW("Tenant_id %(tenant_id)s does not match tenant_id " "of instance %(instance_id)s."), {'tenant_id': tenant_id, 'instance_id': instance_id}) # causes a 404 to be raised meta_data = None return meta_data <|fim▁end|>
remote_address = req.headers.get('X-Forwarded-For', remote_address)
<|file_name|>handler.py<|end_file_name|><|fim▁begin|># Copyright 2010 United States Government as represented by the # Administrator of the National Aeronautics and Space Administration. # All Rights Reserved. # # 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. """Metadata request handler.""" import hashlib import hmac import os from oslo_config import cfg from oslo_log import log as logging import six import webob.dec import webob.exc from nova.api.metadata import base from nova import conductor from nova import exception from nova.i18n import _ from nova.i18n import _LE from nova.i18n import _LW from nova.openstack.common import memorycache from nova import utils from nova import wsgi CACHE_EXPIRATION = 15 # in seconds CONF = cfg.CONF CONF.import_opt('use_forwarded_for', 'nova.api.auth') metadata_proxy_opts = [ cfg.BoolOpt( 'service_metadata_proxy', default=False, help='Set flag to indicate Neutron will proxy metadata requests and ' 'resolve instance ids.'), cfg.StrOpt( 'metadata_proxy_shared_secret', default='', secret=True, help='Shared secret to validate proxies Neutron metadata requests'), ] CONF.register_opts(metadata_proxy_opts, 'neutron') LOG = logging.getLogger(__name__) class MetadataRequestHandler(wsgi.Application): """Serve metadata.""" def __init__(self): self._cache = memorycache.get_client() self.conductor_api = conductor.API() def get_metadata_by_remote_address(self, address): if not address: raise exception.FixedIpNotFoundForAddress(address=address) cache_key = 'metadata-%s' % address data = self._cache.get(cache_key) if data: return data try: data = base.get_metadata_by_address(self.conductor_api, address) except exception.NotFound: return None self._cache.set(cache_key, data, CACHE_EXPIRATION) return data def get_metadata_by_instance_id(self, instance_id, address): cache_key = 'metadata-%s' % instance_id data = self._cache.get(cache_key) if data: return data try: data = base.get_metadata_by_instance_id(self.conductor_api, instance_id, address) except exception.NotFound: return None self._cache.set(cache_key, data, CACHE_EXPIRATION) return data @webob.dec.wsgify(RequestClass=wsgi.Request) def __call__(self, req): if os.path.normpath(req.path_info) == "/": resp = base.ec2_md_print(base.VERSIONS + ["latest"]) req.response.body = resp req.response.content_type = base.MIME_TYPE_TEXT_PLAIN return req.response if CONF.neutron.service_metadata_proxy: meta_data = self._handle_instance_id_request(req) else: if req.headers.get('X-Instance-ID'): LOG.warning( _LW("X-Instance-ID present in request headers. The " "'service_metadata_proxy' option must be " "enabled to process this header.")) meta_data = self._handle_remote_ip_request(req) if meta_data is None: raise webob.exc.HTTPNotFound() try: data = meta_data.lookup(req.path_info) except base.InvalidMetadataPath: raise webob.exc.HTTPNotFound() if callable(data): return data(req, meta_data) resp = base.ec2_md_print(data) if isinstance(resp, six.text_type): req.response.text = resp else: req.response.body = resp req.response.content_type = meta_data.get_mimetype() return req.response def _handle_remote_ip_request(self, req): remote_address = req.remote_addr if CONF.use_forwarded_for: remote_address = req.headers.get('X-Forwarded-For', remote_address) try: meta_data = self.get_metadata_by_remote_address(remote_address) except Exception: LOG.exception(_LE('Failed to get metadata for ip: %s'), remote_address) msg = _('An unknown error has occurred. ' 'Please try your request again.') raise webob.exc.HTTPInternalServerError( explanation=six.text_type(msg)) if meta_data is None: <|fim_middle|> return meta_data def _handle_instance_id_request(self, req): instance_id = req.headers.get('X-Instance-ID') tenant_id = req.headers.get('X-Tenant-ID') signature = req.headers.get('X-Instance-ID-Signature') remote_address = req.headers.get('X-Forwarded-For') # Ensure that only one header was passed if instance_id is None: msg = _('X-Instance-ID header is missing from request.') elif signature is None: msg = _('X-Instance-ID-Signature header is missing from request.') elif tenant_id is None: msg = _('X-Tenant-ID header is missing from request.') elif not isinstance(instance_id, six.string_types): msg = _('Multiple X-Instance-ID headers found within request.') elif not isinstance(tenant_id, six.string_types): msg = _('Multiple X-Tenant-ID headers found within request.') else: msg = None if msg: raise webob.exc.HTTPBadRequest(explanation=msg) expected_signature = hmac.new( CONF.neutron.metadata_proxy_shared_secret, instance_id, hashlib.sha256).hexdigest() if not utils.constant_time_compare(expected_signature, signature): if instance_id: LOG.warning(_LW('X-Instance-ID-Signature: %(signature)s does ' 'not match the expected value: ' '%(expected_signature)s for id: ' '%(instance_id)s. Request From: ' '%(remote_address)s'), {'signature': signature, 'expected_signature': expected_signature, 'instance_id': instance_id, 'remote_address': remote_address}) msg = _('Invalid proxy request signature.') raise webob.exc.HTTPForbidden(explanation=msg) try: meta_data = self.get_metadata_by_instance_id(instance_id, remote_address) except Exception: LOG.exception(_LE('Failed to get metadata for instance id: %s'), instance_id) msg = _('An unknown error has occurred. ' 'Please try your request again.') raise webob.exc.HTTPInternalServerError( explanation=six.text_type(msg)) if meta_data is None: LOG.error(_LE('Failed to get metadata for instance id: %s'), instance_id) elif meta_data.instance.project_id != tenant_id: LOG.warning(_LW("Tenant_id %(tenant_id)s does not match tenant_id " "of instance %(instance_id)s."), {'tenant_id': tenant_id, 'instance_id': instance_id}) # causes a 404 to be raised meta_data = None return meta_data <|fim▁end|>
LOG.error(_LE('Failed to get metadata for ip: %s'), remote_address)
<|file_name|>handler.py<|end_file_name|><|fim▁begin|># Copyright 2010 United States Government as represented by the # Administrator of the National Aeronautics and Space Administration. # All Rights Reserved. # # 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. """Metadata request handler.""" import hashlib import hmac import os from oslo_config import cfg from oslo_log import log as logging import six import webob.dec import webob.exc from nova.api.metadata import base from nova import conductor from nova import exception from nova.i18n import _ from nova.i18n import _LE from nova.i18n import _LW from nova.openstack.common import memorycache from nova import utils from nova import wsgi CACHE_EXPIRATION = 15 # in seconds CONF = cfg.CONF CONF.import_opt('use_forwarded_for', 'nova.api.auth') metadata_proxy_opts = [ cfg.BoolOpt( 'service_metadata_proxy', default=False, help='Set flag to indicate Neutron will proxy metadata requests and ' 'resolve instance ids.'), cfg.StrOpt( 'metadata_proxy_shared_secret', default='', secret=True, help='Shared secret to validate proxies Neutron metadata requests'), ] CONF.register_opts(metadata_proxy_opts, 'neutron') LOG = logging.getLogger(__name__) class MetadataRequestHandler(wsgi.Application): """Serve metadata.""" def __init__(self): self._cache = memorycache.get_client() self.conductor_api = conductor.API() def get_metadata_by_remote_address(self, address): if not address: raise exception.FixedIpNotFoundForAddress(address=address) cache_key = 'metadata-%s' % address data = self._cache.get(cache_key) if data: return data try: data = base.get_metadata_by_address(self.conductor_api, address) except exception.NotFound: return None self._cache.set(cache_key, data, CACHE_EXPIRATION) return data def get_metadata_by_instance_id(self, instance_id, address): cache_key = 'metadata-%s' % instance_id data = self._cache.get(cache_key) if data: return data try: data = base.get_metadata_by_instance_id(self.conductor_api, instance_id, address) except exception.NotFound: return None self._cache.set(cache_key, data, CACHE_EXPIRATION) return data @webob.dec.wsgify(RequestClass=wsgi.Request) def __call__(self, req): if os.path.normpath(req.path_info) == "/": resp = base.ec2_md_print(base.VERSIONS + ["latest"]) req.response.body = resp req.response.content_type = base.MIME_TYPE_TEXT_PLAIN return req.response if CONF.neutron.service_metadata_proxy: meta_data = self._handle_instance_id_request(req) else: if req.headers.get('X-Instance-ID'): LOG.warning( _LW("X-Instance-ID present in request headers. The " "'service_metadata_proxy' option must be " "enabled to process this header.")) meta_data = self._handle_remote_ip_request(req) if meta_data is None: raise webob.exc.HTTPNotFound() try: data = meta_data.lookup(req.path_info) except base.InvalidMetadataPath: raise webob.exc.HTTPNotFound() if callable(data): return data(req, meta_data) resp = base.ec2_md_print(data) if isinstance(resp, six.text_type): req.response.text = resp else: req.response.body = resp req.response.content_type = meta_data.get_mimetype() return req.response def _handle_remote_ip_request(self, req): remote_address = req.remote_addr if CONF.use_forwarded_for: remote_address = req.headers.get('X-Forwarded-For', remote_address) try: meta_data = self.get_metadata_by_remote_address(remote_address) except Exception: LOG.exception(_LE('Failed to get metadata for ip: %s'), remote_address) msg = _('An unknown error has occurred. ' 'Please try your request again.') raise webob.exc.HTTPInternalServerError( explanation=six.text_type(msg)) if meta_data is None: LOG.error(_LE('Failed to get metadata for ip: %s'), remote_address) return meta_data def _handle_instance_id_request(self, req): instance_id = req.headers.get('X-Instance-ID') tenant_id = req.headers.get('X-Tenant-ID') signature = req.headers.get('X-Instance-ID-Signature') remote_address = req.headers.get('X-Forwarded-For') # Ensure that only one header was passed if instance_id is None: <|fim_middle|> elif signature is None: msg = _('X-Instance-ID-Signature header is missing from request.') elif tenant_id is None: msg = _('X-Tenant-ID header is missing from request.') elif not isinstance(instance_id, six.string_types): msg = _('Multiple X-Instance-ID headers found within request.') elif not isinstance(tenant_id, six.string_types): msg = _('Multiple X-Tenant-ID headers found within request.') else: msg = None if msg: raise webob.exc.HTTPBadRequest(explanation=msg) expected_signature = hmac.new( CONF.neutron.metadata_proxy_shared_secret, instance_id, hashlib.sha256).hexdigest() if not utils.constant_time_compare(expected_signature, signature): if instance_id: LOG.warning(_LW('X-Instance-ID-Signature: %(signature)s does ' 'not match the expected value: ' '%(expected_signature)s for id: ' '%(instance_id)s. Request From: ' '%(remote_address)s'), {'signature': signature, 'expected_signature': expected_signature, 'instance_id': instance_id, 'remote_address': remote_address}) msg = _('Invalid proxy request signature.') raise webob.exc.HTTPForbidden(explanation=msg) try: meta_data = self.get_metadata_by_instance_id(instance_id, remote_address) except Exception: LOG.exception(_LE('Failed to get metadata for instance id: %s'), instance_id) msg = _('An unknown error has occurred. ' 'Please try your request again.') raise webob.exc.HTTPInternalServerError( explanation=six.text_type(msg)) if meta_data is None: LOG.error(_LE('Failed to get metadata for instance id: %s'), instance_id) elif meta_data.instance.project_id != tenant_id: LOG.warning(_LW("Tenant_id %(tenant_id)s does not match tenant_id " "of instance %(instance_id)s."), {'tenant_id': tenant_id, 'instance_id': instance_id}) # causes a 404 to be raised meta_data = None return meta_data <|fim▁end|>
msg = _('X-Instance-ID header is missing from request.')
<|file_name|>handler.py<|end_file_name|><|fim▁begin|># Copyright 2010 United States Government as represented by the # Administrator of the National Aeronautics and Space Administration. # All Rights Reserved. # # 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. """Metadata request handler.""" import hashlib import hmac import os from oslo_config import cfg from oslo_log import log as logging import six import webob.dec import webob.exc from nova.api.metadata import base from nova import conductor from nova import exception from nova.i18n import _ from nova.i18n import _LE from nova.i18n import _LW from nova.openstack.common import memorycache from nova import utils from nova import wsgi CACHE_EXPIRATION = 15 # in seconds CONF = cfg.CONF CONF.import_opt('use_forwarded_for', 'nova.api.auth') metadata_proxy_opts = [ cfg.BoolOpt( 'service_metadata_proxy', default=False, help='Set flag to indicate Neutron will proxy metadata requests and ' 'resolve instance ids.'), cfg.StrOpt( 'metadata_proxy_shared_secret', default='', secret=True, help='Shared secret to validate proxies Neutron metadata requests'), ] CONF.register_opts(metadata_proxy_opts, 'neutron') LOG = logging.getLogger(__name__) class MetadataRequestHandler(wsgi.Application): """Serve metadata.""" def __init__(self): self._cache = memorycache.get_client() self.conductor_api = conductor.API() def get_metadata_by_remote_address(self, address): if not address: raise exception.FixedIpNotFoundForAddress(address=address) cache_key = 'metadata-%s' % address data = self._cache.get(cache_key) if data: return data try: data = base.get_metadata_by_address(self.conductor_api, address) except exception.NotFound: return None self._cache.set(cache_key, data, CACHE_EXPIRATION) return data def get_metadata_by_instance_id(self, instance_id, address): cache_key = 'metadata-%s' % instance_id data = self._cache.get(cache_key) if data: return data try: data = base.get_metadata_by_instance_id(self.conductor_api, instance_id, address) except exception.NotFound: return None self._cache.set(cache_key, data, CACHE_EXPIRATION) return data @webob.dec.wsgify(RequestClass=wsgi.Request) def __call__(self, req): if os.path.normpath(req.path_info) == "/": resp = base.ec2_md_print(base.VERSIONS + ["latest"]) req.response.body = resp req.response.content_type = base.MIME_TYPE_TEXT_PLAIN return req.response if CONF.neutron.service_metadata_proxy: meta_data = self._handle_instance_id_request(req) else: if req.headers.get('X-Instance-ID'): LOG.warning( _LW("X-Instance-ID present in request headers. The " "'service_metadata_proxy' option must be " "enabled to process this header.")) meta_data = self._handle_remote_ip_request(req) if meta_data is None: raise webob.exc.HTTPNotFound() try: data = meta_data.lookup(req.path_info) except base.InvalidMetadataPath: raise webob.exc.HTTPNotFound() if callable(data): return data(req, meta_data) resp = base.ec2_md_print(data) if isinstance(resp, six.text_type): req.response.text = resp else: req.response.body = resp req.response.content_type = meta_data.get_mimetype() return req.response def _handle_remote_ip_request(self, req): remote_address = req.remote_addr if CONF.use_forwarded_for: remote_address = req.headers.get('X-Forwarded-For', remote_address) try: meta_data = self.get_metadata_by_remote_address(remote_address) except Exception: LOG.exception(_LE('Failed to get metadata for ip: %s'), remote_address) msg = _('An unknown error has occurred. ' 'Please try your request again.') raise webob.exc.HTTPInternalServerError( explanation=six.text_type(msg)) if meta_data is None: LOG.error(_LE('Failed to get metadata for ip: %s'), remote_address) return meta_data def _handle_instance_id_request(self, req): instance_id = req.headers.get('X-Instance-ID') tenant_id = req.headers.get('X-Tenant-ID') signature = req.headers.get('X-Instance-ID-Signature') remote_address = req.headers.get('X-Forwarded-For') # Ensure that only one header was passed if instance_id is None: msg = _('X-Instance-ID header is missing from request.') elif signature is None: <|fim_middle|> elif tenant_id is None: msg = _('X-Tenant-ID header is missing from request.') elif not isinstance(instance_id, six.string_types): msg = _('Multiple X-Instance-ID headers found within request.') elif not isinstance(tenant_id, six.string_types): msg = _('Multiple X-Tenant-ID headers found within request.') else: msg = None if msg: raise webob.exc.HTTPBadRequest(explanation=msg) expected_signature = hmac.new( CONF.neutron.metadata_proxy_shared_secret, instance_id, hashlib.sha256).hexdigest() if not utils.constant_time_compare(expected_signature, signature): if instance_id: LOG.warning(_LW('X-Instance-ID-Signature: %(signature)s does ' 'not match the expected value: ' '%(expected_signature)s for id: ' '%(instance_id)s. Request From: ' '%(remote_address)s'), {'signature': signature, 'expected_signature': expected_signature, 'instance_id': instance_id, 'remote_address': remote_address}) msg = _('Invalid proxy request signature.') raise webob.exc.HTTPForbidden(explanation=msg) try: meta_data = self.get_metadata_by_instance_id(instance_id, remote_address) except Exception: LOG.exception(_LE('Failed to get metadata for instance id: %s'), instance_id) msg = _('An unknown error has occurred. ' 'Please try your request again.') raise webob.exc.HTTPInternalServerError( explanation=six.text_type(msg)) if meta_data is None: LOG.error(_LE('Failed to get metadata for instance id: %s'), instance_id) elif meta_data.instance.project_id != tenant_id: LOG.warning(_LW("Tenant_id %(tenant_id)s does not match tenant_id " "of instance %(instance_id)s."), {'tenant_id': tenant_id, 'instance_id': instance_id}) # causes a 404 to be raised meta_data = None return meta_data <|fim▁end|>
msg = _('X-Instance-ID-Signature header is missing from request.')
<|file_name|>handler.py<|end_file_name|><|fim▁begin|># Copyright 2010 United States Government as represented by the # Administrator of the National Aeronautics and Space Administration. # All Rights Reserved. # # 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. """Metadata request handler.""" import hashlib import hmac import os from oslo_config import cfg from oslo_log import log as logging import six import webob.dec import webob.exc from nova.api.metadata import base from nova import conductor from nova import exception from nova.i18n import _ from nova.i18n import _LE from nova.i18n import _LW from nova.openstack.common import memorycache from nova import utils from nova import wsgi CACHE_EXPIRATION = 15 # in seconds CONF = cfg.CONF CONF.import_opt('use_forwarded_for', 'nova.api.auth') metadata_proxy_opts = [ cfg.BoolOpt( 'service_metadata_proxy', default=False, help='Set flag to indicate Neutron will proxy metadata requests and ' 'resolve instance ids.'), cfg.StrOpt( 'metadata_proxy_shared_secret', default='', secret=True, help='Shared secret to validate proxies Neutron metadata requests'), ] CONF.register_opts(metadata_proxy_opts, 'neutron') LOG = logging.getLogger(__name__) class MetadataRequestHandler(wsgi.Application): """Serve metadata.""" def __init__(self): self._cache = memorycache.get_client() self.conductor_api = conductor.API() def get_metadata_by_remote_address(self, address): if not address: raise exception.FixedIpNotFoundForAddress(address=address) cache_key = 'metadata-%s' % address data = self._cache.get(cache_key) if data: return data try: data = base.get_metadata_by_address(self.conductor_api, address) except exception.NotFound: return None self._cache.set(cache_key, data, CACHE_EXPIRATION) return data def get_metadata_by_instance_id(self, instance_id, address): cache_key = 'metadata-%s' % instance_id data = self._cache.get(cache_key) if data: return data try: data = base.get_metadata_by_instance_id(self.conductor_api, instance_id, address) except exception.NotFound: return None self._cache.set(cache_key, data, CACHE_EXPIRATION) return data @webob.dec.wsgify(RequestClass=wsgi.Request) def __call__(self, req): if os.path.normpath(req.path_info) == "/": resp = base.ec2_md_print(base.VERSIONS + ["latest"]) req.response.body = resp req.response.content_type = base.MIME_TYPE_TEXT_PLAIN return req.response if CONF.neutron.service_metadata_proxy: meta_data = self._handle_instance_id_request(req) else: if req.headers.get('X-Instance-ID'): LOG.warning( _LW("X-Instance-ID present in request headers. The " "'service_metadata_proxy' option must be " "enabled to process this header.")) meta_data = self._handle_remote_ip_request(req) if meta_data is None: raise webob.exc.HTTPNotFound() try: data = meta_data.lookup(req.path_info) except base.InvalidMetadataPath: raise webob.exc.HTTPNotFound() if callable(data): return data(req, meta_data) resp = base.ec2_md_print(data) if isinstance(resp, six.text_type): req.response.text = resp else: req.response.body = resp req.response.content_type = meta_data.get_mimetype() return req.response def _handle_remote_ip_request(self, req): remote_address = req.remote_addr if CONF.use_forwarded_for: remote_address = req.headers.get('X-Forwarded-For', remote_address) try: meta_data = self.get_metadata_by_remote_address(remote_address) except Exception: LOG.exception(_LE('Failed to get metadata for ip: %s'), remote_address) msg = _('An unknown error has occurred. ' 'Please try your request again.') raise webob.exc.HTTPInternalServerError( explanation=six.text_type(msg)) if meta_data is None: LOG.error(_LE('Failed to get metadata for ip: %s'), remote_address) return meta_data def _handle_instance_id_request(self, req): instance_id = req.headers.get('X-Instance-ID') tenant_id = req.headers.get('X-Tenant-ID') signature = req.headers.get('X-Instance-ID-Signature') remote_address = req.headers.get('X-Forwarded-For') # Ensure that only one header was passed if instance_id is None: msg = _('X-Instance-ID header is missing from request.') elif signature is None: msg = _('X-Instance-ID-Signature header is missing from request.') elif tenant_id is None: <|fim_middle|> elif not isinstance(instance_id, six.string_types): msg = _('Multiple X-Instance-ID headers found within request.') elif not isinstance(tenant_id, six.string_types): msg = _('Multiple X-Tenant-ID headers found within request.') else: msg = None if msg: raise webob.exc.HTTPBadRequest(explanation=msg) expected_signature = hmac.new( CONF.neutron.metadata_proxy_shared_secret, instance_id, hashlib.sha256).hexdigest() if not utils.constant_time_compare(expected_signature, signature): if instance_id: LOG.warning(_LW('X-Instance-ID-Signature: %(signature)s does ' 'not match the expected value: ' '%(expected_signature)s for id: ' '%(instance_id)s. Request From: ' '%(remote_address)s'), {'signature': signature, 'expected_signature': expected_signature, 'instance_id': instance_id, 'remote_address': remote_address}) msg = _('Invalid proxy request signature.') raise webob.exc.HTTPForbidden(explanation=msg) try: meta_data = self.get_metadata_by_instance_id(instance_id, remote_address) except Exception: LOG.exception(_LE('Failed to get metadata for instance id: %s'), instance_id) msg = _('An unknown error has occurred. ' 'Please try your request again.') raise webob.exc.HTTPInternalServerError( explanation=six.text_type(msg)) if meta_data is None: LOG.error(_LE('Failed to get metadata for instance id: %s'), instance_id) elif meta_data.instance.project_id != tenant_id: LOG.warning(_LW("Tenant_id %(tenant_id)s does not match tenant_id " "of instance %(instance_id)s."), {'tenant_id': tenant_id, 'instance_id': instance_id}) # causes a 404 to be raised meta_data = None return meta_data <|fim▁end|>
msg = _('X-Tenant-ID header is missing from request.')
<|file_name|>handler.py<|end_file_name|><|fim▁begin|># Copyright 2010 United States Government as represented by the # Administrator of the National Aeronautics and Space Administration. # All Rights Reserved. # # 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. """Metadata request handler.""" import hashlib import hmac import os from oslo_config import cfg from oslo_log import log as logging import six import webob.dec import webob.exc from nova.api.metadata import base from nova import conductor from nova import exception from nova.i18n import _ from nova.i18n import _LE from nova.i18n import _LW from nova.openstack.common import memorycache from nova import utils from nova import wsgi CACHE_EXPIRATION = 15 # in seconds CONF = cfg.CONF CONF.import_opt('use_forwarded_for', 'nova.api.auth') metadata_proxy_opts = [ cfg.BoolOpt( 'service_metadata_proxy', default=False, help='Set flag to indicate Neutron will proxy metadata requests and ' 'resolve instance ids.'), cfg.StrOpt( 'metadata_proxy_shared_secret', default='', secret=True, help='Shared secret to validate proxies Neutron metadata requests'), ] CONF.register_opts(metadata_proxy_opts, 'neutron') LOG = logging.getLogger(__name__) class MetadataRequestHandler(wsgi.Application): """Serve metadata.""" def __init__(self): self._cache = memorycache.get_client() self.conductor_api = conductor.API() def get_metadata_by_remote_address(self, address): if not address: raise exception.FixedIpNotFoundForAddress(address=address) cache_key = 'metadata-%s' % address data = self._cache.get(cache_key) if data: return data try: data = base.get_metadata_by_address(self.conductor_api, address) except exception.NotFound: return None self._cache.set(cache_key, data, CACHE_EXPIRATION) return data def get_metadata_by_instance_id(self, instance_id, address): cache_key = 'metadata-%s' % instance_id data = self._cache.get(cache_key) if data: return data try: data = base.get_metadata_by_instance_id(self.conductor_api, instance_id, address) except exception.NotFound: return None self._cache.set(cache_key, data, CACHE_EXPIRATION) return data @webob.dec.wsgify(RequestClass=wsgi.Request) def __call__(self, req): if os.path.normpath(req.path_info) == "/": resp = base.ec2_md_print(base.VERSIONS + ["latest"]) req.response.body = resp req.response.content_type = base.MIME_TYPE_TEXT_PLAIN return req.response if CONF.neutron.service_metadata_proxy: meta_data = self._handle_instance_id_request(req) else: if req.headers.get('X-Instance-ID'): LOG.warning( _LW("X-Instance-ID present in request headers. The " "'service_metadata_proxy' option must be " "enabled to process this header.")) meta_data = self._handle_remote_ip_request(req) if meta_data is None: raise webob.exc.HTTPNotFound() try: data = meta_data.lookup(req.path_info) except base.InvalidMetadataPath: raise webob.exc.HTTPNotFound() if callable(data): return data(req, meta_data) resp = base.ec2_md_print(data) if isinstance(resp, six.text_type): req.response.text = resp else: req.response.body = resp req.response.content_type = meta_data.get_mimetype() return req.response def _handle_remote_ip_request(self, req): remote_address = req.remote_addr if CONF.use_forwarded_for: remote_address = req.headers.get('X-Forwarded-For', remote_address) try: meta_data = self.get_metadata_by_remote_address(remote_address) except Exception: LOG.exception(_LE('Failed to get metadata for ip: %s'), remote_address) msg = _('An unknown error has occurred. ' 'Please try your request again.') raise webob.exc.HTTPInternalServerError( explanation=six.text_type(msg)) if meta_data is None: LOG.error(_LE('Failed to get metadata for ip: %s'), remote_address) return meta_data def _handle_instance_id_request(self, req): instance_id = req.headers.get('X-Instance-ID') tenant_id = req.headers.get('X-Tenant-ID') signature = req.headers.get('X-Instance-ID-Signature') remote_address = req.headers.get('X-Forwarded-For') # Ensure that only one header was passed if instance_id is None: msg = _('X-Instance-ID header is missing from request.') elif signature is None: msg = _('X-Instance-ID-Signature header is missing from request.') elif tenant_id is None: msg = _('X-Tenant-ID header is missing from request.') elif not isinstance(instance_id, six.string_types): <|fim_middle|> elif not isinstance(tenant_id, six.string_types): msg = _('Multiple X-Tenant-ID headers found within request.') else: msg = None if msg: raise webob.exc.HTTPBadRequest(explanation=msg) expected_signature = hmac.new( CONF.neutron.metadata_proxy_shared_secret, instance_id, hashlib.sha256).hexdigest() if not utils.constant_time_compare(expected_signature, signature): if instance_id: LOG.warning(_LW('X-Instance-ID-Signature: %(signature)s does ' 'not match the expected value: ' '%(expected_signature)s for id: ' '%(instance_id)s. Request From: ' '%(remote_address)s'), {'signature': signature, 'expected_signature': expected_signature, 'instance_id': instance_id, 'remote_address': remote_address}) msg = _('Invalid proxy request signature.') raise webob.exc.HTTPForbidden(explanation=msg) try: meta_data = self.get_metadata_by_instance_id(instance_id, remote_address) except Exception: LOG.exception(_LE('Failed to get metadata for instance id: %s'), instance_id) msg = _('An unknown error has occurred. ' 'Please try your request again.') raise webob.exc.HTTPInternalServerError( explanation=six.text_type(msg)) if meta_data is None: LOG.error(_LE('Failed to get metadata for instance id: %s'), instance_id) elif meta_data.instance.project_id != tenant_id: LOG.warning(_LW("Tenant_id %(tenant_id)s does not match tenant_id " "of instance %(instance_id)s."), {'tenant_id': tenant_id, 'instance_id': instance_id}) # causes a 404 to be raised meta_data = None return meta_data <|fim▁end|>
msg = _('Multiple X-Instance-ID headers found within request.')
<|file_name|>handler.py<|end_file_name|><|fim▁begin|># Copyright 2010 United States Government as represented by the # Administrator of the National Aeronautics and Space Administration. # All Rights Reserved. # # 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. """Metadata request handler.""" import hashlib import hmac import os from oslo_config import cfg from oslo_log import log as logging import six import webob.dec import webob.exc from nova.api.metadata import base from nova import conductor from nova import exception from nova.i18n import _ from nova.i18n import _LE from nova.i18n import _LW from nova.openstack.common import memorycache from nova import utils from nova import wsgi CACHE_EXPIRATION = 15 # in seconds CONF = cfg.CONF CONF.import_opt('use_forwarded_for', 'nova.api.auth') metadata_proxy_opts = [ cfg.BoolOpt( 'service_metadata_proxy', default=False, help='Set flag to indicate Neutron will proxy metadata requests and ' 'resolve instance ids.'), cfg.StrOpt( 'metadata_proxy_shared_secret', default='', secret=True, help='Shared secret to validate proxies Neutron metadata requests'), ] CONF.register_opts(metadata_proxy_opts, 'neutron') LOG = logging.getLogger(__name__) class MetadataRequestHandler(wsgi.Application): """Serve metadata.""" def __init__(self): self._cache = memorycache.get_client() self.conductor_api = conductor.API() def get_metadata_by_remote_address(self, address): if not address: raise exception.FixedIpNotFoundForAddress(address=address) cache_key = 'metadata-%s' % address data = self._cache.get(cache_key) if data: return data try: data = base.get_metadata_by_address(self.conductor_api, address) except exception.NotFound: return None self._cache.set(cache_key, data, CACHE_EXPIRATION) return data def get_metadata_by_instance_id(self, instance_id, address): cache_key = 'metadata-%s' % instance_id data = self._cache.get(cache_key) if data: return data try: data = base.get_metadata_by_instance_id(self.conductor_api, instance_id, address) except exception.NotFound: return None self._cache.set(cache_key, data, CACHE_EXPIRATION) return data @webob.dec.wsgify(RequestClass=wsgi.Request) def __call__(self, req): if os.path.normpath(req.path_info) == "/": resp = base.ec2_md_print(base.VERSIONS + ["latest"]) req.response.body = resp req.response.content_type = base.MIME_TYPE_TEXT_PLAIN return req.response if CONF.neutron.service_metadata_proxy: meta_data = self._handle_instance_id_request(req) else: if req.headers.get('X-Instance-ID'): LOG.warning( _LW("X-Instance-ID present in request headers. The " "'service_metadata_proxy' option must be " "enabled to process this header.")) meta_data = self._handle_remote_ip_request(req) if meta_data is None: raise webob.exc.HTTPNotFound() try: data = meta_data.lookup(req.path_info) except base.InvalidMetadataPath: raise webob.exc.HTTPNotFound() if callable(data): return data(req, meta_data) resp = base.ec2_md_print(data) if isinstance(resp, six.text_type): req.response.text = resp else: req.response.body = resp req.response.content_type = meta_data.get_mimetype() return req.response def _handle_remote_ip_request(self, req): remote_address = req.remote_addr if CONF.use_forwarded_for: remote_address = req.headers.get('X-Forwarded-For', remote_address) try: meta_data = self.get_metadata_by_remote_address(remote_address) except Exception: LOG.exception(_LE('Failed to get metadata for ip: %s'), remote_address) msg = _('An unknown error has occurred. ' 'Please try your request again.') raise webob.exc.HTTPInternalServerError( explanation=six.text_type(msg)) if meta_data is None: LOG.error(_LE('Failed to get metadata for ip: %s'), remote_address) return meta_data def _handle_instance_id_request(self, req): instance_id = req.headers.get('X-Instance-ID') tenant_id = req.headers.get('X-Tenant-ID') signature = req.headers.get('X-Instance-ID-Signature') remote_address = req.headers.get('X-Forwarded-For') # Ensure that only one header was passed if instance_id is None: msg = _('X-Instance-ID header is missing from request.') elif signature is None: msg = _('X-Instance-ID-Signature header is missing from request.') elif tenant_id is None: msg = _('X-Tenant-ID header is missing from request.') elif not isinstance(instance_id, six.string_types): msg = _('Multiple X-Instance-ID headers found within request.') elif not isinstance(tenant_id, six.string_types): <|fim_middle|> else: msg = None if msg: raise webob.exc.HTTPBadRequest(explanation=msg) expected_signature = hmac.new( CONF.neutron.metadata_proxy_shared_secret, instance_id, hashlib.sha256).hexdigest() if not utils.constant_time_compare(expected_signature, signature): if instance_id: LOG.warning(_LW('X-Instance-ID-Signature: %(signature)s does ' 'not match the expected value: ' '%(expected_signature)s for id: ' '%(instance_id)s. Request From: ' '%(remote_address)s'), {'signature': signature, 'expected_signature': expected_signature, 'instance_id': instance_id, 'remote_address': remote_address}) msg = _('Invalid proxy request signature.') raise webob.exc.HTTPForbidden(explanation=msg) try: meta_data = self.get_metadata_by_instance_id(instance_id, remote_address) except Exception: LOG.exception(_LE('Failed to get metadata for instance id: %s'), instance_id) msg = _('An unknown error has occurred. ' 'Please try your request again.') raise webob.exc.HTTPInternalServerError( explanation=six.text_type(msg)) if meta_data is None: LOG.error(_LE('Failed to get metadata for instance id: %s'), instance_id) elif meta_data.instance.project_id != tenant_id: LOG.warning(_LW("Tenant_id %(tenant_id)s does not match tenant_id " "of instance %(instance_id)s."), {'tenant_id': tenant_id, 'instance_id': instance_id}) # causes a 404 to be raised meta_data = None return meta_data <|fim▁end|>
msg = _('Multiple X-Tenant-ID headers found within request.')
<|file_name|>handler.py<|end_file_name|><|fim▁begin|># Copyright 2010 United States Government as represented by the # Administrator of the National Aeronautics and Space Administration. # All Rights Reserved. # # 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. """Metadata request handler.""" import hashlib import hmac import os from oslo_config import cfg from oslo_log import log as logging import six import webob.dec import webob.exc from nova.api.metadata import base from nova import conductor from nova import exception from nova.i18n import _ from nova.i18n import _LE from nova.i18n import _LW from nova.openstack.common import memorycache from nova import utils from nova import wsgi CACHE_EXPIRATION = 15 # in seconds CONF = cfg.CONF CONF.import_opt('use_forwarded_for', 'nova.api.auth') metadata_proxy_opts = [ cfg.BoolOpt( 'service_metadata_proxy', default=False, help='Set flag to indicate Neutron will proxy metadata requests and ' 'resolve instance ids.'), cfg.StrOpt( 'metadata_proxy_shared_secret', default='', secret=True, help='Shared secret to validate proxies Neutron metadata requests'), ] CONF.register_opts(metadata_proxy_opts, 'neutron') LOG = logging.getLogger(__name__) class MetadataRequestHandler(wsgi.Application): """Serve metadata.""" def __init__(self): self._cache = memorycache.get_client() self.conductor_api = conductor.API() def get_metadata_by_remote_address(self, address): if not address: raise exception.FixedIpNotFoundForAddress(address=address) cache_key = 'metadata-%s' % address data = self._cache.get(cache_key) if data: return data try: data = base.get_metadata_by_address(self.conductor_api, address) except exception.NotFound: return None self._cache.set(cache_key, data, CACHE_EXPIRATION) return data def get_metadata_by_instance_id(self, instance_id, address): cache_key = 'metadata-%s' % instance_id data = self._cache.get(cache_key) if data: return data try: data = base.get_metadata_by_instance_id(self.conductor_api, instance_id, address) except exception.NotFound: return None self._cache.set(cache_key, data, CACHE_EXPIRATION) return data @webob.dec.wsgify(RequestClass=wsgi.Request) def __call__(self, req): if os.path.normpath(req.path_info) == "/": resp = base.ec2_md_print(base.VERSIONS + ["latest"]) req.response.body = resp req.response.content_type = base.MIME_TYPE_TEXT_PLAIN return req.response if CONF.neutron.service_metadata_proxy: meta_data = self._handle_instance_id_request(req) else: if req.headers.get('X-Instance-ID'): LOG.warning( _LW("X-Instance-ID present in request headers. The " "'service_metadata_proxy' option must be " "enabled to process this header.")) meta_data = self._handle_remote_ip_request(req) if meta_data is None: raise webob.exc.HTTPNotFound() try: data = meta_data.lookup(req.path_info) except base.InvalidMetadataPath: raise webob.exc.HTTPNotFound() if callable(data): return data(req, meta_data) resp = base.ec2_md_print(data) if isinstance(resp, six.text_type): req.response.text = resp else: req.response.body = resp req.response.content_type = meta_data.get_mimetype() return req.response def _handle_remote_ip_request(self, req): remote_address = req.remote_addr if CONF.use_forwarded_for: remote_address = req.headers.get('X-Forwarded-For', remote_address) try: meta_data = self.get_metadata_by_remote_address(remote_address) except Exception: LOG.exception(_LE('Failed to get metadata for ip: %s'), remote_address) msg = _('An unknown error has occurred. ' 'Please try your request again.') raise webob.exc.HTTPInternalServerError( explanation=six.text_type(msg)) if meta_data is None: LOG.error(_LE('Failed to get metadata for ip: %s'), remote_address) return meta_data def _handle_instance_id_request(self, req): instance_id = req.headers.get('X-Instance-ID') tenant_id = req.headers.get('X-Tenant-ID') signature = req.headers.get('X-Instance-ID-Signature') remote_address = req.headers.get('X-Forwarded-For') # Ensure that only one header was passed if instance_id is None: msg = _('X-Instance-ID header is missing from request.') elif signature is None: msg = _('X-Instance-ID-Signature header is missing from request.') elif tenant_id is None: msg = _('X-Tenant-ID header is missing from request.') elif not isinstance(instance_id, six.string_types): msg = _('Multiple X-Instance-ID headers found within request.') elif not isinstance(tenant_id, six.string_types): msg = _('Multiple X-Tenant-ID headers found within request.') else: <|fim_middle|> if msg: raise webob.exc.HTTPBadRequest(explanation=msg) expected_signature = hmac.new( CONF.neutron.metadata_proxy_shared_secret, instance_id, hashlib.sha256).hexdigest() if not utils.constant_time_compare(expected_signature, signature): if instance_id: LOG.warning(_LW('X-Instance-ID-Signature: %(signature)s does ' 'not match the expected value: ' '%(expected_signature)s for id: ' '%(instance_id)s. Request From: ' '%(remote_address)s'), {'signature': signature, 'expected_signature': expected_signature, 'instance_id': instance_id, 'remote_address': remote_address}) msg = _('Invalid proxy request signature.') raise webob.exc.HTTPForbidden(explanation=msg) try: meta_data = self.get_metadata_by_instance_id(instance_id, remote_address) except Exception: LOG.exception(_LE('Failed to get metadata for instance id: %s'), instance_id) msg = _('An unknown error has occurred. ' 'Please try your request again.') raise webob.exc.HTTPInternalServerError( explanation=six.text_type(msg)) if meta_data is None: LOG.error(_LE('Failed to get metadata for instance id: %s'), instance_id) elif meta_data.instance.project_id != tenant_id: LOG.warning(_LW("Tenant_id %(tenant_id)s does not match tenant_id " "of instance %(instance_id)s."), {'tenant_id': tenant_id, 'instance_id': instance_id}) # causes a 404 to be raised meta_data = None return meta_data <|fim▁end|>
msg = None
<|file_name|>handler.py<|end_file_name|><|fim▁begin|># Copyright 2010 United States Government as represented by the # Administrator of the National Aeronautics and Space Administration. # All Rights Reserved. # # 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. """Metadata request handler.""" import hashlib import hmac import os from oslo_config import cfg from oslo_log import log as logging import six import webob.dec import webob.exc from nova.api.metadata import base from nova import conductor from nova import exception from nova.i18n import _ from nova.i18n import _LE from nova.i18n import _LW from nova.openstack.common import memorycache from nova import utils from nova import wsgi CACHE_EXPIRATION = 15 # in seconds CONF = cfg.CONF CONF.import_opt('use_forwarded_for', 'nova.api.auth') metadata_proxy_opts = [ cfg.BoolOpt( 'service_metadata_proxy', default=False, help='Set flag to indicate Neutron will proxy metadata requests and ' 'resolve instance ids.'), cfg.StrOpt( 'metadata_proxy_shared_secret', default='', secret=True, help='Shared secret to validate proxies Neutron metadata requests'), ] CONF.register_opts(metadata_proxy_opts, 'neutron') LOG = logging.getLogger(__name__) class MetadataRequestHandler(wsgi.Application): """Serve metadata.""" def __init__(self): self._cache = memorycache.get_client() self.conductor_api = conductor.API() def get_metadata_by_remote_address(self, address): if not address: raise exception.FixedIpNotFoundForAddress(address=address) cache_key = 'metadata-%s' % address data = self._cache.get(cache_key) if data: return data try: data = base.get_metadata_by_address(self.conductor_api, address) except exception.NotFound: return None self._cache.set(cache_key, data, CACHE_EXPIRATION) return data def get_metadata_by_instance_id(self, instance_id, address): cache_key = 'metadata-%s' % instance_id data = self._cache.get(cache_key) if data: return data try: data = base.get_metadata_by_instance_id(self.conductor_api, instance_id, address) except exception.NotFound: return None self._cache.set(cache_key, data, CACHE_EXPIRATION) return data @webob.dec.wsgify(RequestClass=wsgi.Request) def __call__(self, req): if os.path.normpath(req.path_info) == "/": resp = base.ec2_md_print(base.VERSIONS + ["latest"]) req.response.body = resp req.response.content_type = base.MIME_TYPE_TEXT_PLAIN return req.response if CONF.neutron.service_metadata_proxy: meta_data = self._handle_instance_id_request(req) else: if req.headers.get('X-Instance-ID'): LOG.warning( _LW("X-Instance-ID present in request headers. The " "'service_metadata_proxy' option must be " "enabled to process this header.")) meta_data = self._handle_remote_ip_request(req) if meta_data is None: raise webob.exc.HTTPNotFound() try: data = meta_data.lookup(req.path_info) except base.InvalidMetadataPath: raise webob.exc.HTTPNotFound() if callable(data): return data(req, meta_data) resp = base.ec2_md_print(data) if isinstance(resp, six.text_type): req.response.text = resp else: req.response.body = resp req.response.content_type = meta_data.get_mimetype() return req.response def _handle_remote_ip_request(self, req): remote_address = req.remote_addr if CONF.use_forwarded_for: remote_address = req.headers.get('X-Forwarded-For', remote_address) try: meta_data = self.get_metadata_by_remote_address(remote_address) except Exception: LOG.exception(_LE('Failed to get metadata for ip: %s'), remote_address) msg = _('An unknown error has occurred. ' 'Please try your request again.') raise webob.exc.HTTPInternalServerError( explanation=six.text_type(msg)) if meta_data is None: LOG.error(_LE('Failed to get metadata for ip: %s'), remote_address) return meta_data def _handle_instance_id_request(self, req): instance_id = req.headers.get('X-Instance-ID') tenant_id = req.headers.get('X-Tenant-ID') signature = req.headers.get('X-Instance-ID-Signature') remote_address = req.headers.get('X-Forwarded-For') # Ensure that only one header was passed if instance_id is None: msg = _('X-Instance-ID header is missing from request.') elif signature is None: msg = _('X-Instance-ID-Signature header is missing from request.') elif tenant_id is None: msg = _('X-Tenant-ID header is missing from request.') elif not isinstance(instance_id, six.string_types): msg = _('Multiple X-Instance-ID headers found within request.') elif not isinstance(tenant_id, six.string_types): msg = _('Multiple X-Tenant-ID headers found within request.') else: msg = None if msg: <|fim_middle|> expected_signature = hmac.new( CONF.neutron.metadata_proxy_shared_secret, instance_id, hashlib.sha256).hexdigest() if not utils.constant_time_compare(expected_signature, signature): if instance_id: LOG.warning(_LW('X-Instance-ID-Signature: %(signature)s does ' 'not match the expected value: ' '%(expected_signature)s for id: ' '%(instance_id)s. Request From: ' '%(remote_address)s'), {'signature': signature, 'expected_signature': expected_signature, 'instance_id': instance_id, 'remote_address': remote_address}) msg = _('Invalid proxy request signature.') raise webob.exc.HTTPForbidden(explanation=msg) try: meta_data = self.get_metadata_by_instance_id(instance_id, remote_address) except Exception: LOG.exception(_LE('Failed to get metadata for instance id: %s'), instance_id) msg = _('An unknown error has occurred. ' 'Please try your request again.') raise webob.exc.HTTPInternalServerError( explanation=six.text_type(msg)) if meta_data is None: LOG.error(_LE('Failed to get metadata for instance id: %s'), instance_id) elif meta_data.instance.project_id != tenant_id: LOG.warning(_LW("Tenant_id %(tenant_id)s does not match tenant_id " "of instance %(instance_id)s."), {'tenant_id': tenant_id, 'instance_id': instance_id}) # causes a 404 to be raised meta_data = None return meta_data <|fim▁end|>
raise webob.exc.HTTPBadRequest(explanation=msg)
<|file_name|>handler.py<|end_file_name|><|fim▁begin|># Copyright 2010 United States Government as represented by the # Administrator of the National Aeronautics and Space Administration. # All Rights Reserved. # # 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. """Metadata request handler.""" import hashlib import hmac import os from oslo_config import cfg from oslo_log import log as logging import six import webob.dec import webob.exc from nova.api.metadata import base from nova import conductor from nova import exception from nova.i18n import _ from nova.i18n import _LE from nova.i18n import _LW from nova.openstack.common import memorycache from nova import utils from nova import wsgi CACHE_EXPIRATION = 15 # in seconds CONF = cfg.CONF CONF.import_opt('use_forwarded_for', 'nova.api.auth') metadata_proxy_opts = [ cfg.BoolOpt( 'service_metadata_proxy', default=False, help='Set flag to indicate Neutron will proxy metadata requests and ' 'resolve instance ids.'), cfg.StrOpt( 'metadata_proxy_shared_secret', default='', secret=True, help='Shared secret to validate proxies Neutron metadata requests'), ] CONF.register_opts(metadata_proxy_opts, 'neutron') LOG = logging.getLogger(__name__) class MetadataRequestHandler(wsgi.Application): """Serve metadata.""" def __init__(self): self._cache = memorycache.get_client() self.conductor_api = conductor.API() def get_metadata_by_remote_address(self, address): if not address: raise exception.FixedIpNotFoundForAddress(address=address) cache_key = 'metadata-%s' % address data = self._cache.get(cache_key) if data: return data try: data = base.get_metadata_by_address(self.conductor_api, address) except exception.NotFound: return None self._cache.set(cache_key, data, CACHE_EXPIRATION) return data def get_metadata_by_instance_id(self, instance_id, address): cache_key = 'metadata-%s' % instance_id data = self._cache.get(cache_key) if data: return data try: data = base.get_metadata_by_instance_id(self.conductor_api, instance_id, address) except exception.NotFound: return None self._cache.set(cache_key, data, CACHE_EXPIRATION) return data @webob.dec.wsgify(RequestClass=wsgi.Request) def __call__(self, req): if os.path.normpath(req.path_info) == "/": resp = base.ec2_md_print(base.VERSIONS + ["latest"]) req.response.body = resp req.response.content_type = base.MIME_TYPE_TEXT_PLAIN return req.response if CONF.neutron.service_metadata_proxy: meta_data = self._handle_instance_id_request(req) else: if req.headers.get('X-Instance-ID'): LOG.warning( _LW("X-Instance-ID present in request headers. The " "'service_metadata_proxy' option must be " "enabled to process this header.")) meta_data = self._handle_remote_ip_request(req) if meta_data is None: raise webob.exc.HTTPNotFound() try: data = meta_data.lookup(req.path_info) except base.InvalidMetadataPath: raise webob.exc.HTTPNotFound() if callable(data): return data(req, meta_data) resp = base.ec2_md_print(data) if isinstance(resp, six.text_type): req.response.text = resp else: req.response.body = resp req.response.content_type = meta_data.get_mimetype() return req.response def _handle_remote_ip_request(self, req): remote_address = req.remote_addr if CONF.use_forwarded_for: remote_address = req.headers.get('X-Forwarded-For', remote_address) try: meta_data = self.get_metadata_by_remote_address(remote_address) except Exception: LOG.exception(_LE('Failed to get metadata for ip: %s'), remote_address) msg = _('An unknown error has occurred. ' 'Please try your request again.') raise webob.exc.HTTPInternalServerError( explanation=six.text_type(msg)) if meta_data is None: LOG.error(_LE('Failed to get metadata for ip: %s'), remote_address) return meta_data def _handle_instance_id_request(self, req): instance_id = req.headers.get('X-Instance-ID') tenant_id = req.headers.get('X-Tenant-ID') signature = req.headers.get('X-Instance-ID-Signature') remote_address = req.headers.get('X-Forwarded-For') # Ensure that only one header was passed if instance_id is None: msg = _('X-Instance-ID header is missing from request.') elif signature is None: msg = _('X-Instance-ID-Signature header is missing from request.') elif tenant_id is None: msg = _('X-Tenant-ID header is missing from request.') elif not isinstance(instance_id, six.string_types): msg = _('Multiple X-Instance-ID headers found within request.') elif not isinstance(tenant_id, six.string_types): msg = _('Multiple X-Tenant-ID headers found within request.') else: msg = None if msg: raise webob.exc.HTTPBadRequest(explanation=msg) expected_signature = hmac.new( CONF.neutron.metadata_proxy_shared_secret, instance_id, hashlib.sha256).hexdigest() if not utils.constant_time_compare(expected_signature, signature): <|fim_middle|> try: meta_data = self.get_metadata_by_instance_id(instance_id, remote_address) except Exception: LOG.exception(_LE('Failed to get metadata for instance id: %s'), instance_id) msg = _('An unknown error has occurred. ' 'Please try your request again.') raise webob.exc.HTTPInternalServerError( explanation=six.text_type(msg)) if meta_data is None: LOG.error(_LE('Failed to get metadata for instance id: %s'), instance_id) elif meta_data.instance.project_id != tenant_id: LOG.warning(_LW("Tenant_id %(tenant_id)s does not match tenant_id " "of instance %(instance_id)s."), {'tenant_id': tenant_id, 'instance_id': instance_id}) # causes a 404 to be raised meta_data = None return meta_data <|fim▁end|>
if instance_id: LOG.warning(_LW('X-Instance-ID-Signature: %(signature)s does ' 'not match the expected value: ' '%(expected_signature)s for id: ' '%(instance_id)s. Request From: ' '%(remote_address)s'), {'signature': signature, 'expected_signature': expected_signature, 'instance_id': instance_id, 'remote_address': remote_address}) msg = _('Invalid proxy request signature.') raise webob.exc.HTTPForbidden(explanation=msg)
<|file_name|>handler.py<|end_file_name|><|fim▁begin|># Copyright 2010 United States Government as represented by the # Administrator of the National Aeronautics and Space Administration. # All Rights Reserved. # # 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. """Metadata request handler.""" import hashlib import hmac import os from oslo_config import cfg from oslo_log import log as logging import six import webob.dec import webob.exc from nova.api.metadata import base from nova import conductor from nova import exception from nova.i18n import _ from nova.i18n import _LE from nova.i18n import _LW from nova.openstack.common import memorycache from nova import utils from nova import wsgi CACHE_EXPIRATION = 15 # in seconds CONF = cfg.CONF CONF.import_opt('use_forwarded_for', 'nova.api.auth') metadata_proxy_opts = [ cfg.BoolOpt( 'service_metadata_proxy', default=False, help='Set flag to indicate Neutron will proxy metadata requests and ' 'resolve instance ids.'), cfg.StrOpt( 'metadata_proxy_shared_secret', default='', secret=True, help='Shared secret to validate proxies Neutron metadata requests'), ] CONF.register_opts(metadata_proxy_opts, 'neutron') LOG = logging.getLogger(__name__) class MetadataRequestHandler(wsgi.Application): """Serve metadata.""" def __init__(self): self._cache = memorycache.get_client() self.conductor_api = conductor.API() def get_metadata_by_remote_address(self, address): if not address: raise exception.FixedIpNotFoundForAddress(address=address) cache_key = 'metadata-%s' % address data = self._cache.get(cache_key) if data: return data try: data = base.get_metadata_by_address(self.conductor_api, address) except exception.NotFound: return None self._cache.set(cache_key, data, CACHE_EXPIRATION) return data def get_metadata_by_instance_id(self, instance_id, address): cache_key = 'metadata-%s' % instance_id data = self._cache.get(cache_key) if data: return data try: data = base.get_metadata_by_instance_id(self.conductor_api, instance_id, address) except exception.NotFound: return None self._cache.set(cache_key, data, CACHE_EXPIRATION) return data @webob.dec.wsgify(RequestClass=wsgi.Request) def __call__(self, req): if os.path.normpath(req.path_info) == "/": resp = base.ec2_md_print(base.VERSIONS + ["latest"]) req.response.body = resp req.response.content_type = base.MIME_TYPE_TEXT_PLAIN return req.response if CONF.neutron.service_metadata_proxy: meta_data = self._handle_instance_id_request(req) else: if req.headers.get('X-Instance-ID'): LOG.warning( _LW("X-Instance-ID present in request headers. The " "'service_metadata_proxy' option must be " "enabled to process this header.")) meta_data = self._handle_remote_ip_request(req) if meta_data is None: raise webob.exc.HTTPNotFound() try: data = meta_data.lookup(req.path_info) except base.InvalidMetadataPath: raise webob.exc.HTTPNotFound() if callable(data): return data(req, meta_data) resp = base.ec2_md_print(data) if isinstance(resp, six.text_type): req.response.text = resp else: req.response.body = resp req.response.content_type = meta_data.get_mimetype() return req.response def _handle_remote_ip_request(self, req): remote_address = req.remote_addr if CONF.use_forwarded_for: remote_address = req.headers.get('X-Forwarded-For', remote_address) try: meta_data = self.get_metadata_by_remote_address(remote_address) except Exception: LOG.exception(_LE('Failed to get metadata for ip: %s'), remote_address) msg = _('An unknown error has occurred. ' 'Please try your request again.') raise webob.exc.HTTPInternalServerError( explanation=six.text_type(msg)) if meta_data is None: LOG.error(_LE('Failed to get metadata for ip: %s'), remote_address) return meta_data def _handle_instance_id_request(self, req): instance_id = req.headers.get('X-Instance-ID') tenant_id = req.headers.get('X-Tenant-ID') signature = req.headers.get('X-Instance-ID-Signature') remote_address = req.headers.get('X-Forwarded-For') # Ensure that only one header was passed if instance_id is None: msg = _('X-Instance-ID header is missing from request.') elif signature is None: msg = _('X-Instance-ID-Signature header is missing from request.') elif tenant_id is None: msg = _('X-Tenant-ID header is missing from request.') elif not isinstance(instance_id, six.string_types): msg = _('Multiple X-Instance-ID headers found within request.') elif not isinstance(tenant_id, six.string_types): msg = _('Multiple X-Tenant-ID headers found within request.') else: msg = None if msg: raise webob.exc.HTTPBadRequest(explanation=msg) expected_signature = hmac.new( CONF.neutron.metadata_proxy_shared_secret, instance_id, hashlib.sha256).hexdigest() if not utils.constant_time_compare(expected_signature, signature): if instance_id: <|fim_middle|> msg = _('Invalid proxy request signature.') raise webob.exc.HTTPForbidden(explanation=msg) try: meta_data = self.get_metadata_by_instance_id(instance_id, remote_address) except Exception: LOG.exception(_LE('Failed to get metadata for instance id: %s'), instance_id) msg = _('An unknown error has occurred. ' 'Please try your request again.') raise webob.exc.HTTPInternalServerError( explanation=six.text_type(msg)) if meta_data is None: LOG.error(_LE('Failed to get metadata for instance id: %s'), instance_id) elif meta_data.instance.project_id != tenant_id: LOG.warning(_LW("Tenant_id %(tenant_id)s does not match tenant_id " "of instance %(instance_id)s."), {'tenant_id': tenant_id, 'instance_id': instance_id}) # causes a 404 to be raised meta_data = None return meta_data <|fim▁end|>
LOG.warning(_LW('X-Instance-ID-Signature: %(signature)s does ' 'not match the expected value: ' '%(expected_signature)s for id: ' '%(instance_id)s. Request From: ' '%(remote_address)s'), {'signature': signature, 'expected_signature': expected_signature, 'instance_id': instance_id, 'remote_address': remote_address})
<|file_name|>handler.py<|end_file_name|><|fim▁begin|># Copyright 2010 United States Government as represented by the # Administrator of the National Aeronautics and Space Administration. # All Rights Reserved. # # 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. """Metadata request handler.""" import hashlib import hmac import os from oslo_config import cfg from oslo_log import log as logging import six import webob.dec import webob.exc from nova.api.metadata import base from nova import conductor from nova import exception from nova.i18n import _ from nova.i18n import _LE from nova.i18n import _LW from nova.openstack.common import memorycache from nova import utils from nova import wsgi CACHE_EXPIRATION = 15 # in seconds CONF = cfg.CONF CONF.import_opt('use_forwarded_for', 'nova.api.auth') metadata_proxy_opts = [ cfg.BoolOpt( 'service_metadata_proxy', default=False, help='Set flag to indicate Neutron will proxy metadata requests and ' 'resolve instance ids.'), cfg.StrOpt( 'metadata_proxy_shared_secret', default='', secret=True, help='Shared secret to validate proxies Neutron metadata requests'), ] CONF.register_opts(metadata_proxy_opts, 'neutron') LOG = logging.getLogger(__name__) class MetadataRequestHandler(wsgi.Application): """Serve metadata.""" def __init__(self): self._cache = memorycache.get_client() self.conductor_api = conductor.API() def get_metadata_by_remote_address(self, address): if not address: raise exception.FixedIpNotFoundForAddress(address=address) cache_key = 'metadata-%s' % address data = self._cache.get(cache_key) if data: return data try: data = base.get_metadata_by_address(self.conductor_api, address) except exception.NotFound: return None self._cache.set(cache_key, data, CACHE_EXPIRATION) return data def get_metadata_by_instance_id(self, instance_id, address): cache_key = 'metadata-%s' % instance_id data = self._cache.get(cache_key) if data: return data try: data = base.get_metadata_by_instance_id(self.conductor_api, instance_id, address) except exception.NotFound: return None self._cache.set(cache_key, data, CACHE_EXPIRATION) return data @webob.dec.wsgify(RequestClass=wsgi.Request) def __call__(self, req): if os.path.normpath(req.path_info) == "/": resp = base.ec2_md_print(base.VERSIONS + ["latest"]) req.response.body = resp req.response.content_type = base.MIME_TYPE_TEXT_PLAIN return req.response if CONF.neutron.service_metadata_proxy: meta_data = self._handle_instance_id_request(req) else: if req.headers.get('X-Instance-ID'): LOG.warning( _LW("X-Instance-ID present in request headers. The " "'service_metadata_proxy' option must be " "enabled to process this header.")) meta_data = self._handle_remote_ip_request(req) if meta_data is None: raise webob.exc.HTTPNotFound() try: data = meta_data.lookup(req.path_info) except base.InvalidMetadataPath: raise webob.exc.HTTPNotFound() if callable(data): return data(req, meta_data) resp = base.ec2_md_print(data) if isinstance(resp, six.text_type): req.response.text = resp else: req.response.body = resp req.response.content_type = meta_data.get_mimetype() return req.response def _handle_remote_ip_request(self, req): remote_address = req.remote_addr if CONF.use_forwarded_for: remote_address = req.headers.get('X-Forwarded-For', remote_address) try: meta_data = self.get_metadata_by_remote_address(remote_address) except Exception: LOG.exception(_LE('Failed to get metadata for ip: %s'), remote_address) msg = _('An unknown error has occurred. ' 'Please try your request again.') raise webob.exc.HTTPInternalServerError( explanation=six.text_type(msg)) if meta_data is None: LOG.error(_LE('Failed to get metadata for ip: %s'), remote_address) return meta_data def _handle_instance_id_request(self, req): instance_id = req.headers.get('X-Instance-ID') tenant_id = req.headers.get('X-Tenant-ID') signature = req.headers.get('X-Instance-ID-Signature') remote_address = req.headers.get('X-Forwarded-For') # Ensure that only one header was passed if instance_id is None: msg = _('X-Instance-ID header is missing from request.') elif signature is None: msg = _('X-Instance-ID-Signature header is missing from request.') elif tenant_id is None: msg = _('X-Tenant-ID header is missing from request.') elif not isinstance(instance_id, six.string_types): msg = _('Multiple X-Instance-ID headers found within request.') elif not isinstance(tenant_id, six.string_types): msg = _('Multiple X-Tenant-ID headers found within request.') else: msg = None if msg: raise webob.exc.HTTPBadRequest(explanation=msg) expected_signature = hmac.new( CONF.neutron.metadata_proxy_shared_secret, instance_id, hashlib.sha256).hexdigest() if not utils.constant_time_compare(expected_signature, signature): if instance_id: LOG.warning(_LW('X-Instance-ID-Signature: %(signature)s does ' 'not match the expected value: ' '%(expected_signature)s for id: ' '%(instance_id)s. Request From: ' '%(remote_address)s'), {'signature': signature, 'expected_signature': expected_signature, 'instance_id': instance_id, 'remote_address': remote_address}) msg = _('Invalid proxy request signature.') raise webob.exc.HTTPForbidden(explanation=msg) try: meta_data = self.get_metadata_by_instance_id(instance_id, remote_address) except Exception: LOG.exception(_LE('Failed to get metadata for instance id: %s'), instance_id) msg = _('An unknown error has occurred. ' 'Please try your request again.') raise webob.exc.HTTPInternalServerError( explanation=six.text_type(msg)) if meta_data is None: <|fim_middle|> elif meta_data.instance.project_id != tenant_id: LOG.warning(_LW("Tenant_id %(tenant_id)s does not match tenant_id " "of instance %(instance_id)s."), {'tenant_id': tenant_id, 'instance_id': instance_id}) # causes a 404 to be raised meta_data = None return meta_data <|fim▁end|>
LOG.error(_LE('Failed to get metadata for instance id: %s'), instance_id)
<|file_name|>handler.py<|end_file_name|><|fim▁begin|># Copyright 2010 United States Government as represented by the # Administrator of the National Aeronautics and Space Administration. # All Rights Reserved. # # 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. """Metadata request handler.""" import hashlib import hmac import os from oslo_config import cfg from oslo_log import log as logging import six import webob.dec import webob.exc from nova.api.metadata import base from nova import conductor from nova import exception from nova.i18n import _ from nova.i18n import _LE from nova.i18n import _LW from nova.openstack.common import memorycache from nova import utils from nova import wsgi CACHE_EXPIRATION = 15 # in seconds CONF = cfg.CONF CONF.import_opt('use_forwarded_for', 'nova.api.auth') metadata_proxy_opts = [ cfg.BoolOpt( 'service_metadata_proxy', default=False, help='Set flag to indicate Neutron will proxy metadata requests and ' 'resolve instance ids.'), cfg.StrOpt( 'metadata_proxy_shared_secret', default='', secret=True, help='Shared secret to validate proxies Neutron metadata requests'), ] CONF.register_opts(metadata_proxy_opts, 'neutron') LOG = logging.getLogger(__name__) class MetadataRequestHandler(wsgi.Application): """Serve metadata.""" def __init__(self): self._cache = memorycache.get_client() self.conductor_api = conductor.API() def get_metadata_by_remote_address(self, address): if not address: raise exception.FixedIpNotFoundForAddress(address=address) cache_key = 'metadata-%s' % address data = self._cache.get(cache_key) if data: return data try: data = base.get_metadata_by_address(self.conductor_api, address) except exception.NotFound: return None self._cache.set(cache_key, data, CACHE_EXPIRATION) return data def get_metadata_by_instance_id(self, instance_id, address): cache_key = 'metadata-%s' % instance_id data = self._cache.get(cache_key) if data: return data try: data = base.get_metadata_by_instance_id(self.conductor_api, instance_id, address) except exception.NotFound: return None self._cache.set(cache_key, data, CACHE_EXPIRATION) return data @webob.dec.wsgify(RequestClass=wsgi.Request) def __call__(self, req): if os.path.normpath(req.path_info) == "/": resp = base.ec2_md_print(base.VERSIONS + ["latest"]) req.response.body = resp req.response.content_type = base.MIME_TYPE_TEXT_PLAIN return req.response if CONF.neutron.service_metadata_proxy: meta_data = self._handle_instance_id_request(req) else: if req.headers.get('X-Instance-ID'): LOG.warning( _LW("X-Instance-ID present in request headers. The " "'service_metadata_proxy' option must be " "enabled to process this header.")) meta_data = self._handle_remote_ip_request(req) if meta_data is None: raise webob.exc.HTTPNotFound() try: data = meta_data.lookup(req.path_info) except base.InvalidMetadataPath: raise webob.exc.HTTPNotFound() if callable(data): return data(req, meta_data) resp = base.ec2_md_print(data) if isinstance(resp, six.text_type): req.response.text = resp else: req.response.body = resp req.response.content_type = meta_data.get_mimetype() return req.response def _handle_remote_ip_request(self, req): remote_address = req.remote_addr if CONF.use_forwarded_for: remote_address = req.headers.get('X-Forwarded-For', remote_address) try: meta_data = self.get_metadata_by_remote_address(remote_address) except Exception: LOG.exception(_LE('Failed to get metadata for ip: %s'), remote_address) msg = _('An unknown error has occurred. ' 'Please try your request again.') raise webob.exc.HTTPInternalServerError( explanation=six.text_type(msg)) if meta_data is None: LOG.error(_LE('Failed to get metadata for ip: %s'), remote_address) return meta_data def _handle_instance_id_request(self, req): instance_id = req.headers.get('X-Instance-ID') tenant_id = req.headers.get('X-Tenant-ID') signature = req.headers.get('X-Instance-ID-Signature') remote_address = req.headers.get('X-Forwarded-For') # Ensure that only one header was passed if instance_id is None: msg = _('X-Instance-ID header is missing from request.') elif signature is None: msg = _('X-Instance-ID-Signature header is missing from request.') elif tenant_id is None: msg = _('X-Tenant-ID header is missing from request.') elif not isinstance(instance_id, six.string_types): msg = _('Multiple X-Instance-ID headers found within request.') elif not isinstance(tenant_id, six.string_types): msg = _('Multiple X-Tenant-ID headers found within request.') else: msg = None if msg: raise webob.exc.HTTPBadRequest(explanation=msg) expected_signature = hmac.new( CONF.neutron.metadata_proxy_shared_secret, instance_id, hashlib.sha256).hexdigest() if not utils.constant_time_compare(expected_signature, signature): if instance_id: LOG.warning(_LW('X-Instance-ID-Signature: %(signature)s does ' 'not match the expected value: ' '%(expected_signature)s for id: ' '%(instance_id)s. Request From: ' '%(remote_address)s'), {'signature': signature, 'expected_signature': expected_signature, 'instance_id': instance_id, 'remote_address': remote_address}) msg = _('Invalid proxy request signature.') raise webob.exc.HTTPForbidden(explanation=msg) try: meta_data = self.get_metadata_by_instance_id(instance_id, remote_address) except Exception: LOG.exception(_LE('Failed to get metadata for instance id: %s'), instance_id) msg = _('An unknown error has occurred. ' 'Please try your request again.') raise webob.exc.HTTPInternalServerError( explanation=six.text_type(msg)) if meta_data is None: LOG.error(_LE('Failed to get metadata for instance id: %s'), instance_id) elif meta_data.instance.project_id != tenant_id: <|fim_middle|> return meta_data <|fim▁end|>
LOG.warning(_LW("Tenant_id %(tenant_id)s does not match tenant_id " "of instance %(instance_id)s."), {'tenant_id': tenant_id, 'instance_id': instance_id}) # causes a 404 to be raised meta_data = None
<|file_name|>handler.py<|end_file_name|><|fim▁begin|># Copyright 2010 United States Government as represented by the # Administrator of the National Aeronautics and Space Administration. # All Rights Reserved. # # 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. """Metadata request handler.""" import hashlib import hmac import os from oslo_config import cfg from oslo_log import log as logging import six import webob.dec import webob.exc from nova.api.metadata import base from nova import conductor from nova import exception from nova.i18n import _ from nova.i18n import _LE from nova.i18n import _LW from nova.openstack.common import memorycache from nova import utils from nova import wsgi CACHE_EXPIRATION = 15 # in seconds CONF = cfg.CONF CONF.import_opt('use_forwarded_for', 'nova.api.auth') metadata_proxy_opts = [ cfg.BoolOpt( 'service_metadata_proxy', default=False, help='Set flag to indicate Neutron will proxy metadata requests and ' 'resolve instance ids.'), cfg.StrOpt( 'metadata_proxy_shared_secret', default='', secret=True, help='Shared secret to validate proxies Neutron metadata requests'), ] CONF.register_opts(metadata_proxy_opts, 'neutron') LOG = logging.getLogger(__name__) class MetadataRequestHandler(wsgi.Application): """Serve metadata.""" def <|fim_middle|>(self): self._cache = memorycache.get_client() self.conductor_api = conductor.API() def get_metadata_by_remote_address(self, address): if not address: raise exception.FixedIpNotFoundForAddress(address=address) cache_key = 'metadata-%s' % address data = self._cache.get(cache_key) if data: return data try: data = base.get_metadata_by_address(self.conductor_api, address) except exception.NotFound: return None self._cache.set(cache_key, data, CACHE_EXPIRATION) return data def get_metadata_by_instance_id(self, instance_id, address): cache_key = 'metadata-%s' % instance_id data = self._cache.get(cache_key) if data: return data try: data = base.get_metadata_by_instance_id(self.conductor_api, instance_id, address) except exception.NotFound: return None self._cache.set(cache_key, data, CACHE_EXPIRATION) return data @webob.dec.wsgify(RequestClass=wsgi.Request) def __call__(self, req): if os.path.normpath(req.path_info) == "/": resp = base.ec2_md_print(base.VERSIONS + ["latest"]) req.response.body = resp req.response.content_type = base.MIME_TYPE_TEXT_PLAIN return req.response if CONF.neutron.service_metadata_proxy: meta_data = self._handle_instance_id_request(req) else: if req.headers.get('X-Instance-ID'): LOG.warning( _LW("X-Instance-ID present in request headers. The " "'service_metadata_proxy' option must be " "enabled to process this header.")) meta_data = self._handle_remote_ip_request(req) if meta_data is None: raise webob.exc.HTTPNotFound() try: data = meta_data.lookup(req.path_info) except base.InvalidMetadataPath: raise webob.exc.HTTPNotFound() if callable(data): return data(req, meta_data) resp = base.ec2_md_print(data) if isinstance(resp, six.text_type): req.response.text = resp else: req.response.body = resp req.response.content_type = meta_data.get_mimetype() return req.response def _handle_remote_ip_request(self, req): remote_address = req.remote_addr if CONF.use_forwarded_for: remote_address = req.headers.get('X-Forwarded-For', remote_address) try: meta_data = self.get_metadata_by_remote_address(remote_address) except Exception: LOG.exception(_LE('Failed to get metadata for ip: %s'), remote_address) msg = _('An unknown error has occurred. ' 'Please try your request again.') raise webob.exc.HTTPInternalServerError( explanation=six.text_type(msg)) if meta_data is None: LOG.error(_LE('Failed to get metadata for ip: %s'), remote_address) return meta_data def _handle_instance_id_request(self, req): instance_id = req.headers.get('X-Instance-ID') tenant_id = req.headers.get('X-Tenant-ID') signature = req.headers.get('X-Instance-ID-Signature') remote_address = req.headers.get('X-Forwarded-For') # Ensure that only one header was passed if instance_id is None: msg = _('X-Instance-ID header is missing from request.') elif signature is None: msg = _('X-Instance-ID-Signature header is missing from request.') elif tenant_id is None: msg = _('X-Tenant-ID header is missing from request.') elif not isinstance(instance_id, six.string_types): msg = _('Multiple X-Instance-ID headers found within request.') elif not isinstance(tenant_id, six.string_types): msg = _('Multiple X-Tenant-ID headers found within request.') else: msg = None if msg: raise webob.exc.HTTPBadRequest(explanation=msg) expected_signature = hmac.new( CONF.neutron.metadata_proxy_shared_secret, instance_id, hashlib.sha256).hexdigest() if not utils.constant_time_compare(expected_signature, signature): if instance_id: LOG.warning(_LW('X-Instance-ID-Signature: %(signature)s does ' 'not match the expected value: ' '%(expected_signature)s for id: ' '%(instance_id)s. Request From: ' '%(remote_address)s'), {'signature': signature, 'expected_signature': expected_signature, 'instance_id': instance_id, 'remote_address': remote_address}) msg = _('Invalid proxy request signature.') raise webob.exc.HTTPForbidden(explanation=msg) try: meta_data = self.get_metadata_by_instance_id(instance_id, remote_address) except Exception: LOG.exception(_LE('Failed to get metadata for instance id: %s'), instance_id) msg = _('An unknown error has occurred. ' 'Please try your request again.') raise webob.exc.HTTPInternalServerError( explanation=six.text_type(msg)) if meta_data is None: LOG.error(_LE('Failed to get metadata for instance id: %s'), instance_id) elif meta_data.instance.project_id != tenant_id: LOG.warning(_LW("Tenant_id %(tenant_id)s does not match tenant_id " "of instance %(instance_id)s."), {'tenant_id': tenant_id, 'instance_id': instance_id}) # causes a 404 to be raised meta_data = None return meta_data <|fim▁end|>
__init__
<|file_name|>handler.py<|end_file_name|><|fim▁begin|># Copyright 2010 United States Government as represented by the # Administrator of the National Aeronautics and Space Administration. # All Rights Reserved. # # 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. """Metadata request handler.""" import hashlib import hmac import os from oslo_config import cfg from oslo_log import log as logging import six import webob.dec import webob.exc from nova.api.metadata import base from nova import conductor from nova import exception from nova.i18n import _ from nova.i18n import _LE from nova.i18n import _LW from nova.openstack.common import memorycache from nova import utils from nova import wsgi CACHE_EXPIRATION = 15 # in seconds CONF = cfg.CONF CONF.import_opt('use_forwarded_for', 'nova.api.auth') metadata_proxy_opts = [ cfg.BoolOpt( 'service_metadata_proxy', default=False, help='Set flag to indicate Neutron will proxy metadata requests and ' 'resolve instance ids.'), cfg.StrOpt( 'metadata_proxy_shared_secret', default='', secret=True, help='Shared secret to validate proxies Neutron metadata requests'), ] CONF.register_opts(metadata_proxy_opts, 'neutron') LOG = logging.getLogger(__name__) class MetadataRequestHandler(wsgi.Application): """Serve metadata.""" def __init__(self): self._cache = memorycache.get_client() self.conductor_api = conductor.API() def <|fim_middle|>(self, address): if not address: raise exception.FixedIpNotFoundForAddress(address=address) cache_key = 'metadata-%s' % address data = self._cache.get(cache_key) if data: return data try: data = base.get_metadata_by_address(self.conductor_api, address) except exception.NotFound: return None self._cache.set(cache_key, data, CACHE_EXPIRATION) return data def get_metadata_by_instance_id(self, instance_id, address): cache_key = 'metadata-%s' % instance_id data = self._cache.get(cache_key) if data: return data try: data = base.get_metadata_by_instance_id(self.conductor_api, instance_id, address) except exception.NotFound: return None self._cache.set(cache_key, data, CACHE_EXPIRATION) return data @webob.dec.wsgify(RequestClass=wsgi.Request) def __call__(self, req): if os.path.normpath(req.path_info) == "/": resp = base.ec2_md_print(base.VERSIONS + ["latest"]) req.response.body = resp req.response.content_type = base.MIME_TYPE_TEXT_PLAIN return req.response if CONF.neutron.service_metadata_proxy: meta_data = self._handle_instance_id_request(req) else: if req.headers.get('X-Instance-ID'): LOG.warning( _LW("X-Instance-ID present in request headers. The " "'service_metadata_proxy' option must be " "enabled to process this header.")) meta_data = self._handle_remote_ip_request(req) if meta_data is None: raise webob.exc.HTTPNotFound() try: data = meta_data.lookup(req.path_info) except base.InvalidMetadataPath: raise webob.exc.HTTPNotFound() if callable(data): return data(req, meta_data) resp = base.ec2_md_print(data) if isinstance(resp, six.text_type): req.response.text = resp else: req.response.body = resp req.response.content_type = meta_data.get_mimetype() return req.response def _handle_remote_ip_request(self, req): remote_address = req.remote_addr if CONF.use_forwarded_for: remote_address = req.headers.get('X-Forwarded-For', remote_address) try: meta_data = self.get_metadata_by_remote_address(remote_address) except Exception: LOG.exception(_LE('Failed to get metadata for ip: %s'), remote_address) msg = _('An unknown error has occurred. ' 'Please try your request again.') raise webob.exc.HTTPInternalServerError( explanation=six.text_type(msg)) if meta_data is None: LOG.error(_LE('Failed to get metadata for ip: %s'), remote_address) return meta_data def _handle_instance_id_request(self, req): instance_id = req.headers.get('X-Instance-ID') tenant_id = req.headers.get('X-Tenant-ID') signature = req.headers.get('X-Instance-ID-Signature') remote_address = req.headers.get('X-Forwarded-For') # Ensure that only one header was passed if instance_id is None: msg = _('X-Instance-ID header is missing from request.') elif signature is None: msg = _('X-Instance-ID-Signature header is missing from request.') elif tenant_id is None: msg = _('X-Tenant-ID header is missing from request.') elif not isinstance(instance_id, six.string_types): msg = _('Multiple X-Instance-ID headers found within request.') elif not isinstance(tenant_id, six.string_types): msg = _('Multiple X-Tenant-ID headers found within request.') else: msg = None if msg: raise webob.exc.HTTPBadRequest(explanation=msg) expected_signature = hmac.new( CONF.neutron.metadata_proxy_shared_secret, instance_id, hashlib.sha256).hexdigest() if not utils.constant_time_compare(expected_signature, signature): if instance_id: LOG.warning(_LW('X-Instance-ID-Signature: %(signature)s does ' 'not match the expected value: ' '%(expected_signature)s for id: ' '%(instance_id)s. Request From: ' '%(remote_address)s'), {'signature': signature, 'expected_signature': expected_signature, 'instance_id': instance_id, 'remote_address': remote_address}) msg = _('Invalid proxy request signature.') raise webob.exc.HTTPForbidden(explanation=msg) try: meta_data = self.get_metadata_by_instance_id(instance_id, remote_address) except Exception: LOG.exception(_LE('Failed to get metadata for instance id: %s'), instance_id) msg = _('An unknown error has occurred. ' 'Please try your request again.') raise webob.exc.HTTPInternalServerError( explanation=six.text_type(msg)) if meta_data is None: LOG.error(_LE('Failed to get metadata for instance id: %s'), instance_id) elif meta_data.instance.project_id != tenant_id: LOG.warning(_LW("Tenant_id %(tenant_id)s does not match tenant_id " "of instance %(instance_id)s."), {'tenant_id': tenant_id, 'instance_id': instance_id}) # causes a 404 to be raised meta_data = None return meta_data <|fim▁end|>
get_metadata_by_remote_address
<|file_name|>handler.py<|end_file_name|><|fim▁begin|># Copyright 2010 United States Government as represented by the # Administrator of the National Aeronautics and Space Administration. # All Rights Reserved. # # 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. """Metadata request handler.""" import hashlib import hmac import os from oslo_config import cfg from oslo_log import log as logging import six import webob.dec import webob.exc from nova.api.metadata import base from nova import conductor from nova import exception from nova.i18n import _ from nova.i18n import _LE from nova.i18n import _LW from nova.openstack.common import memorycache from nova import utils from nova import wsgi CACHE_EXPIRATION = 15 # in seconds CONF = cfg.CONF CONF.import_opt('use_forwarded_for', 'nova.api.auth') metadata_proxy_opts = [ cfg.BoolOpt( 'service_metadata_proxy', default=False, help='Set flag to indicate Neutron will proxy metadata requests and ' 'resolve instance ids.'), cfg.StrOpt( 'metadata_proxy_shared_secret', default='', secret=True, help='Shared secret to validate proxies Neutron metadata requests'), ] CONF.register_opts(metadata_proxy_opts, 'neutron') LOG = logging.getLogger(__name__) class MetadataRequestHandler(wsgi.Application): """Serve metadata.""" def __init__(self): self._cache = memorycache.get_client() self.conductor_api = conductor.API() def get_metadata_by_remote_address(self, address): if not address: raise exception.FixedIpNotFoundForAddress(address=address) cache_key = 'metadata-%s' % address data = self._cache.get(cache_key) if data: return data try: data = base.get_metadata_by_address(self.conductor_api, address) except exception.NotFound: return None self._cache.set(cache_key, data, CACHE_EXPIRATION) return data def <|fim_middle|>(self, instance_id, address): cache_key = 'metadata-%s' % instance_id data = self._cache.get(cache_key) if data: return data try: data = base.get_metadata_by_instance_id(self.conductor_api, instance_id, address) except exception.NotFound: return None self._cache.set(cache_key, data, CACHE_EXPIRATION) return data @webob.dec.wsgify(RequestClass=wsgi.Request) def __call__(self, req): if os.path.normpath(req.path_info) == "/": resp = base.ec2_md_print(base.VERSIONS + ["latest"]) req.response.body = resp req.response.content_type = base.MIME_TYPE_TEXT_PLAIN return req.response if CONF.neutron.service_metadata_proxy: meta_data = self._handle_instance_id_request(req) else: if req.headers.get('X-Instance-ID'): LOG.warning( _LW("X-Instance-ID present in request headers. The " "'service_metadata_proxy' option must be " "enabled to process this header.")) meta_data = self._handle_remote_ip_request(req) if meta_data is None: raise webob.exc.HTTPNotFound() try: data = meta_data.lookup(req.path_info) except base.InvalidMetadataPath: raise webob.exc.HTTPNotFound() if callable(data): return data(req, meta_data) resp = base.ec2_md_print(data) if isinstance(resp, six.text_type): req.response.text = resp else: req.response.body = resp req.response.content_type = meta_data.get_mimetype() return req.response def _handle_remote_ip_request(self, req): remote_address = req.remote_addr if CONF.use_forwarded_for: remote_address = req.headers.get('X-Forwarded-For', remote_address) try: meta_data = self.get_metadata_by_remote_address(remote_address) except Exception: LOG.exception(_LE('Failed to get metadata for ip: %s'), remote_address) msg = _('An unknown error has occurred. ' 'Please try your request again.') raise webob.exc.HTTPInternalServerError( explanation=six.text_type(msg)) if meta_data is None: LOG.error(_LE('Failed to get metadata for ip: %s'), remote_address) return meta_data def _handle_instance_id_request(self, req): instance_id = req.headers.get('X-Instance-ID') tenant_id = req.headers.get('X-Tenant-ID') signature = req.headers.get('X-Instance-ID-Signature') remote_address = req.headers.get('X-Forwarded-For') # Ensure that only one header was passed if instance_id is None: msg = _('X-Instance-ID header is missing from request.') elif signature is None: msg = _('X-Instance-ID-Signature header is missing from request.') elif tenant_id is None: msg = _('X-Tenant-ID header is missing from request.') elif not isinstance(instance_id, six.string_types): msg = _('Multiple X-Instance-ID headers found within request.') elif not isinstance(tenant_id, six.string_types): msg = _('Multiple X-Tenant-ID headers found within request.') else: msg = None if msg: raise webob.exc.HTTPBadRequest(explanation=msg) expected_signature = hmac.new( CONF.neutron.metadata_proxy_shared_secret, instance_id, hashlib.sha256).hexdigest() if not utils.constant_time_compare(expected_signature, signature): if instance_id: LOG.warning(_LW('X-Instance-ID-Signature: %(signature)s does ' 'not match the expected value: ' '%(expected_signature)s for id: ' '%(instance_id)s. Request From: ' '%(remote_address)s'), {'signature': signature, 'expected_signature': expected_signature, 'instance_id': instance_id, 'remote_address': remote_address}) msg = _('Invalid proxy request signature.') raise webob.exc.HTTPForbidden(explanation=msg) try: meta_data = self.get_metadata_by_instance_id(instance_id, remote_address) except Exception: LOG.exception(_LE('Failed to get metadata for instance id: %s'), instance_id) msg = _('An unknown error has occurred. ' 'Please try your request again.') raise webob.exc.HTTPInternalServerError( explanation=six.text_type(msg)) if meta_data is None: LOG.error(_LE('Failed to get metadata for instance id: %s'), instance_id) elif meta_data.instance.project_id != tenant_id: LOG.warning(_LW("Tenant_id %(tenant_id)s does not match tenant_id " "of instance %(instance_id)s."), {'tenant_id': tenant_id, 'instance_id': instance_id}) # causes a 404 to be raised meta_data = None return meta_data <|fim▁end|>
get_metadata_by_instance_id
<|file_name|>handler.py<|end_file_name|><|fim▁begin|># Copyright 2010 United States Government as represented by the # Administrator of the National Aeronautics and Space Administration. # All Rights Reserved. # # 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. """Metadata request handler.""" import hashlib import hmac import os from oslo_config import cfg from oslo_log import log as logging import six import webob.dec import webob.exc from nova.api.metadata import base from nova import conductor from nova import exception from nova.i18n import _ from nova.i18n import _LE from nova.i18n import _LW from nova.openstack.common import memorycache from nova import utils from nova import wsgi CACHE_EXPIRATION = 15 # in seconds CONF = cfg.CONF CONF.import_opt('use_forwarded_for', 'nova.api.auth') metadata_proxy_opts = [ cfg.BoolOpt( 'service_metadata_proxy', default=False, help='Set flag to indicate Neutron will proxy metadata requests and ' 'resolve instance ids.'), cfg.StrOpt( 'metadata_proxy_shared_secret', default='', secret=True, help='Shared secret to validate proxies Neutron metadata requests'), ] CONF.register_opts(metadata_proxy_opts, 'neutron') LOG = logging.getLogger(__name__) class MetadataRequestHandler(wsgi.Application): """Serve metadata.""" def __init__(self): self._cache = memorycache.get_client() self.conductor_api = conductor.API() def get_metadata_by_remote_address(self, address): if not address: raise exception.FixedIpNotFoundForAddress(address=address) cache_key = 'metadata-%s' % address data = self._cache.get(cache_key) if data: return data try: data = base.get_metadata_by_address(self.conductor_api, address) except exception.NotFound: return None self._cache.set(cache_key, data, CACHE_EXPIRATION) return data def get_metadata_by_instance_id(self, instance_id, address): cache_key = 'metadata-%s' % instance_id data = self._cache.get(cache_key) if data: return data try: data = base.get_metadata_by_instance_id(self.conductor_api, instance_id, address) except exception.NotFound: return None self._cache.set(cache_key, data, CACHE_EXPIRATION) return data @webob.dec.wsgify(RequestClass=wsgi.Request) def <|fim_middle|>(self, req): if os.path.normpath(req.path_info) == "/": resp = base.ec2_md_print(base.VERSIONS + ["latest"]) req.response.body = resp req.response.content_type = base.MIME_TYPE_TEXT_PLAIN return req.response if CONF.neutron.service_metadata_proxy: meta_data = self._handle_instance_id_request(req) else: if req.headers.get('X-Instance-ID'): LOG.warning( _LW("X-Instance-ID present in request headers. The " "'service_metadata_proxy' option must be " "enabled to process this header.")) meta_data = self._handle_remote_ip_request(req) if meta_data is None: raise webob.exc.HTTPNotFound() try: data = meta_data.lookup(req.path_info) except base.InvalidMetadataPath: raise webob.exc.HTTPNotFound() if callable(data): return data(req, meta_data) resp = base.ec2_md_print(data) if isinstance(resp, six.text_type): req.response.text = resp else: req.response.body = resp req.response.content_type = meta_data.get_mimetype() return req.response def _handle_remote_ip_request(self, req): remote_address = req.remote_addr if CONF.use_forwarded_for: remote_address = req.headers.get('X-Forwarded-For', remote_address) try: meta_data = self.get_metadata_by_remote_address(remote_address) except Exception: LOG.exception(_LE('Failed to get metadata for ip: %s'), remote_address) msg = _('An unknown error has occurred. ' 'Please try your request again.') raise webob.exc.HTTPInternalServerError( explanation=six.text_type(msg)) if meta_data is None: LOG.error(_LE('Failed to get metadata for ip: %s'), remote_address) return meta_data def _handle_instance_id_request(self, req): instance_id = req.headers.get('X-Instance-ID') tenant_id = req.headers.get('X-Tenant-ID') signature = req.headers.get('X-Instance-ID-Signature') remote_address = req.headers.get('X-Forwarded-For') # Ensure that only one header was passed if instance_id is None: msg = _('X-Instance-ID header is missing from request.') elif signature is None: msg = _('X-Instance-ID-Signature header is missing from request.') elif tenant_id is None: msg = _('X-Tenant-ID header is missing from request.') elif not isinstance(instance_id, six.string_types): msg = _('Multiple X-Instance-ID headers found within request.') elif not isinstance(tenant_id, six.string_types): msg = _('Multiple X-Tenant-ID headers found within request.') else: msg = None if msg: raise webob.exc.HTTPBadRequest(explanation=msg) expected_signature = hmac.new( CONF.neutron.metadata_proxy_shared_secret, instance_id, hashlib.sha256).hexdigest() if not utils.constant_time_compare(expected_signature, signature): if instance_id: LOG.warning(_LW('X-Instance-ID-Signature: %(signature)s does ' 'not match the expected value: ' '%(expected_signature)s for id: ' '%(instance_id)s. Request From: ' '%(remote_address)s'), {'signature': signature, 'expected_signature': expected_signature, 'instance_id': instance_id, 'remote_address': remote_address}) msg = _('Invalid proxy request signature.') raise webob.exc.HTTPForbidden(explanation=msg) try: meta_data = self.get_metadata_by_instance_id(instance_id, remote_address) except Exception: LOG.exception(_LE('Failed to get metadata for instance id: %s'), instance_id) msg = _('An unknown error has occurred. ' 'Please try your request again.') raise webob.exc.HTTPInternalServerError( explanation=six.text_type(msg)) if meta_data is None: LOG.error(_LE('Failed to get metadata for instance id: %s'), instance_id) elif meta_data.instance.project_id != tenant_id: LOG.warning(_LW("Tenant_id %(tenant_id)s does not match tenant_id " "of instance %(instance_id)s."), {'tenant_id': tenant_id, 'instance_id': instance_id}) # causes a 404 to be raised meta_data = None return meta_data <|fim▁end|>
__call__
<|file_name|>handler.py<|end_file_name|><|fim▁begin|># Copyright 2010 United States Government as represented by the # Administrator of the National Aeronautics and Space Administration. # All Rights Reserved. # # 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. """Metadata request handler.""" import hashlib import hmac import os from oslo_config import cfg from oslo_log import log as logging import six import webob.dec import webob.exc from nova.api.metadata import base from nova import conductor from nova import exception from nova.i18n import _ from nova.i18n import _LE from nova.i18n import _LW from nova.openstack.common import memorycache from nova import utils from nova import wsgi CACHE_EXPIRATION = 15 # in seconds CONF = cfg.CONF CONF.import_opt('use_forwarded_for', 'nova.api.auth') metadata_proxy_opts = [ cfg.BoolOpt( 'service_metadata_proxy', default=False, help='Set flag to indicate Neutron will proxy metadata requests and ' 'resolve instance ids.'), cfg.StrOpt( 'metadata_proxy_shared_secret', default='', secret=True, help='Shared secret to validate proxies Neutron metadata requests'), ] CONF.register_opts(metadata_proxy_opts, 'neutron') LOG = logging.getLogger(__name__) class MetadataRequestHandler(wsgi.Application): """Serve metadata.""" def __init__(self): self._cache = memorycache.get_client() self.conductor_api = conductor.API() def get_metadata_by_remote_address(self, address): if not address: raise exception.FixedIpNotFoundForAddress(address=address) cache_key = 'metadata-%s' % address data = self._cache.get(cache_key) if data: return data try: data = base.get_metadata_by_address(self.conductor_api, address) except exception.NotFound: return None self._cache.set(cache_key, data, CACHE_EXPIRATION) return data def get_metadata_by_instance_id(self, instance_id, address): cache_key = 'metadata-%s' % instance_id data = self._cache.get(cache_key) if data: return data try: data = base.get_metadata_by_instance_id(self.conductor_api, instance_id, address) except exception.NotFound: return None self._cache.set(cache_key, data, CACHE_EXPIRATION) return data @webob.dec.wsgify(RequestClass=wsgi.Request) def __call__(self, req): if os.path.normpath(req.path_info) == "/": resp = base.ec2_md_print(base.VERSIONS + ["latest"]) req.response.body = resp req.response.content_type = base.MIME_TYPE_TEXT_PLAIN return req.response if CONF.neutron.service_metadata_proxy: meta_data = self._handle_instance_id_request(req) else: if req.headers.get('X-Instance-ID'): LOG.warning( _LW("X-Instance-ID present in request headers. The " "'service_metadata_proxy' option must be " "enabled to process this header.")) meta_data = self._handle_remote_ip_request(req) if meta_data is None: raise webob.exc.HTTPNotFound() try: data = meta_data.lookup(req.path_info) except base.InvalidMetadataPath: raise webob.exc.HTTPNotFound() if callable(data): return data(req, meta_data) resp = base.ec2_md_print(data) if isinstance(resp, six.text_type): req.response.text = resp else: req.response.body = resp req.response.content_type = meta_data.get_mimetype() return req.response def <|fim_middle|>(self, req): remote_address = req.remote_addr if CONF.use_forwarded_for: remote_address = req.headers.get('X-Forwarded-For', remote_address) try: meta_data = self.get_metadata_by_remote_address(remote_address) except Exception: LOG.exception(_LE('Failed to get metadata for ip: %s'), remote_address) msg = _('An unknown error has occurred. ' 'Please try your request again.') raise webob.exc.HTTPInternalServerError( explanation=six.text_type(msg)) if meta_data is None: LOG.error(_LE('Failed to get metadata for ip: %s'), remote_address) return meta_data def _handle_instance_id_request(self, req): instance_id = req.headers.get('X-Instance-ID') tenant_id = req.headers.get('X-Tenant-ID') signature = req.headers.get('X-Instance-ID-Signature') remote_address = req.headers.get('X-Forwarded-For') # Ensure that only one header was passed if instance_id is None: msg = _('X-Instance-ID header is missing from request.') elif signature is None: msg = _('X-Instance-ID-Signature header is missing from request.') elif tenant_id is None: msg = _('X-Tenant-ID header is missing from request.') elif not isinstance(instance_id, six.string_types): msg = _('Multiple X-Instance-ID headers found within request.') elif not isinstance(tenant_id, six.string_types): msg = _('Multiple X-Tenant-ID headers found within request.') else: msg = None if msg: raise webob.exc.HTTPBadRequest(explanation=msg) expected_signature = hmac.new( CONF.neutron.metadata_proxy_shared_secret, instance_id, hashlib.sha256).hexdigest() if not utils.constant_time_compare(expected_signature, signature): if instance_id: LOG.warning(_LW('X-Instance-ID-Signature: %(signature)s does ' 'not match the expected value: ' '%(expected_signature)s for id: ' '%(instance_id)s. Request From: ' '%(remote_address)s'), {'signature': signature, 'expected_signature': expected_signature, 'instance_id': instance_id, 'remote_address': remote_address}) msg = _('Invalid proxy request signature.') raise webob.exc.HTTPForbidden(explanation=msg) try: meta_data = self.get_metadata_by_instance_id(instance_id, remote_address) except Exception: LOG.exception(_LE('Failed to get metadata for instance id: %s'), instance_id) msg = _('An unknown error has occurred. ' 'Please try your request again.') raise webob.exc.HTTPInternalServerError( explanation=six.text_type(msg)) if meta_data is None: LOG.error(_LE('Failed to get metadata for instance id: %s'), instance_id) elif meta_data.instance.project_id != tenant_id: LOG.warning(_LW("Tenant_id %(tenant_id)s does not match tenant_id " "of instance %(instance_id)s."), {'tenant_id': tenant_id, 'instance_id': instance_id}) # causes a 404 to be raised meta_data = None return meta_data <|fim▁end|>
_handle_remote_ip_request
<|file_name|>handler.py<|end_file_name|><|fim▁begin|># Copyright 2010 United States Government as represented by the # Administrator of the National Aeronautics and Space Administration. # All Rights Reserved. # # 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. """Metadata request handler.""" import hashlib import hmac import os from oslo_config import cfg from oslo_log import log as logging import six import webob.dec import webob.exc from nova.api.metadata import base from nova import conductor from nova import exception from nova.i18n import _ from nova.i18n import _LE from nova.i18n import _LW from nova.openstack.common import memorycache from nova import utils from nova import wsgi CACHE_EXPIRATION = 15 # in seconds CONF = cfg.CONF CONF.import_opt('use_forwarded_for', 'nova.api.auth') metadata_proxy_opts = [ cfg.BoolOpt( 'service_metadata_proxy', default=False, help='Set flag to indicate Neutron will proxy metadata requests and ' 'resolve instance ids.'), cfg.StrOpt( 'metadata_proxy_shared_secret', default='', secret=True, help='Shared secret to validate proxies Neutron metadata requests'), ] CONF.register_opts(metadata_proxy_opts, 'neutron') LOG = logging.getLogger(__name__) class MetadataRequestHandler(wsgi.Application): """Serve metadata.""" def __init__(self): self._cache = memorycache.get_client() self.conductor_api = conductor.API() def get_metadata_by_remote_address(self, address): if not address: raise exception.FixedIpNotFoundForAddress(address=address) cache_key = 'metadata-%s' % address data = self._cache.get(cache_key) if data: return data try: data = base.get_metadata_by_address(self.conductor_api, address) except exception.NotFound: return None self._cache.set(cache_key, data, CACHE_EXPIRATION) return data def get_metadata_by_instance_id(self, instance_id, address): cache_key = 'metadata-%s' % instance_id data = self._cache.get(cache_key) if data: return data try: data = base.get_metadata_by_instance_id(self.conductor_api, instance_id, address) except exception.NotFound: return None self._cache.set(cache_key, data, CACHE_EXPIRATION) return data @webob.dec.wsgify(RequestClass=wsgi.Request) def __call__(self, req): if os.path.normpath(req.path_info) == "/": resp = base.ec2_md_print(base.VERSIONS + ["latest"]) req.response.body = resp req.response.content_type = base.MIME_TYPE_TEXT_PLAIN return req.response if CONF.neutron.service_metadata_proxy: meta_data = self._handle_instance_id_request(req) else: if req.headers.get('X-Instance-ID'): LOG.warning( _LW("X-Instance-ID present in request headers. The " "'service_metadata_proxy' option must be " "enabled to process this header.")) meta_data = self._handle_remote_ip_request(req) if meta_data is None: raise webob.exc.HTTPNotFound() try: data = meta_data.lookup(req.path_info) except base.InvalidMetadataPath: raise webob.exc.HTTPNotFound() if callable(data): return data(req, meta_data) resp = base.ec2_md_print(data) if isinstance(resp, six.text_type): req.response.text = resp else: req.response.body = resp req.response.content_type = meta_data.get_mimetype() return req.response def _handle_remote_ip_request(self, req): remote_address = req.remote_addr if CONF.use_forwarded_for: remote_address = req.headers.get('X-Forwarded-For', remote_address) try: meta_data = self.get_metadata_by_remote_address(remote_address) except Exception: LOG.exception(_LE('Failed to get metadata for ip: %s'), remote_address) msg = _('An unknown error has occurred. ' 'Please try your request again.') raise webob.exc.HTTPInternalServerError( explanation=six.text_type(msg)) if meta_data is None: LOG.error(_LE('Failed to get metadata for ip: %s'), remote_address) return meta_data def <|fim_middle|>(self, req): instance_id = req.headers.get('X-Instance-ID') tenant_id = req.headers.get('X-Tenant-ID') signature = req.headers.get('X-Instance-ID-Signature') remote_address = req.headers.get('X-Forwarded-For') # Ensure that only one header was passed if instance_id is None: msg = _('X-Instance-ID header is missing from request.') elif signature is None: msg = _('X-Instance-ID-Signature header is missing from request.') elif tenant_id is None: msg = _('X-Tenant-ID header is missing from request.') elif not isinstance(instance_id, six.string_types): msg = _('Multiple X-Instance-ID headers found within request.') elif not isinstance(tenant_id, six.string_types): msg = _('Multiple X-Tenant-ID headers found within request.') else: msg = None if msg: raise webob.exc.HTTPBadRequest(explanation=msg) expected_signature = hmac.new( CONF.neutron.metadata_proxy_shared_secret, instance_id, hashlib.sha256).hexdigest() if not utils.constant_time_compare(expected_signature, signature): if instance_id: LOG.warning(_LW('X-Instance-ID-Signature: %(signature)s does ' 'not match the expected value: ' '%(expected_signature)s for id: ' '%(instance_id)s. Request From: ' '%(remote_address)s'), {'signature': signature, 'expected_signature': expected_signature, 'instance_id': instance_id, 'remote_address': remote_address}) msg = _('Invalid proxy request signature.') raise webob.exc.HTTPForbidden(explanation=msg) try: meta_data = self.get_metadata_by_instance_id(instance_id, remote_address) except Exception: LOG.exception(_LE('Failed to get metadata for instance id: %s'), instance_id) msg = _('An unknown error has occurred. ' 'Please try your request again.') raise webob.exc.HTTPInternalServerError( explanation=six.text_type(msg)) if meta_data is None: LOG.error(_LE('Failed to get metadata for instance id: %s'), instance_id) elif meta_data.instance.project_id != tenant_id: LOG.warning(_LW("Tenant_id %(tenant_id)s does not match tenant_id " "of instance %(instance_id)s."), {'tenant_id': tenant_id, 'instance_id': instance_id}) # causes a 404 to be raised meta_data = None return meta_data <|fim▁end|>
_handle_instance_id_request
<|file_name|>PrimeSieve.py<|end_file_name|><|fim▁begin|>import math def isPrime(num):<|fim▁hole|> # num为100时, 它是不可能有因子是大于50的. 比如说60 * ? = 100, 这是不可能的, 所以这里只要比较sqrt(), 平方根 boundary = int(math.sqrt(num)) + 1 for i in range(2, boundary): if num % i == 0: return False return True def primeSieve(size): sieve = [True] * size # 某格一为乘积, 就置为False sieve[0] = False sieve[1] = True # num为100时, 它是不可能有因子是大于50的. 比如说60 * ? = 100, 这是不可能的, 所以这里只要比较sqrt(), 平方根 boundary = int(math.sqrt(size)) + 1 for i in range(2, boundary): pointer = i * 2 # startPosition. 以3为例, 3其实是质数, 但它的位数6,9, 12, ...都不是质数 while pointer < size: sieve[pointer] = False pointer += i ret = [] # contains all the prime number within "size" for i in range(size): if sieve[i] == True: ret.append(str(i)) return ret if __name__ == '__main__': primes = primeSieve(100) primesString = ", ".join(primes) print("prime : ", primesString) ''' prime : 1, 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97 '''<|fim▁end|>
if num < 2: return False # 0, 1不是质数
<|file_name|>PrimeSieve.py<|end_file_name|><|fim▁begin|>import math def isPrime(num): <|fim_middle|> ve[0] = False sieve[1] = True # num为100时, 它是不可能有因子是大于50的. 比如说60 * ? = 100, 这是不可能的, 所以这里只要比较sqrt(), 平方根 boundary = int(math.sqrt(size)) + 1 for i in range(2, boundary): pointer = i * 2 # startPosition. 以3为例, 3其实是质数, 但它的位数6,9, 12, ...都不是质数 while pointer < size: sieve[pointer] = False pointer += i ret = [] # contains all the prime number within "size" for i in range(size): if sieve[i] == True: ret.append(str(i)) return ret if __name__ == '__main__': primes = primeSieve(100) primesString = ", ".join(primes) print("prime : ", primesString) ''' prime : 1, 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97 '''<|fim▁end|>
if num < 2: return False # 0, 1不是质数 # num为100时, 它是不可能有因子是大于50的. 比如说60 * ? = 100, 这是不可能的, 所以这里只要比较sqrt(), 平方根 boundary = int(math.sqrt(num)) + 1 for i in range(2, boundary): if num % i == 0: return False return True def primeSieve(size): sieve = [True] * size # 某格一为乘积, 就置为False sie
<|file_name|>PrimeSieve.py<|end_file_name|><|fim▁begin|>import math def isPrime(num): if num < 2: return False # 0, 1不是质数 # num为100时, 它是不可能有因子是大于50的. 比如说60 * ? = 100, 这是不可能的, 所以这里只要比较sqrt(), 平方根 boundary = int(math.sqrt(num)) + 1 for i in range(2, boundary): if num % i == 0: return False return True def primeSieve(size): sieve = [True] * size # 某格一为乘积, 就置为False sieve[0] = False sieve[1] =<|fim_middle|> 3, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97 '''<|fim▁end|>
True # num为100时, 它是不可能有因子是大于50的. 比如说60 * ? = 100, 这是不可能的, 所以这里只要比较sqrt(), 平方根 boundary = int(math.sqrt(size)) + 1 for i in range(2, boundary): pointer = i * 2 # startPosition. 以3为例, 3其实是质数, 但它的位数6,9, 12, ...都不是质数 while pointer < size: sieve[pointer] = False pointer += i ret = [] # contains all the prime number within "size" for i in range(size): if sieve[i] == True: ret.append(str(i)) return ret if __name__ == '__main__': primes = primeSieve(100) primesString = ", ".join(primes) print("prime : ", primesString) ''' prime : 1, 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 4
<|file_name|>PrimeSieve.py<|end_file_name|><|fim▁begin|>import math def isPrime(num): if num < 2: <|fim_middle|> num为100时, 它是不可能有因子是大于50的. 比如说60 * ? = 100, 这是不可能的, 所以这里只要比较sqrt(), 平方根 boundary = int(math.sqrt(num)) + 1 for i in range(2, boundary): if num % i == 0: return False return True def primeSieve(size): sieve = [True] * size # 某格一为乘积, 就置为False sieve[0] = False sieve[1] = True # num为100时, 它是不可能有因子是大于50的. 比如说60 * ? = 100, 这是不可能的, 所以这里只要比较sqrt(), 平方根 boundary = int(math.sqrt(size)) + 1 for i in range(2, boundary): pointer = i * 2 # startPosition. 以3为例, 3其实是质数, 但它的位数6,9, 12, ...都不是质数 while pointer < size: sieve[pointer] = False pointer += i ret = [] # contains all the prime number within "size" for i in range(size): if sieve[i] == True: ret.append(str(i)) return ret if __name__ == '__main__': primes = primeSieve(100) primesString = ", ".join(primes) print("prime : ", primesString) ''' prime : 1, 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97 '''<|fim▁end|>
return False # 0, 1不是质数 #
<|file_name|>PrimeSieve.py<|end_file_name|><|fim▁begin|>import math def isPrime(num): if num < 2: return False # 0, 1不是质数 # num为100时, 它是不可能有因子是大于50的. 比如说60 * ? = 100, 这是不可能的, 所以这里只要比较sqrt(), 平方根 boundary = int(math.sqrt(num)) + 1 for i in range(2, boundary): if num % i == 0: return False return True def primeSieve(size): sieve = [True] * si <|fim_middle|> 就置为False sieve[0] = False sieve[1] = True # num为100时, 它是不可能有因子是大于50的. 比如说60 * ? = 100, 这是不可能的, 所以这里只要比较sqrt(), 平方根 boundary = int(math.sqrt(size)) + 1 for i in range(2, boundary): pointer = i * 2 # startPosition. 以3为例, 3其实是质数, 但它的位数6,9, 12, ...都不是质数 while pointer < size: sieve[pointer] = False pointer += i ret = [] # contains all the prime number within "size" for i in range(size): if sieve[i] == True: ret.append(str(i)) return ret if __name__ == '__main__': primes = primeSieve(100) primesString = ", ".join(primes) print("prime : ", primesString) ''' prime : 1, 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97 '''<|fim▁end|>
ze # 某格一为乘积,
<|file_name|>PrimeSieve.py<|end_file_name|><|fim▁begin|>import math def isPrime(num): if num < 2: return False # 0, 1不是质数 # num为100时, 它是不可能有因子是大于50的. 比如说60 * ? = 100, 这是不可能的, 所以这里只要比较sqrt(), 平方根 boundary = int(math.sqrt(num)) + 1 for i in range(2, boundary): if num % i == 0: return False return True def primeSieve(size): sieve = [True] * size # 某格一为乘积, 就置为False sieve[0] = False sieve[1] = True # num为100时, 它是不可能有因子是大于50的. 比如说60 * ? = 100, 这是不可能的, 所以这里只要比较sqrt(), 平方根 boundary = int(math.sqrt(size)) + 1 for i in range(2, boundary): pointer = i * 2 # startPosition. 以3为例, 3其实是质数, 但它的位数6,9, 12, ...都不是质数 while pointer < size: sieve[pointer] = False pointer += i ret = [] # contains all the prime number within "size" for i in range(size): if sieve[i] == True: ret.append(str(i)) return ret if __name__ == '__main__': primes = primeSieve(100) primesString = ", ".join(primes) print("prime : ", primesString) ''' prime : 1, 2, 3, 5, 7, 11, <|fim_middle|> , 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97 '''<|fim▁end|>
13, 17, 19, 23, 29
<|file_name|>PrimeSieve.py<|end_file_name|><|fim▁begin|>import math def isPrime(num): if num < 2: return False # 0, 1不是质数 # num为100时, 它是不可能有因子是大于50的. 比如说60 * ? = 100, 这是不可能的, 所以这里只要比较sqrt(), 平方根 boundary = int(math.sqrt(num)) + 1 for i in range(2, boundary): if num % i == 0: return False return True def primeSieve(size): sieve = [True] * size # 某格一为乘积, 就置为False sieve[0] = False sieve[1] = True # num为100时, 它是不可能有因子是大于50的. 比如说60 * ? = 100, 这是不可能的, 所以这里只要比较sqrt(), 平方根 boundary = int(math.sqrt(size)) + 1 for i in range(2, boundary): pointer = i * 2 # startPosition. 以3为例, 3其实是质数, 但它的位数6,9, 12, ...都不是质数 while pointer < size: sieve[pointer] = False pointer += i ret = [] # contains all the prime number within "size" for i in range(size): if sieve[i] == True: ret.append(str(i)) return ret if __name__ == '__main__': primes = primeSieve(100) primesString = ", ".join(primes) print("prime : ", primesString) ''' prime : 1, 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, <|fim_middle|> <|fim▁end|>
83, 89, 97 '''
<|file_name|>PrimeSieve.py<|end_file_name|><|fim▁begin|>import math def <|fim_middle|>(num): if num < 2: return False # 0, 1不是质数 # num为100时, 它是不可能有因子是大于50的. 比如说60 * ? = 100, 这是不可能的, 所以这里只要比较sqrt(), 平方根 boundary = int(math.sqrt(num)) + 1 for i in range(2, boundary): if num % i == 0: return False return True def primeSieve(size): sieve = [True] * size # 某格一为乘积, 就置为False sieve[0] = False sieve[1] = True # num为100时, 它是不可能有因子是大于50的. 比如说60 * ? = 100, 这是不可能的, 所以这里只要比较sqrt(), 平方根 boundary = int(math.sqrt(size)) + 1 for i in range(2, boundary): pointer = i * 2 # startPosition. 以3为例, 3其实是质数, 但它的位数6,9, 12, ...都不是质数 while pointer < size: sieve[pointer] = False pointer += i ret = [] # contains all the prime number within "size" for i in range(size): if sieve[i] == True: ret.append(str(i)) return ret if __name__ == '__main__': primes = primeSieve(100) primesString = ", ".join(primes) print("prime : ", primesString) ''' prime : 1, 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97 '''<|fim▁end|>
isPrime
<|file_name|>PrimeSieve.py<|end_file_name|><|fim▁begin|>import math def isPrime(num): if num < 2: return False # 0, 1不是质数 # num为100时, 它是不可能有因子是大于50的. 比如说60 * ? = 100, 这是不可能的, 所以这里只要比较sqrt(), 平方根 boundary = int(math.sqrt(num)) + 1 for i in range(2, boundary): if num % i == 0: return False return True def primeSieve(size): sieve = [True] * size # 某格一为乘积, 就置为False sieve[0] <|fim_middle|> sieve[1] = True # num为100时, 它是不可能有因子是大于50的. 比如说60 * ? = 100, 这是不可能的, 所以这里只要比较sqrt(), 平方根 boundary = int(math.sqrt(size)) + 1 for i in range(2, boundary): pointer = i * 2 # startPosition. 以3为例, 3其实是质数, 但它的位数6,9, 12, ...都不是质数 while pointer < size: sieve[pointer] = False pointer += i ret = [] # contains all the prime number within "size" for i in range(size): if sieve[i] == True: ret.append(str(i)) return ret if __name__ == '__main__': primes = primeSieve(100) primesString = ", ".join(primes) print("prime : ", primesString) ''' prime : 1, 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97 '''<|fim▁end|>
= False
<|file_name|>test_climatology.py<|end_file_name|><|fim▁begin|># Copyright Iris contributors # # This file is part of Iris and is released under the LGPL license. # See COPYING and COPYING.LESSER in the root of the repository for full # licensing details. """Integration tests for loading and saving netcdf files.""" # Import iris.tests first so that some things can be initialised before # importing anything else. import iris.tests as tests from os.path import join as path_join, dirname, sep as os_sep import shutil<|fim▁hole|> import iris from iris.tests import stock class TestClimatology(iris.tests.IrisTest): reference_cdl_path = os_sep.join( [ dirname(tests.__file__), ( "results/integration/climatology/TestClimatology/" "reference_simpledata.cdl" ), ] ) @classmethod def _simple_cdl_string(cls): with open(cls.reference_cdl_path, "r") as f: cdl_content = f.read() # Add the expected CDL first line since this is removed from the # stored results file. cdl_content = "netcdf {\n" + cdl_content return cdl_content @staticmethod def _load_sanitised_cube(filepath): cube = iris.load_cube(filepath) # Remove attributes convention, if any. cube.attributes.pop("Conventions", None) # Remove any var-names. for coord in cube.coords(): coord.var_name = None cube.var_name = None return cube @classmethod def setUpClass(cls): # Create a temp directory for temp files. cls.temp_dir = tempfile.mkdtemp() cls.path_ref_cdl = path_join(cls.temp_dir, "standard.cdl") cls.path_ref_nc = path_join(cls.temp_dir, "standard.nc") # Create reference CDL file. with open(cls.path_ref_cdl, "w") as f_out: f_out.write(cls._simple_cdl_string()) # Create reference netCDF file from reference CDL. command = "ncgen -o {} {}".format(cls.path_ref_nc, cls.path_ref_cdl) check_call(command, shell=True) cls.path_temp_nc = path_join(cls.temp_dir, "tmp.nc") # Create reference cube. cls.cube_ref = stock.climatology_3d() @classmethod def tearDownClass(cls): # Destroy a temp directory for temp files. shutil.rmtree(cls.temp_dir) ############################################################################### # Round-trip tests def test_cube_to_cube(self): # Save reference cube to file, load cube from same file, test against # reference cube. iris.save(self.cube_ref, self.path_temp_nc) cube = self._load_sanitised_cube(self.path_temp_nc) self.assertEqual(cube, self.cube_ref) def test_file_to_file(self): # Load cube from reference file, save same cube to file, test against # reference CDL. cube = iris.load_cube(self.path_ref_nc) iris.save(cube, self.path_temp_nc) self.assertCDL( self.path_temp_nc, reference_filename=self.reference_cdl_path, flags="", ) # NOTE: # The saving half of the round-trip tests is tested in the # appropriate dedicated test class: # unit.fileformats.netcdf.test_Saver.Test_write.test_with_climatology . # The loading half has no equivalent dedicated location, so is tested # here as test_load_from_file. def test_load_from_file(self): # Create cube from file, test against reference cube. cube = self._load_sanitised_cube(self.path_ref_nc) self.assertEqual(cube, self.cube_ref) if __name__ == "__main__": tests.main()<|fim▁end|>
from subprocess import check_call import tempfile
<|file_name|>test_climatology.py<|end_file_name|><|fim▁begin|># Copyright Iris contributors # # This file is part of Iris and is released under the LGPL license. # See COPYING and COPYING.LESSER in the root of the repository for full # licensing details. """Integration tests for loading and saving netcdf files.""" # Import iris.tests first so that some things can be initialised before # importing anything else. import iris.tests as tests from os.path import join as path_join, dirname, sep as os_sep import shutil from subprocess import check_call import tempfile import iris from iris.tests import stock class TestClimatology(iris.tests.IrisTest): <|fim_middle|> if __name__ == "__main__": tests.main() <|fim▁end|>
reference_cdl_path = os_sep.join( [ dirname(tests.__file__), ( "results/integration/climatology/TestClimatology/" "reference_simpledata.cdl" ), ] ) @classmethod def _simple_cdl_string(cls): with open(cls.reference_cdl_path, "r") as f: cdl_content = f.read() # Add the expected CDL first line since this is removed from the # stored results file. cdl_content = "netcdf {\n" + cdl_content return cdl_content @staticmethod def _load_sanitised_cube(filepath): cube = iris.load_cube(filepath) # Remove attributes convention, if any. cube.attributes.pop("Conventions", None) # Remove any var-names. for coord in cube.coords(): coord.var_name = None cube.var_name = None return cube @classmethod def setUpClass(cls): # Create a temp directory for temp files. cls.temp_dir = tempfile.mkdtemp() cls.path_ref_cdl = path_join(cls.temp_dir, "standard.cdl") cls.path_ref_nc = path_join(cls.temp_dir, "standard.nc") # Create reference CDL file. with open(cls.path_ref_cdl, "w") as f_out: f_out.write(cls._simple_cdl_string()) # Create reference netCDF file from reference CDL. command = "ncgen -o {} {}".format(cls.path_ref_nc, cls.path_ref_cdl) check_call(command, shell=True) cls.path_temp_nc = path_join(cls.temp_dir, "tmp.nc") # Create reference cube. cls.cube_ref = stock.climatology_3d() @classmethod def tearDownClass(cls): # Destroy a temp directory for temp files. shutil.rmtree(cls.temp_dir) ############################################################################### # Round-trip tests def test_cube_to_cube(self): # Save reference cube to file, load cube from same file, test against # reference cube. iris.save(self.cube_ref, self.path_temp_nc) cube = self._load_sanitised_cube(self.path_temp_nc) self.assertEqual(cube, self.cube_ref) def test_file_to_file(self): # Load cube from reference file, save same cube to file, test against # reference CDL. cube = iris.load_cube(self.path_ref_nc) iris.save(cube, self.path_temp_nc) self.assertCDL( self.path_temp_nc, reference_filename=self.reference_cdl_path, flags="", ) # NOTE: # The saving half of the round-trip tests is tested in the # appropriate dedicated test class: # unit.fileformats.netcdf.test_Saver.Test_write.test_with_climatology . # The loading half has no equivalent dedicated location, so is tested # here as test_load_from_file. def test_load_from_file(self): # Create cube from file, test against reference cube. cube = self._load_sanitised_cube(self.path_ref_nc) self.assertEqual(cube, self.cube_ref)
<|file_name|>test_climatology.py<|end_file_name|><|fim▁begin|># Copyright Iris contributors # # This file is part of Iris and is released under the LGPL license. # See COPYING and COPYING.LESSER in the root of the repository for full # licensing details. """Integration tests for loading and saving netcdf files.""" # Import iris.tests first so that some things can be initialised before # importing anything else. import iris.tests as tests from os.path import join as path_join, dirname, sep as os_sep import shutil from subprocess import check_call import tempfile import iris from iris.tests import stock class TestClimatology(iris.tests.IrisTest): reference_cdl_path = os_sep.join( [ dirname(tests.__file__), ( "results/integration/climatology/TestClimatology/" "reference_simpledata.cdl" ), ] ) @classmethod def _simple_cdl_string(cls): <|fim_middle|> @staticmethod def _load_sanitised_cube(filepath): cube = iris.load_cube(filepath) # Remove attributes convention, if any. cube.attributes.pop("Conventions", None) # Remove any var-names. for coord in cube.coords(): coord.var_name = None cube.var_name = None return cube @classmethod def setUpClass(cls): # Create a temp directory for temp files. cls.temp_dir = tempfile.mkdtemp() cls.path_ref_cdl = path_join(cls.temp_dir, "standard.cdl") cls.path_ref_nc = path_join(cls.temp_dir, "standard.nc") # Create reference CDL file. with open(cls.path_ref_cdl, "w") as f_out: f_out.write(cls._simple_cdl_string()) # Create reference netCDF file from reference CDL. command = "ncgen -o {} {}".format(cls.path_ref_nc, cls.path_ref_cdl) check_call(command, shell=True) cls.path_temp_nc = path_join(cls.temp_dir, "tmp.nc") # Create reference cube. cls.cube_ref = stock.climatology_3d() @classmethod def tearDownClass(cls): # Destroy a temp directory for temp files. shutil.rmtree(cls.temp_dir) ############################################################################### # Round-trip tests def test_cube_to_cube(self): # Save reference cube to file, load cube from same file, test against # reference cube. iris.save(self.cube_ref, self.path_temp_nc) cube = self._load_sanitised_cube(self.path_temp_nc) self.assertEqual(cube, self.cube_ref) def test_file_to_file(self): # Load cube from reference file, save same cube to file, test against # reference CDL. cube = iris.load_cube(self.path_ref_nc) iris.save(cube, self.path_temp_nc) self.assertCDL( self.path_temp_nc, reference_filename=self.reference_cdl_path, flags="", ) # NOTE: # The saving half of the round-trip tests is tested in the # appropriate dedicated test class: # unit.fileformats.netcdf.test_Saver.Test_write.test_with_climatology . # The loading half has no equivalent dedicated location, so is tested # here as test_load_from_file. def test_load_from_file(self): # Create cube from file, test against reference cube. cube = self._load_sanitised_cube(self.path_ref_nc) self.assertEqual(cube, self.cube_ref) if __name__ == "__main__": tests.main() <|fim▁end|>
with open(cls.reference_cdl_path, "r") as f: cdl_content = f.read() # Add the expected CDL first line since this is removed from the # stored results file. cdl_content = "netcdf {\n" + cdl_content return cdl_content
<|file_name|>test_climatology.py<|end_file_name|><|fim▁begin|># Copyright Iris contributors # # This file is part of Iris and is released under the LGPL license. # See COPYING and COPYING.LESSER in the root of the repository for full # licensing details. """Integration tests for loading and saving netcdf files.""" # Import iris.tests first so that some things can be initialised before # importing anything else. import iris.tests as tests from os.path import join as path_join, dirname, sep as os_sep import shutil from subprocess import check_call import tempfile import iris from iris.tests import stock class TestClimatology(iris.tests.IrisTest): reference_cdl_path = os_sep.join( [ dirname(tests.__file__), ( "results/integration/climatology/TestClimatology/" "reference_simpledata.cdl" ), ] ) @classmethod def _simple_cdl_string(cls): with open(cls.reference_cdl_path, "r") as f: cdl_content = f.read() # Add the expected CDL first line since this is removed from the # stored results file. cdl_content = "netcdf {\n" + cdl_content return cdl_content @staticmethod def _load_sanitised_cube(filepath): <|fim_middle|> @classmethod def setUpClass(cls): # Create a temp directory for temp files. cls.temp_dir = tempfile.mkdtemp() cls.path_ref_cdl = path_join(cls.temp_dir, "standard.cdl") cls.path_ref_nc = path_join(cls.temp_dir, "standard.nc") # Create reference CDL file. with open(cls.path_ref_cdl, "w") as f_out: f_out.write(cls._simple_cdl_string()) # Create reference netCDF file from reference CDL. command = "ncgen -o {} {}".format(cls.path_ref_nc, cls.path_ref_cdl) check_call(command, shell=True) cls.path_temp_nc = path_join(cls.temp_dir, "tmp.nc") # Create reference cube. cls.cube_ref = stock.climatology_3d() @classmethod def tearDownClass(cls): # Destroy a temp directory for temp files. shutil.rmtree(cls.temp_dir) ############################################################################### # Round-trip tests def test_cube_to_cube(self): # Save reference cube to file, load cube from same file, test against # reference cube. iris.save(self.cube_ref, self.path_temp_nc) cube = self._load_sanitised_cube(self.path_temp_nc) self.assertEqual(cube, self.cube_ref) def test_file_to_file(self): # Load cube from reference file, save same cube to file, test against # reference CDL. cube = iris.load_cube(self.path_ref_nc) iris.save(cube, self.path_temp_nc) self.assertCDL( self.path_temp_nc, reference_filename=self.reference_cdl_path, flags="", ) # NOTE: # The saving half of the round-trip tests is tested in the # appropriate dedicated test class: # unit.fileformats.netcdf.test_Saver.Test_write.test_with_climatology . # The loading half has no equivalent dedicated location, so is tested # here as test_load_from_file. def test_load_from_file(self): # Create cube from file, test against reference cube. cube = self._load_sanitised_cube(self.path_ref_nc) self.assertEqual(cube, self.cube_ref) if __name__ == "__main__": tests.main() <|fim▁end|>
cube = iris.load_cube(filepath) # Remove attributes convention, if any. cube.attributes.pop("Conventions", None) # Remove any var-names. for coord in cube.coords(): coord.var_name = None cube.var_name = None return cube
<|file_name|>test_climatology.py<|end_file_name|><|fim▁begin|># Copyright Iris contributors # # This file is part of Iris and is released under the LGPL license. # See COPYING and COPYING.LESSER in the root of the repository for full # licensing details. """Integration tests for loading and saving netcdf files.""" # Import iris.tests first so that some things can be initialised before # importing anything else. import iris.tests as tests from os.path import join as path_join, dirname, sep as os_sep import shutil from subprocess import check_call import tempfile import iris from iris.tests import stock class TestClimatology(iris.tests.IrisTest): reference_cdl_path = os_sep.join( [ dirname(tests.__file__), ( "results/integration/climatology/TestClimatology/" "reference_simpledata.cdl" ), ] ) @classmethod def _simple_cdl_string(cls): with open(cls.reference_cdl_path, "r") as f: cdl_content = f.read() # Add the expected CDL first line since this is removed from the # stored results file. cdl_content = "netcdf {\n" + cdl_content return cdl_content @staticmethod def _load_sanitised_cube(filepath): cube = iris.load_cube(filepath) # Remove attributes convention, if any. cube.attributes.pop("Conventions", None) # Remove any var-names. for coord in cube.coords(): coord.var_name = None cube.var_name = None return cube @classmethod def setUpClass(cls): # Create a temp directory for temp files. <|fim_middle|> @classmethod def tearDownClass(cls): # Destroy a temp directory for temp files. shutil.rmtree(cls.temp_dir) ############################################################################### # Round-trip tests def test_cube_to_cube(self): # Save reference cube to file, load cube from same file, test against # reference cube. iris.save(self.cube_ref, self.path_temp_nc) cube = self._load_sanitised_cube(self.path_temp_nc) self.assertEqual(cube, self.cube_ref) def test_file_to_file(self): # Load cube from reference file, save same cube to file, test against # reference CDL. cube = iris.load_cube(self.path_ref_nc) iris.save(cube, self.path_temp_nc) self.assertCDL( self.path_temp_nc, reference_filename=self.reference_cdl_path, flags="", ) # NOTE: # The saving half of the round-trip tests is tested in the # appropriate dedicated test class: # unit.fileformats.netcdf.test_Saver.Test_write.test_with_climatology . # The loading half has no equivalent dedicated location, so is tested # here as test_load_from_file. def test_load_from_file(self): # Create cube from file, test against reference cube. cube = self._load_sanitised_cube(self.path_ref_nc) self.assertEqual(cube, self.cube_ref) if __name__ == "__main__": tests.main() <|fim▁end|>
cls.temp_dir = tempfile.mkdtemp() cls.path_ref_cdl = path_join(cls.temp_dir, "standard.cdl") cls.path_ref_nc = path_join(cls.temp_dir, "standard.nc") # Create reference CDL file. with open(cls.path_ref_cdl, "w") as f_out: f_out.write(cls._simple_cdl_string()) # Create reference netCDF file from reference CDL. command = "ncgen -o {} {}".format(cls.path_ref_nc, cls.path_ref_cdl) check_call(command, shell=True) cls.path_temp_nc = path_join(cls.temp_dir, "tmp.nc") # Create reference cube. cls.cube_ref = stock.climatology_3d()
<|file_name|>test_climatology.py<|end_file_name|><|fim▁begin|># Copyright Iris contributors # # This file is part of Iris and is released under the LGPL license. # See COPYING and COPYING.LESSER in the root of the repository for full # licensing details. """Integration tests for loading and saving netcdf files.""" # Import iris.tests first so that some things can be initialised before # importing anything else. import iris.tests as tests from os.path import join as path_join, dirname, sep as os_sep import shutil from subprocess import check_call import tempfile import iris from iris.tests import stock class TestClimatology(iris.tests.IrisTest): reference_cdl_path = os_sep.join( [ dirname(tests.__file__), ( "results/integration/climatology/TestClimatology/" "reference_simpledata.cdl" ), ] ) @classmethod def _simple_cdl_string(cls): with open(cls.reference_cdl_path, "r") as f: cdl_content = f.read() # Add the expected CDL first line since this is removed from the # stored results file. cdl_content = "netcdf {\n" + cdl_content return cdl_content @staticmethod def _load_sanitised_cube(filepath): cube = iris.load_cube(filepath) # Remove attributes convention, if any. cube.attributes.pop("Conventions", None) # Remove any var-names. for coord in cube.coords(): coord.var_name = None cube.var_name = None return cube @classmethod def setUpClass(cls): # Create a temp directory for temp files. cls.temp_dir = tempfile.mkdtemp() cls.path_ref_cdl = path_join(cls.temp_dir, "standard.cdl") cls.path_ref_nc = path_join(cls.temp_dir, "standard.nc") # Create reference CDL file. with open(cls.path_ref_cdl, "w") as f_out: f_out.write(cls._simple_cdl_string()) # Create reference netCDF file from reference CDL. command = "ncgen -o {} {}".format(cls.path_ref_nc, cls.path_ref_cdl) check_call(command, shell=True) cls.path_temp_nc = path_join(cls.temp_dir, "tmp.nc") # Create reference cube. cls.cube_ref = stock.climatology_3d() @classmethod def tearDownClass(cls): # Destroy a temp directory for temp files. <|fim_middle|> ############################################################################### # Round-trip tests def test_cube_to_cube(self): # Save reference cube to file, load cube from same file, test against # reference cube. iris.save(self.cube_ref, self.path_temp_nc) cube = self._load_sanitised_cube(self.path_temp_nc) self.assertEqual(cube, self.cube_ref) def test_file_to_file(self): # Load cube from reference file, save same cube to file, test against # reference CDL. cube = iris.load_cube(self.path_ref_nc) iris.save(cube, self.path_temp_nc) self.assertCDL( self.path_temp_nc, reference_filename=self.reference_cdl_path, flags="", ) # NOTE: # The saving half of the round-trip tests is tested in the # appropriate dedicated test class: # unit.fileformats.netcdf.test_Saver.Test_write.test_with_climatology . # The loading half has no equivalent dedicated location, so is tested # here as test_load_from_file. def test_load_from_file(self): # Create cube from file, test against reference cube. cube = self._load_sanitised_cube(self.path_ref_nc) self.assertEqual(cube, self.cube_ref) if __name__ == "__main__": tests.main() <|fim▁end|>
shutil.rmtree(cls.temp_dir)
<|file_name|>test_climatology.py<|end_file_name|><|fim▁begin|># Copyright Iris contributors # # This file is part of Iris and is released under the LGPL license. # See COPYING and COPYING.LESSER in the root of the repository for full # licensing details. """Integration tests for loading and saving netcdf files.""" # Import iris.tests first so that some things can be initialised before # importing anything else. import iris.tests as tests from os.path import join as path_join, dirname, sep as os_sep import shutil from subprocess import check_call import tempfile import iris from iris.tests import stock class TestClimatology(iris.tests.IrisTest): reference_cdl_path = os_sep.join( [ dirname(tests.__file__), ( "results/integration/climatology/TestClimatology/" "reference_simpledata.cdl" ), ] ) @classmethod def _simple_cdl_string(cls): with open(cls.reference_cdl_path, "r") as f: cdl_content = f.read() # Add the expected CDL first line since this is removed from the # stored results file. cdl_content = "netcdf {\n" + cdl_content return cdl_content @staticmethod def _load_sanitised_cube(filepath): cube = iris.load_cube(filepath) # Remove attributes convention, if any. cube.attributes.pop("Conventions", None) # Remove any var-names. for coord in cube.coords(): coord.var_name = None cube.var_name = None return cube @classmethod def setUpClass(cls): # Create a temp directory for temp files. cls.temp_dir = tempfile.mkdtemp() cls.path_ref_cdl = path_join(cls.temp_dir, "standard.cdl") cls.path_ref_nc = path_join(cls.temp_dir, "standard.nc") # Create reference CDL file. with open(cls.path_ref_cdl, "w") as f_out: f_out.write(cls._simple_cdl_string()) # Create reference netCDF file from reference CDL. command = "ncgen -o {} {}".format(cls.path_ref_nc, cls.path_ref_cdl) check_call(command, shell=True) cls.path_temp_nc = path_join(cls.temp_dir, "tmp.nc") # Create reference cube. cls.cube_ref = stock.climatology_3d() @classmethod def tearDownClass(cls): # Destroy a temp directory for temp files. shutil.rmtree(cls.temp_dir) ############################################################################### # Round-trip tests def test_cube_to_cube(self): # Save reference cube to file, load cube from same file, test against # reference cube. <|fim_middle|> def test_file_to_file(self): # Load cube from reference file, save same cube to file, test against # reference CDL. cube = iris.load_cube(self.path_ref_nc) iris.save(cube, self.path_temp_nc) self.assertCDL( self.path_temp_nc, reference_filename=self.reference_cdl_path, flags="", ) # NOTE: # The saving half of the round-trip tests is tested in the # appropriate dedicated test class: # unit.fileformats.netcdf.test_Saver.Test_write.test_with_climatology . # The loading half has no equivalent dedicated location, so is tested # here as test_load_from_file. def test_load_from_file(self): # Create cube from file, test against reference cube. cube = self._load_sanitised_cube(self.path_ref_nc) self.assertEqual(cube, self.cube_ref) if __name__ == "__main__": tests.main() <|fim▁end|>
iris.save(self.cube_ref, self.path_temp_nc) cube = self._load_sanitised_cube(self.path_temp_nc) self.assertEqual(cube, self.cube_ref)
<|file_name|>test_climatology.py<|end_file_name|><|fim▁begin|># Copyright Iris contributors # # This file is part of Iris and is released under the LGPL license. # See COPYING and COPYING.LESSER in the root of the repository for full # licensing details. """Integration tests for loading and saving netcdf files.""" # Import iris.tests first so that some things can be initialised before # importing anything else. import iris.tests as tests from os.path import join as path_join, dirname, sep as os_sep import shutil from subprocess import check_call import tempfile import iris from iris.tests import stock class TestClimatology(iris.tests.IrisTest): reference_cdl_path = os_sep.join( [ dirname(tests.__file__), ( "results/integration/climatology/TestClimatology/" "reference_simpledata.cdl" ), ] ) @classmethod def _simple_cdl_string(cls): with open(cls.reference_cdl_path, "r") as f: cdl_content = f.read() # Add the expected CDL first line since this is removed from the # stored results file. cdl_content = "netcdf {\n" + cdl_content return cdl_content @staticmethod def _load_sanitised_cube(filepath): cube = iris.load_cube(filepath) # Remove attributes convention, if any. cube.attributes.pop("Conventions", None) # Remove any var-names. for coord in cube.coords(): coord.var_name = None cube.var_name = None return cube @classmethod def setUpClass(cls): # Create a temp directory for temp files. cls.temp_dir = tempfile.mkdtemp() cls.path_ref_cdl = path_join(cls.temp_dir, "standard.cdl") cls.path_ref_nc = path_join(cls.temp_dir, "standard.nc") # Create reference CDL file. with open(cls.path_ref_cdl, "w") as f_out: f_out.write(cls._simple_cdl_string()) # Create reference netCDF file from reference CDL. command = "ncgen -o {} {}".format(cls.path_ref_nc, cls.path_ref_cdl) check_call(command, shell=True) cls.path_temp_nc = path_join(cls.temp_dir, "tmp.nc") # Create reference cube. cls.cube_ref = stock.climatology_3d() @classmethod def tearDownClass(cls): # Destroy a temp directory for temp files. shutil.rmtree(cls.temp_dir) ############################################################################### # Round-trip tests def test_cube_to_cube(self): # Save reference cube to file, load cube from same file, test against # reference cube. iris.save(self.cube_ref, self.path_temp_nc) cube = self._load_sanitised_cube(self.path_temp_nc) self.assertEqual(cube, self.cube_ref) def test_file_to_file(self): # Load cube from reference file, save same cube to file, test against # reference CDL. <|fim_middle|> # NOTE: # The saving half of the round-trip tests is tested in the # appropriate dedicated test class: # unit.fileformats.netcdf.test_Saver.Test_write.test_with_climatology . # The loading half has no equivalent dedicated location, so is tested # here as test_load_from_file. def test_load_from_file(self): # Create cube from file, test against reference cube. cube = self._load_sanitised_cube(self.path_ref_nc) self.assertEqual(cube, self.cube_ref) if __name__ == "__main__": tests.main() <|fim▁end|>
cube = iris.load_cube(self.path_ref_nc) iris.save(cube, self.path_temp_nc) self.assertCDL( self.path_temp_nc, reference_filename=self.reference_cdl_path, flags="", )
<|file_name|>test_climatology.py<|end_file_name|><|fim▁begin|># Copyright Iris contributors # # This file is part of Iris and is released under the LGPL license. # See COPYING and COPYING.LESSER in the root of the repository for full # licensing details. """Integration tests for loading and saving netcdf files.""" # Import iris.tests first so that some things can be initialised before # importing anything else. import iris.tests as tests from os.path import join as path_join, dirname, sep as os_sep import shutil from subprocess import check_call import tempfile import iris from iris.tests import stock class TestClimatology(iris.tests.IrisTest): reference_cdl_path = os_sep.join( [ dirname(tests.__file__), ( "results/integration/climatology/TestClimatology/" "reference_simpledata.cdl" ), ] ) @classmethod def _simple_cdl_string(cls): with open(cls.reference_cdl_path, "r") as f: cdl_content = f.read() # Add the expected CDL first line since this is removed from the # stored results file. cdl_content = "netcdf {\n" + cdl_content return cdl_content @staticmethod def _load_sanitised_cube(filepath): cube = iris.load_cube(filepath) # Remove attributes convention, if any. cube.attributes.pop("Conventions", None) # Remove any var-names. for coord in cube.coords(): coord.var_name = None cube.var_name = None return cube @classmethod def setUpClass(cls): # Create a temp directory for temp files. cls.temp_dir = tempfile.mkdtemp() cls.path_ref_cdl = path_join(cls.temp_dir, "standard.cdl") cls.path_ref_nc = path_join(cls.temp_dir, "standard.nc") # Create reference CDL file. with open(cls.path_ref_cdl, "w") as f_out: f_out.write(cls._simple_cdl_string()) # Create reference netCDF file from reference CDL. command = "ncgen -o {} {}".format(cls.path_ref_nc, cls.path_ref_cdl) check_call(command, shell=True) cls.path_temp_nc = path_join(cls.temp_dir, "tmp.nc") # Create reference cube. cls.cube_ref = stock.climatology_3d() @classmethod def tearDownClass(cls): # Destroy a temp directory for temp files. shutil.rmtree(cls.temp_dir) ############################################################################### # Round-trip tests def test_cube_to_cube(self): # Save reference cube to file, load cube from same file, test against # reference cube. iris.save(self.cube_ref, self.path_temp_nc) cube = self._load_sanitised_cube(self.path_temp_nc) self.assertEqual(cube, self.cube_ref) def test_file_to_file(self): # Load cube from reference file, save same cube to file, test against # reference CDL. cube = iris.load_cube(self.path_ref_nc) iris.save(cube, self.path_temp_nc) self.assertCDL( self.path_temp_nc, reference_filename=self.reference_cdl_path, flags="", ) # NOTE: # The saving half of the round-trip tests is tested in the # appropriate dedicated test class: # unit.fileformats.netcdf.test_Saver.Test_write.test_with_climatology . # The loading half has no equivalent dedicated location, so is tested # here as test_load_from_file. def test_load_from_file(self): # Create cube from file, test against reference cube. <|fim_middle|> if __name__ == "__main__": tests.main() <|fim▁end|>
cube = self._load_sanitised_cube(self.path_ref_nc) self.assertEqual(cube, self.cube_ref)
<|file_name|>test_climatology.py<|end_file_name|><|fim▁begin|># Copyright Iris contributors # # This file is part of Iris and is released under the LGPL license. # See COPYING and COPYING.LESSER in the root of the repository for full # licensing details. """Integration tests for loading and saving netcdf files.""" # Import iris.tests first so that some things can be initialised before # importing anything else. import iris.tests as tests from os.path import join as path_join, dirname, sep as os_sep import shutil from subprocess import check_call import tempfile import iris from iris.tests import stock class TestClimatology(iris.tests.IrisTest): reference_cdl_path = os_sep.join( [ dirname(tests.__file__), ( "results/integration/climatology/TestClimatology/" "reference_simpledata.cdl" ), ] ) @classmethod def _simple_cdl_string(cls): with open(cls.reference_cdl_path, "r") as f: cdl_content = f.read() # Add the expected CDL first line since this is removed from the # stored results file. cdl_content = "netcdf {\n" + cdl_content return cdl_content @staticmethod def _load_sanitised_cube(filepath): cube = iris.load_cube(filepath) # Remove attributes convention, if any. cube.attributes.pop("Conventions", None) # Remove any var-names. for coord in cube.coords(): coord.var_name = None cube.var_name = None return cube @classmethod def setUpClass(cls): # Create a temp directory for temp files. cls.temp_dir = tempfile.mkdtemp() cls.path_ref_cdl = path_join(cls.temp_dir, "standard.cdl") cls.path_ref_nc = path_join(cls.temp_dir, "standard.nc") # Create reference CDL file. with open(cls.path_ref_cdl, "w") as f_out: f_out.write(cls._simple_cdl_string()) # Create reference netCDF file from reference CDL. command = "ncgen -o {} {}".format(cls.path_ref_nc, cls.path_ref_cdl) check_call(command, shell=True) cls.path_temp_nc = path_join(cls.temp_dir, "tmp.nc") # Create reference cube. cls.cube_ref = stock.climatology_3d() @classmethod def tearDownClass(cls): # Destroy a temp directory for temp files. shutil.rmtree(cls.temp_dir) ############################################################################### # Round-trip tests def test_cube_to_cube(self): # Save reference cube to file, load cube from same file, test against # reference cube. iris.save(self.cube_ref, self.path_temp_nc) cube = self._load_sanitised_cube(self.path_temp_nc) self.assertEqual(cube, self.cube_ref) def test_file_to_file(self): # Load cube from reference file, save same cube to file, test against # reference CDL. cube = iris.load_cube(self.path_ref_nc) iris.save(cube, self.path_temp_nc) self.assertCDL( self.path_temp_nc, reference_filename=self.reference_cdl_path, flags="", ) # NOTE: # The saving half of the round-trip tests is tested in the # appropriate dedicated test class: # unit.fileformats.netcdf.test_Saver.Test_write.test_with_climatology . # The loading half has no equivalent dedicated location, so is tested # here as test_load_from_file. def test_load_from_file(self): # Create cube from file, test against reference cube. cube = self._load_sanitised_cube(self.path_ref_nc) self.assertEqual(cube, self.cube_ref) if __name__ == "__main__": <|fim_middle|> <|fim▁end|>
tests.main()
<|file_name|>test_climatology.py<|end_file_name|><|fim▁begin|># Copyright Iris contributors # # This file is part of Iris and is released under the LGPL license. # See COPYING and COPYING.LESSER in the root of the repository for full # licensing details. """Integration tests for loading and saving netcdf files.""" # Import iris.tests first so that some things can be initialised before # importing anything else. import iris.tests as tests from os.path import join as path_join, dirname, sep as os_sep import shutil from subprocess import check_call import tempfile import iris from iris.tests import stock class TestClimatology(iris.tests.IrisTest): reference_cdl_path = os_sep.join( [ dirname(tests.__file__), ( "results/integration/climatology/TestClimatology/" "reference_simpledata.cdl" ), ] ) @classmethod def <|fim_middle|>(cls): with open(cls.reference_cdl_path, "r") as f: cdl_content = f.read() # Add the expected CDL first line since this is removed from the # stored results file. cdl_content = "netcdf {\n" + cdl_content return cdl_content @staticmethod def _load_sanitised_cube(filepath): cube = iris.load_cube(filepath) # Remove attributes convention, if any. cube.attributes.pop("Conventions", None) # Remove any var-names. for coord in cube.coords(): coord.var_name = None cube.var_name = None return cube @classmethod def setUpClass(cls): # Create a temp directory for temp files. cls.temp_dir = tempfile.mkdtemp() cls.path_ref_cdl = path_join(cls.temp_dir, "standard.cdl") cls.path_ref_nc = path_join(cls.temp_dir, "standard.nc") # Create reference CDL file. with open(cls.path_ref_cdl, "w") as f_out: f_out.write(cls._simple_cdl_string()) # Create reference netCDF file from reference CDL. command = "ncgen -o {} {}".format(cls.path_ref_nc, cls.path_ref_cdl) check_call(command, shell=True) cls.path_temp_nc = path_join(cls.temp_dir, "tmp.nc") # Create reference cube. cls.cube_ref = stock.climatology_3d() @classmethod def tearDownClass(cls): # Destroy a temp directory for temp files. shutil.rmtree(cls.temp_dir) ############################################################################### # Round-trip tests def test_cube_to_cube(self): # Save reference cube to file, load cube from same file, test against # reference cube. iris.save(self.cube_ref, self.path_temp_nc) cube = self._load_sanitised_cube(self.path_temp_nc) self.assertEqual(cube, self.cube_ref) def test_file_to_file(self): # Load cube from reference file, save same cube to file, test against # reference CDL. cube = iris.load_cube(self.path_ref_nc) iris.save(cube, self.path_temp_nc) self.assertCDL( self.path_temp_nc, reference_filename=self.reference_cdl_path, flags="", ) # NOTE: # The saving half of the round-trip tests is tested in the # appropriate dedicated test class: # unit.fileformats.netcdf.test_Saver.Test_write.test_with_climatology . # The loading half has no equivalent dedicated location, so is tested # here as test_load_from_file. def test_load_from_file(self): # Create cube from file, test against reference cube. cube = self._load_sanitised_cube(self.path_ref_nc) self.assertEqual(cube, self.cube_ref) if __name__ == "__main__": tests.main() <|fim▁end|>
_simple_cdl_string
<|file_name|>test_climatology.py<|end_file_name|><|fim▁begin|># Copyright Iris contributors # # This file is part of Iris and is released under the LGPL license. # See COPYING and COPYING.LESSER in the root of the repository for full # licensing details. """Integration tests for loading and saving netcdf files.""" # Import iris.tests first so that some things can be initialised before # importing anything else. import iris.tests as tests from os.path import join as path_join, dirname, sep as os_sep import shutil from subprocess import check_call import tempfile import iris from iris.tests import stock class TestClimatology(iris.tests.IrisTest): reference_cdl_path = os_sep.join( [ dirname(tests.__file__), ( "results/integration/climatology/TestClimatology/" "reference_simpledata.cdl" ), ] ) @classmethod def _simple_cdl_string(cls): with open(cls.reference_cdl_path, "r") as f: cdl_content = f.read() # Add the expected CDL first line since this is removed from the # stored results file. cdl_content = "netcdf {\n" + cdl_content return cdl_content @staticmethod def <|fim_middle|>(filepath): cube = iris.load_cube(filepath) # Remove attributes convention, if any. cube.attributes.pop("Conventions", None) # Remove any var-names. for coord in cube.coords(): coord.var_name = None cube.var_name = None return cube @classmethod def setUpClass(cls): # Create a temp directory for temp files. cls.temp_dir = tempfile.mkdtemp() cls.path_ref_cdl = path_join(cls.temp_dir, "standard.cdl") cls.path_ref_nc = path_join(cls.temp_dir, "standard.nc") # Create reference CDL file. with open(cls.path_ref_cdl, "w") as f_out: f_out.write(cls._simple_cdl_string()) # Create reference netCDF file from reference CDL. command = "ncgen -o {} {}".format(cls.path_ref_nc, cls.path_ref_cdl) check_call(command, shell=True) cls.path_temp_nc = path_join(cls.temp_dir, "tmp.nc") # Create reference cube. cls.cube_ref = stock.climatology_3d() @classmethod def tearDownClass(cls): # Destroy a temp directory for temp files. shutil.rmtree(cls.temp_dir) ############################################################################### # Round-trip tests def test_cube_to_cube(self): # Save reference cube to file, load cube from same file, test against # reference cube. iris.save(self.cube_ref, self.path_temp_nc) cube = self._load_sanitised_cube(self.path_temp_nc) self.assertEqual(cube, self.cube_ref) def test_file_to_file(self): # Load cube from reference file, save same cube to file, test against # reference CDL. cube = iris.load_cube(self.path_ref_nc) iris.save(cube, self.path_temp_nc) self.assertCDL( self.path_temp_nc, reference_filename=self.reference_cdl_path, flags="", ) # NOTE: # The saving half of the round-trip tests is tested in the # appropriate dedicated test class: # unit.fileformats.netcdf.test_Saver.Test_write.test_with_climatology . # The loading half has no equivalent dedicated location, so is tested # here as test_load_from_file. def test_load_from_file(self): # Create cube from file, test against reference cube. cube = self._load_sanitised_cube(self.path_ref_nc) self.assertEqual(cube, self.cube_ref) if __name__ == "__main__": tests.main() <|fim▁end|>
_load_sanitised_cube
<|file_name|>test_climatology.py<|end_file_name|><|fim▁begin|># Copyright Iris contributors # # This file is part of Iris and is released under the LGPL license. # See COPYING and COPYING.LESSER in the root of the repository for full # licensing details. """Integration tests for loading and saving netcdf files.""" # Import iris.tests first so that some things can be initialised before # importing anything else. import iris.tests as tests from os.path import join as path_join, dirname, sep as os_sep import shutil from subprocess import check_call import tempfile import iris from iris.tests import stock class TestClimatology(iris.tests.IrisTest): reference_cdl_path = os_sep.join( [ dirname(tests.__file__), ( "results/integration/climatology/TestClimatology/" "reference_simpledata.cdl" ), ] ) @classmethod def _simple_cdl_string(cls): with open(cls.reference_cdl_path, "r") as f: cdl_content = f.read() # Add the expected CDL first line since this is removed from the # stored results file. cdl_content = "netcdf {\n" + cdl_content return cdl_content @staticmethod def _load_sanitised_cube(filepath): cube = iris.load_cube(filepath) # Remove attributes convention, if any. cube.attributes.pop("Conventions", None) # Remove any var-names. for coord in cube.coords(): coord.var_name = None cube.var_name = None return cube @classmethod def <|fim_middle|>(cls): # Create a temp directory for temp files. cls.temp_dir = tempfile.mkdtemp() cls.path_ref_cdl = path_join(cls.temp_dir, "standard.cdl") cls.path_ref_nc = path_join(cls.temp_dir, "standard.nc") # Create reference CDL file. with open(cls.path_ref_cdl, "w") as f_out: f_out.write(cls._simple_cdl_string()) # Create reference netCDF file from reference CDL. command = "ncgen -o {} {}".format(cls.path_ref_nc, cls.path_ref_cdl) check_call(command, shell=True) cls.path_temp_nc = path_join(cls.temp_dir, "tmp.nc") # Create reference cube. cls.cube_ref = stock.climatology_3d() @classmethod def tearDownClass(cls): # Destroy a temp directory for temp files. shutil.rmtree(cls.temp_dir) ############################################################################### # Round-trip tests def test_cube_to_cube(self): # Save reference cube to file, load cube from same file, test against # reference cube. iris.save(self.cube_ref, self.path_temp_nc) cube = self._load_sanitised_cube(self.path_temp_nc) self.assertEqual(cube, self.cube_ref) def test_file_to_file(self): # Load cube from reference file, save same cube to file, test against # reference CDL. cube = iris.load_cube(self.path_ref_nc) iris.save(cube, self.path_temp_nc) self.assertCDL( self.path_temp_nc, reference_filename=self.reference_cdl_path, flags="", ) # NOTE: # The saving half of the round-trip tests is tested in the # appropriate dedicated test class: # unit.fileformats.netcdf.test_Saver.Test_write.test_with_climatology . # The loading half has no equivalent dedicated location, so is tested # here as test_load_from_file. def test_load_from_file(self): # Create cube from file, test against reference cube. cube = self._load_sanitised_cube(self.path_ref_nc) self.assertEqual(cube, self.cube_ref) if __name__ == "__main__": tests.main() <|fim▁end|>
setUpClass
<|file_name|>test_climatology.py<|end_file_name|><|fim▁begin|># Copyright Iris contributors # # This file is part of Iris and is released under the LGPL license. # See COPYING and COPYING.LESSER in the root of the repository for full # licensing details. """Integration tests for loading and saving netcdf files.""" # Import iris.tests first so that some things can be initialised before # importing anything else. import iris.tests as tests from os.path import join as path_join, dirname, sep as os_sep import shutil from subprocess import check_call import tempfile import iris from iris.tests import stock class TestClimatology(iris.tests.IrisTest): reference_cdl_path = os_sep.join( [ dirname(tests.__file__), ( "results/integration/climatology/TestClimatology/" "reference_simpledata.cdl" ), ] ) @classmethod def _simple_cdl_string(cls): with open(cls.reference_cdl_path, "r") as f: cdl_content = f.read() # Add the expected CDL first line since this is removed from the # stored results file. cdl_content = "netcdf {\n" + cdl_content return cdl_content @staticmethod def _load_sanitised_cube(filepath): cube = iris.load_cube(filepath) # Remove attributes convention, if any. cube.attributes.pop("Conventions", None) # Remove any var-names. for coord in cube.coords(): coord.var_name = None cube.var_name = None return cube @classmethod def setUpClass(cls): # Create a temp directory for temp files. cls.temp_dir = tempfile.mkdtemp() cls.path_ref_cdl = path_join(cls.temp_dir, "standard.cdl") cls.path_ref_nc = path_join(cls.temp_dir, "standard.nc") # Create reference CDL file. with open(cls.path_ref_cdl, "w") as f_out: f_out.write(cls._simple_cdl_string()) # Create reference netCDF file from reference CDL. command = "ncgen -o {} {}".format(cls.path_ref_nc, cls.path_ref_cdl) check_call(command, shell=True) cls.path_temp_nc = path_join(cls.temp_dir, "tmp.nc") # Create reference cube. cls.cube_ref = stock.climatology_3d() @classmethod def <|fim_middle|>(cls): # Destroy a temp directory for temp files. shutil.rmtree(cls.temp_dir) ############################################################################### # Round-trip tests def test_cube_to_cube(self): # Save reference cube to file, load cube from same file, test against # reference cube. iris.save(self.cube_ref, self.path_temp_nc) cube = self._load_sanitised_cube(self.path_temp_nc) self.assertEqual(cube, self.cube_ref) def test_file_to_file(self): # Load cube from reference file, save same cube to file, test against # reference CDL. cube = iris.load_cube(self.path_ref_nc) iris.save(cube, self.path_temp_nc) self.assertCDL( self.path_temp_nc, reference_filename=self.reference_cdl_path, flags="", ) # NOTE: # The saving half of the round-trip tests is tested in the # appropriate dedicated test class: # unit.fileformats.netcdf.test_Saver.Test_write.test_with_climatology . # The loading half has no equivalent dedicated location, so is tested # here as test_load_from_file. def test_load_from_file(self): # Create cube from file, test against reference cube. cube = self._load_sanitised_cube(self.path_ref_nc) self.assertEqual(cube, self.cube_ref) if __name__ == "__main__": tests.main() <|fim▁end|>
tearDownClass
<|file_name|>test_climatology.py<|end_file_name|><|fim▁begin|># Copyright Iris contributors # # This file is part of Iris and is released under the LGPL license. # See COPYING and COPYING.LESSER in the root of the repository for full # licensing details. """Integration tests for loading and saving netcdf files.""" # Import iris.tests first so that some things can be initialised before # importing anything else. import iris.tests as tests from os.path import join as path_join, dirname, sep as os_sep import shutil from subprocess import check_call import tempfile import iris from iris.tests import stock class TestClimatology(iris.tests.IrisTest): reference_cdl_path = os_sep.join( [ dirname(tests.__file__), ( "results/integration/climatology/TestClimatology/" "reference_simpledata.cdl" ), ] ) @classmethod def _simple_cdl_string(cls): with open(cls.reference_cdl_path, "r") as f: cdl_content = f.read() # Add the expected CDL first line since this is removed from the # stored results file. cdl_content = "netcdf {\n" + cdl_content return cdl_content @staticmethod def _load_sanitised_cube(filepath): cube = iris.load_cube(filepath) # Remove attributes convention, if any. cube.attributes.pop("Conventions", None) # Remove any var-names. for coord in cube.coords(): coord.var_name = None cube.var_name = None return cube @classmethod def setUpClass(cls): # Create a temp directory for temp files. cls.temp_dir = tempfile.mkdtemp() cls.path_ref_cdl = path_join(cls.temp_dir, "standard.cdl") cls.path_ref_nc = path_join(cls.temp_dir, "standard.nc") # Create reference CDL file. with open(cls.path_ref_cdl, "w") as f_out: f_out.write(cls._simple_cdl_string()) # Create reference netCDF file from reference CDL. command = "ncgen -o {} {}".format(cls.path_ref_nc, cls.path_ref_cdl) check_call(command, shell=True) cls.path_temp_nc = path_join(cls.temp_dir, "tmp.nc") # Create reference cube. cls.cube_ref = stock.climatology_3d() @classmethod def tearDownClass(cls): # Destroy a temp directory for temp files. shutil.rmtree(cls.temp_dir) ############################################################################### # Round-trip tests def <|fim_middle|>(self): # Save reference cube to file, load cube from same file, test against # reference cube. iris.save(self.cube_ref, self.path_temp_nc) cube = self._load_sanitised_cube(self.path_temp_nc) self.assertEqual(cube, self.cube_ref) def test_file_to_file(self): # Load cube from reference file, save same cube to file, test against # reference CDL. cube = iris.load_cube(self.path_ref_nc) iris.save(cube, self.path_temp_nc) self.assertCDL( self.path_temp_nc, reference_filename=self.reference_cdl_path, flags="", ) # NOTE: # The saving half of the round-trip tests is tested in the # appropriate dedicated test class: # unit.fileformats.netcdf.test_Saver.Test_write.test_with_climatology . # The loading half has no equivalent dedicated location, so is tested # here as test_load_from_file. def test_load_from_file(self): # Create cube from file, test against reference cube. cube = self._load_sanitised_cube(self.path_ref_nc) self.assertEqual(cube, self.cube_ref) if __name__ == "__main__": tests.main() <|fim▁end|>
test_cube_to_cube
<|file_name|>test_climatology.py<|end_file_name|><|fim▁begin|># Copyright Iris contributors # # This file is part of Iris and is released under the LGPL license. # See COPYING and COPYING.LESSER in the root of the repository for full # licensing details. """Integration tests for loading and saving netcdf files.""" # Import iris.tests first so that some things can be initialised before # importing anything else. import iris.tests as tests from os.path import join as path_join, dirname, sep as os_sep import shutil from subprocess import check_call import tempfile import iris from iris.tests import stock class TestClimatology(iris.tests.IrisTest): reference_cdl_path = os_sep.join( [ dirname(tests.__file__), ( "results/integration/climatology/TestClimatology/" "reference_simpledata.cdl" ), ] ) @classmethod def _simple_cdl_string(cls): with open(cls.reference_cdl_path, "r") as f: cdl_content = f.read() # Add the expected CDL first line since this is removed from the # stored results file. cdl_content = "netcdf {\n" + cdl_content return cdl_content @staticmethod def _load_sanitised_cube(filepath): cube = iris.load_cube(filepath) # Remove attributes convention, if any. cube.attributes.pop("Conventions", None) # Remove any var-names. for coord in cube.coords(): coord.var_name = None cube.var_name = None return cube @classmethod def setUpClass(cls): # Create a temp directory for temp files. cls.temp_dir = tempfile.mkdtemp() cls.path_ref_cdl = path_join(cls.temp_dir, "standard.cdl") cls.path_ref_nc = path_join(cls.temp_dir, "standard.nc") # Create reference CDL file. with open(cls.path_ref_cdl, "w") as f_out: f_out.write(cls._simple_cdl_string()) # Create reference netCDF file from reference CDL. command = "ncgen -o {} {}".format(cls.path_ref_nc, cls.path_ref_cdl) check_call(command, shell=True) cls.path_temp_nc = path_join(cls.temp_dir, "tmp.nc") # Create reference cube. cls.cube_ref = stock.climatology_3d() @classmethod def tearDownClass(cls): # Destroy a temp directory for temp files. shutil.rmtree(cls.temp_dir) ############################################################################### # Round-trip tests def test_cube_to_cube(self): # Save reference cube to file, load cube from same file, test against # reference cube. iris.save(self.cube_ref, self.path_temp_nc) cube = self._load_sanitised_cube(self.path_temp_nc) self.assertEqual(cube, self.cube_ref) def <|fim_middle|>(self): # Load cube from reference file, save same cube to file, test against # reference CDL. cube = iris.load_cube(self.path_ref_nc) iris.save(cube, self.path_temp_nc) self.assertCDL( self.path_temp_nc, reference_filename=self.reference_cdl_path, flags="", ) # NOTE: # The saving half of the round-trip tests is tested in the # appropriate dedicated test class: # unit.fileformats.netcdf.test_Saver.Test_write.test_with_climatology . # The loading half has no equivalent dedicated location, so is tested # here as test_load_from_file. def test_load_from_file(self): # Create cube from file, test against reference cube. cube = self._load_sanitised_cube(self.path_ref_nc) self.assertEqual(cube, self.cube_ref) if __name__ == "__main__": tests.main() <|fim▁end|>
test_file_to_file
<|file_name|>test_climatology.py<|end_file_name|><|fim▁begin|># Copyright Iris contributors # # This file is part of Iris and is released under the LGPL license. # See COPYING and COPYING.LESSER in the root of the repository for full # licensing details. """Integration tests for loading and saving netcdf files.""" # Import iris.tests first so that some things can be initialised before # importing anything else. import iris.tests as tests from os.path import join as path_join, dirname, sep as os_sep import shutil from subprocess import check_call import tempfile import iris from iris.tests import stock class TestClimatology(iris.tests.IrisTest): reference_cdl_path = os_sep.join( [ dirname(tests.__file__), ( "results/integration/climatology/TestClimatology/" "reference_simpledata.cdl" ), ] ) @classmethod def _simple_cdl_string(cls): with open(cls.reference_cdl_path, "r") as f: cdl_content = f.read() # Add the expected CDL first line since this is removed from the # stored results file. cdl_content = "netcdf {\n" + cdl_content return cdl_content @staticmethod def _load_sanitised_cube(filepath): cube = iris.load_cube(filepath) # Remove attributes convention, if any. cube.attributes.pop("Conventions", None) # Remove any var-names. for coord in cube.coords(): coord.var_name = None cube.var_name = None return cube @classmethod def setUpClass(cls): # Create a temp directory for temp files. cls.temp_dir = tempfile.mkdtemp() cls.path_ref_cdl = path_join(cls.temp_dir, "standard.cdl") cls.path_ref_nc = path_join(cls.temp_dir, "standard.nc") # Create reference CDL file. with open(cls.path_ref_cdl, "w") as f_out: f_out.write(cls._simple_cdl_string()) # Create reference netCDF file from reference CDL. command = "ncgen -o {} {}".format(cls.path_ref_nc, cls.path_ref_cdl) check_call(command, shell=True) cls.path_temp_nc = path_join(cls.temp_dir, "tmp.nc") # Create reference cube. cls.cube_ref = stock.climatology_3d() @classmethod def tearDownClass(cls): # Destroy a temp directory for temp files. shutil.rmtree(cls.temp_dir) ############################################################################### # Round-trip tests def test_cube_to_cube(self): # Save reference cube to file, load cube from same file, test against # reference cube. iris.save(self.cube_ref, self.path_temp_nc) cube = self._load_sanitised_cube(self.path_temp_nc) self.assertEqual(cube, self.cube_ref) def test_file_to_file(self): # Load cube from reference file, save same cube to file, test against # reference CDL. cube = iris.load_cube(self.path_ref_nc) iris.save(cube, self.path_temp_nc) self.assertCDL( self.path_temp_nc, reference_filename=self.reference_cdl_path, flags="", ) # NOTE: # The saving half of the round-trip tests is tested in the # appropriate dedicated test class: # unit.fileformats.netcdf.test_Saver.Test_write.test_with_climatology . # The loading half has no equivalent dedicated location, so is tested # here as test_load_from_file. def <|fim_middle|>(self): # Create cube from file, test against reference cube. cube = self._load_sanitised_cube(self.path_ref_nc) self.assertEqual(cube, self.cube_ref) if __name__ == "__main__": tests.main() <|fim▁end|>
test_load_from_file
<|file_name|>admin_form_part.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- # This file is part of Shoop. # # Copyright (c) 2012-2015, Shoop Ltd. All rights reserved.<|fim▁hole|> from django import forms from django.utils.translation import ugettext_lazy as _ from shoop.admin.form_part import FormPart, TemplatedFormDef from shoop.core.models import Shop from shoop.discount_pricing.models import DiscountedProductPrice class DiscountPricingForm(forms.Form): def __init__(self, **kwargs): self.product = kwargs.pop("product") super(DiscountPricingForm, self).__init__(**kwargs) self.shops = [] if self.product: self._build_fields() def _build_fields(self): self.shops = list(Shop.objects.all()) prices_by_shop_and_group = dict( (shop_id, price) for (shop_id, price) in DiscountedProductPrice.objects.filter(product=self.product) .values_list("shop_id", "price_value") ) for shop in self.shops: name = self._get_field_name(shop) price = prices_by_shop_and_group.get(shop.id) price_field = forms.DecimalField( min_value=0, initial=price, label=_("Price (%s)") % shop, required=False ) self.fields[name] = price_field def _get_field_name(self, shop): return "s_%d" % shop.id def _process_single_save(self, shop): name = self._get_field_name(shop) value = self.cleaned_data.get(name) clear = (value is None or value < 0) if clear: DiscountedProductPrice.objects.filter(product=self.product, shop=shop).delete() else: (spp, created) = DiscountedProductPrice.objects.get_or_create( product=self.product, shop=shop, defaults={'price_value': value}) if not created: spp.price_value = value spp.save() def save(self): if not self.has_changed(): # No changes, so no need to do anything. return for shop in self.shops: self._process_single_save(shop) def get_shop_field(self, shop): name = self._get_field_name(shop) return self[name] class DiscountPricingFormPart(FormPart): priority = 10 def get_form_defs(self): yield TemplatedFormDef( name="discount_pricing", form_class=DiscountPricingForm, template_name="shoop/admin/discount_pricing/form_part.jinja", required=False, kwargs={"product": self.object} ) def form_valid(self, form): form["discount_pricing"].save()<|fim▁end|>
# # This source code is licensed under the AGPLv3 license found in the # LICENSE file in the root directory of this source tree. from __future__ import unicode_literals
<|file_name|>admin_form_part.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- # This file is part of Shoop. # # Copyright (c) 2012-2015, Shoop Ltd. All rights reserved. # # This source code is licensed under the AGPLv3 license found in the # LICENSE file in the root directory of this source tree. from __future__ import unicode_literals from django import forms from django.utils.translation import ugettext_lazy as _ from shoop.admin.form_part import FormPart, TemplatedFormDef from shoop.core.models import Shop from shoop.discount_pricing.models import DiscountedProductPrice class DiscountPricingForm(forms.Form): <|fim_middle|> class DiscountPricingFormPart(FormPart): priority = 10 def get_form_defs(self): yield TemplatedFormDef( name="discount_pricing", form_class=DiscountPricingForm, template_name="shoop/admin/discount_pricing/form_part.jinja", required=False, kwargs={"product": self.object} ) def form_valid(self, form): form["discount_pricing"].save() <|fim▁end|>
def __init__(self, **kwargs): self.product = kwargs.pop("product") super(DiscountPricingForm, self).__init__(**kwargs) self.shops = [] if self.product: self._build_fields() def _build_fields(self): self.shops = list(Shop.objects.all()) prices_by_shop_and_group = dict( (shop_id, price) for (shop_id, price) in DiscountedProductPrice.objects.filter(product=self.product) .values_list("shop_id", "price_value") ) for shop in self.shops: name = self._get_field_name(shop) price = prices_by_shop_and_group.get(shop.id) price_field = forms.DecimalField( min_value=0, initial=price, label=_("Price (%s)") % shop, required=False ) self.fields[name] = price_field def _get_field_name(self, shop): return "s_%d" % shop.id def _process_single_save(self, shop): name = self._get_field_name(shop) value = self.cleaned_data.get(name) clear = (value is None or value < 0) if clear: DiscountedProductPrice.objects.filter(product=self.product, shop=shop).delete() else: (spp, created) = DiscountedProductPrice.objects.get_or_create( product=self.product, shop=shop, defaults={'price_value': value}) if not created: spp.price_value = value spp.save() def save(self): if not self.has_changed(): # No changes, so no need to do anything. return for shop in self.shops: self._process_single_save(shop) def get_shop_field(self, shop): name = self._get_field_name(shop) return self[name]
<|file_name|>admin_form_part.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- # This file is part of Shoop. # # Copyright (c) 2012-2015, Shoop Ltd. All rights reserved. # # This source code is licensed under the AGPLv3 license found in the # LICENSE file in the root directory of this source tree. from __future__ import unicode_literals from django import forms from django.utils.translation import ugettext_lazy as _ from shoop.admin.form_part import FormPart, TemplatedFormDef from shoop.core.models import Shop from shoop.discount_pricing.models import DiscountedProductPrice class DiscountPricingForm(forms.Form): def __init__(self, **kwargs): <|fim_middle|> def _build_fields(self): self.shops = list(Shop.objects.all()) prices_by_shop_and_group = dict( (shop_id, price) for (shop_id, price) in DiscountedProductPrice.objects.filter(product=self.product) .values_list("shop_id", "price_value") ) for shop in self.shops: name = self._get_field_name(shop) price = prices_by_shop_and_group.get(shop.id) price_field = forms.DecimalField( min_value=0, initial=price, label=_("Price (%s)") % shop, required=False ) self.fields[name] = price_field def _get_field_name(self, shop): return "s_%d" % shop.id def _process_single_save(self, shop): name = self._get_field_name(shop) value = self.cleaned_data.get(name) clear = (value is None or value < 0) if clear: DiscountedProductPrice.objects.filter(product=self.product, shop=shop).delete() else: (spp, created) = DiscountedProductPrice.objects.get_or_create( product=self.product, shop=shop, defaults={'price_value': value}) if not created: spp.price_value = value spp.save() def save(self): if not self.has_changed(): # No changes, so no need to do anything. return for shop in self.shops: self._process_single_save(shop) def get_shop_field(self, shop): name = self._get_field_name(shop) return self[name] class DiscountPricingFormPart(FormPart): priority = 10 def get_form_defs(self): yield TemplatedFormDef( name="discount_pricing", form_class=DiscountPricingForm, template_name="shoop/admin/discount_pricing/form_part.jinja", required=False, kwargs={"product": self.object} ) def form_valid(self, form): form["discount_pricing"].save() <|fim▁end|>
self.product = kwargs.pop("product") super(DiscountPricingForm, self).__init__(**kwargs) self.shops = [] if self.product: self._build_fields()
<|file_name|>admin_form_part.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- # This file is part of Shoop. # # Copyright (c) 2012-2015, Shoop Ltd. All rights reserved. # # This source code is licensed under the AGPLv3 license found in the # LICENSE file in the root directory of this source tree. from __future__ import unicode_literals from django import forms from django.utils.translation import ugettext_lazy as _ from shoop.admin.form_part import FormPart, TemplatedFormDef from shoop.core.models import Shop from shoop.discount_pricing.models import DiscountedProductPrice class DiscountPricingForm(forms.Form): def __init__(self, **kwargs): self.product = kwargs.pop("product") super(DiscountPricingForm, self).__init__(**kwargs) self.shops = [] if self.product: self._build_fields() def _build_fields(self): <|fim_middle|> def _get_field_name(self, shop): return "s_%d" % shop.id def _process_single_save(self, shop): name = self._get_field_name(shop) value = self.cleaned_data.get(name) clear = (value is None or value < 0) if clear: DiscountedProductPrice.objects.filter(product=self.product, shop=shop).delete() else: (spp, created) = DiscountedProductPrice.objects.get_or_create( product=self.product, shop=shop, defaults={'price_value': value}) if not created: spp.price_value = value spp.save() def save(self): if not self.has_changed(): # No changes, so no need to do anything. return for shop in self.shops: self._process_single_save(shop) def get_shop_field(self, shop): name = self._get_field_name(shop) return self[name] class DiscountPricingFormPart(FormPart): priority = 10 def get_form_defs(self): yield TemplatedFormDef( name="discount_pricing", form_class=DiscountPricingForm, template_name="shoop/admin/discount_pricing/form_part.jinja", required=False, kwargs={"product": self.object} ) def form_valid(self, form): form["discount_pricing"].save() <|fim▁end|>
self.shops = list(Shop.objects.all()) prices_by_shop_and_group = dict( (shop_id, price) for (shop_id, price) in DiscountedProductPrice.objects.filter(product=self.product) .values_list("shop_id", "price_value") ) for shop in self.shops: name = self._get_field_name(shop) price = prices_by_shop_and_group.get(shop.id) price_field = forms.DecimalField( min_value=0, initial=price, label=_("Price (%s)") % shop, required=False ) self.fields[name] = price_field
<|file_name|>admin_form_part.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- # This file is part of Shoop. # # Copyright (c) 2012-2015, Shoop Ltd. All rights reserved. # # This source code is licensed under the AGPLv3 license found in the # LICENSE file in the root directory of this source tree. from __future__ import unicode_literals from django import forms from django.utils.translation import ugettext_lazy as _ from shoop.admin.form_part import FormPart, TemplatedFormDef from shoop.core.models import Shop from shoop.discount_pricing.models import DiscountedProductPrice class DiscountPricingForm(forms.Form): def __init__(self, **kwargs): self.product = kwargs.pop("product") super(DiscountPricingForm, self).__init__(**kwargs) self.shops = [] if self.product: self._build_fields() def _build_fields(self): self.shops = list(Shop.objects.all()) prices_by_shop_and_group = dict( (shop_id, price) for (shop_id, price) in DiscountedProductPrice.objects.filter(product=self.product) .values_list("shop_id", "price_value") ) for shop in self.shops: name = self._get_field_name(shop) price = prices_by_shop_and_group.get(shop.id) price_field = forms.DecimalField( min_value=0, initial=price, label=_("Price (%s)") % shop, required=False ) self.fields[name] = price_field def _get_field_name(self, shop): <|fim_middle|> def _process_single_save(self, shop): name = self._get_field_name(shop) value = self.cleaned_data.get(name) clear = (value is None or value < 0) if clear: DiscountedProductPrice.objects.filter(product=self.product, shop=shop).delete() else: (spp, created) = DiscountedProductPrice.objects.get_or_create( product=self.product, shop=shop, defaults={'price_value': value}) if not created: spp.price_value = value spp.save() def save(self): if not self.has_changed(): # No changes, so no need to do anything. return for shop in self.shops: self._process_single_save(shop) def get_shop_field(self, shop): name = self._get_field_name(shop) return self[name] class DiscountPricingFormPart(FormPart): priority = 10 def get_form_defs(self): yield TemplatedFormDef( name="discount_pricing", form_class=DiscountPricingForm, template_name="shoop/admin/discount_pricing/form_part.jinja", required=False, kwargs={"product": self.object} ) def form_valid(self, form): form["discount_pricing"].save() <|fim▁end|>
return "s_%d" % shop.id
<|file_name|>admin_form_part.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- # This file is part of Shoop. # # Copyright (c) 2012-2015, Shoop Ltd. All rights reserved. # # This source code is licensed under the AGPLv3 license found in the # LICENSE file in the root directory of this source tree. from __future__ import unicode_literals from django import forms from django.utils.translation import ugettext_lazy as _ from shoop.admin.form_part import FormPart, TemplatedFormDef from shoop.core.models import Shop from shoop.discount_pricing.models import DiscountedProductPrice class DiscountPricingForm(forms.Form): def __init__(self, **kwargs): self.product = kwargs.pop("product") super(DiscountPricingForm, self).__init__(**kwargs) self.shops = [] if self.product: self._build_fields() def _build_fields(self): self.shops = list(Shop.objects.all()) prices_by_shop_and_group = dict( (shop_id, price) for (shop_id, price) in DiscountedProductPrice.objects.filter(product=self.product) .values_list("shop_id", "price_value") ) for shop in self.shops: name = self._get_field_name(shop) price = prices_by_shop_and_group.get(shop.id) price_field = forms.DecimalField( min_value=0, initial=price, label=_("Price (%s)") % shop, required=False ) self.fields[name] = price_field def _get_field_name(self, shop): return "s_%d" % shop.id def _process_single_save(self, shop): <|fim_middle|> def save(self): if not self.has_changed(): # No changes, so no need to do anything. return for shop in self.shops: self._process_single_save(shop) def get_shop_field(self, shop): name = self._get_field_name(shop) return self[name] class DiscountPricingFormPart(FormPart): priority = 10 def get_form_defs(self): yield TemplatedFormDef( name="discount_pricing", form_class=DiscountPricingForm, template_name="shoop/admin/discount_pricing/form_part.jinja", required=False, kwargs={"product": self.object} ) def form_valid(self, form): form["discount_pricing"].save() <|fim▁end|>
name = self._get_field_name(shop) value = self.cleaned_data.get(name) clear = (value is None or value < 0) if clear: DiscountedProductPrice.objects.filter(product=self.product, shop=shop).delete() else: (spp, created) = DiscountedProductPrice.objects.get_or_create( product=self.product, shop=shop, defaults={'price_value': value}) if not created: spp.price_value = value spp.save()
<|file_name|>admin_form_part.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- # This file is part of Shoop. # # Copyright (c) 2012-2015, Shoop Ltd. All rights reserved. # # This source code is licensed under the AGPLv3 license found in the # LICENSE file in the root directory of this source tree. from __future__ import unicode_literals from django import forms from django.utils.translation import ugettext_lazy as _ from shoop.admin.form_part import FormPart, TemplatedFormDef from shoop.core.models import Shop from shoop.discount_pricing.models import DiscountedProductPrice class DiscountPricingForm(forms.Form): def __init__(self, **kwargs): self.product = kwargs.pop("product") super(DiscountPricingForm, self).__init__(**kwargs) self.shops = [] if self.product: self._build_fields() def _build_fields(self): self.shops = list(Shop.objects.all()) prices_by_shop_and_group = dict( (shop_id, price) for (shop_id, price) in DiscountedProductPrice.objects.filter(product=self.product) .values_list("shop_id", "price_value") ) for shop in self.shops: name = self._get_field_name(shop) price = prices_by_shop_and_group.get(shop.id) price_field = forms.DecimalField( min_value=0, initial=price, label=_("Price (%s)") % shop, required=False ) self.fields[name] = price_field def _get_field_name(self, shop): return "s_%d" % shop.id def _process_single_save(self, shop): name = self._get_field_name(shop) value = self.cleaned_data.get(name) clear = (value is None or value < 0) if clear: DiscountedProductPrice.objects.filter(product=self.product, shop=shop).delete() else: (spp, created) = DiscountedProductPrice.objects.get_or_create( product=self.product, shop=shop, defaults={'price_value': value}) if not created: spp.price_value = value spp.save() def save(self): <|fim_middle|> def get_shop_field(self, shop): name = self._get_field_name(shop) return self[name] class DiscountPricingFormPart(FormPart): priority = 10 def get_form_defs(self): yield TemplatedFormDef( name="discount_pricing", form_class=DiscountPricingForm, template_name="shoop/admin/discount_pricing/form_part.jinja", required=False, kwargs={"product": self.object} ) def form_valid(self, form): form["discount_pricing"].save() <|fim▁end|>
if not self.has_changed(): # No changes, so no need to do anything. return for shop in self.shops: self._process_single_save(shop)
<|file_name|>admin_form_part.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- # This file is part of Shoop. # # Copyright (c) 2012-2015, Shoop Ltd. All rights reserved. # # This source code is licensed under the AGPLv3 license found in the # LICENSE file in the root directory of this source tree. from __future__ import unicode_literals from django import forms from django.utils.translation import ugettext_lazy as _ from shoop.admin.form_part import FormPart, TemplatedFormDef from shoop.core.models import Shop from shoop.discount_pricing.models import DiscountedProductPrice class DiscountPricingForm(forms.Form): def __init__(self, **kwargs): self.product = kwargs.pop("product") super(DiscountPricingForm, self).__init__(**kwargs) self.shops = [] if self.product: self._build_fields() def _build_fields(self): self.shops = list(Shop.objects.all()) prices_by_shop_and_group = dict( (shop_id, price) for (shop_id, price) in DiscountedProductPrice.objects.filter(product=self.product) .values_list("shop_id", "price_value") ) for shop in self.shops: name = self._get_field_name(shop) price = prices_by_shop_and_group.get(shop.id) price_field = forms.DecimalField( min_value=0, initial=price, label=_("Price (%s)") % shop, required=False ) self.fields[name] = price_field def _get_field_name(self, shop): return "s_%d" % shop.id def _process_single_save(self, shop): name = self._get_field_name(shop) value = self.cleaned_data.get(name) clear = (value is None or value < 0) if clear: DiscountedProductPrice.objects.filter(product=self.product, shop=shop).delete() else: (spp, created) = DiscountedProductPrice.objects.get_or_create( product=self.product, shop=shop, defaults={'price_value': value}) if not created: spp.price_value = value spp.save() def save(self): if not self.has_changed(): # No changes, so no need to do anything. return for shop in self.shops: self._process_single_save(shop) def get_shop_field(self, shop): <|fim_middle|> class DiscountPricingFormPart(FormPart): priority = 10 def get_form_defs(self): yield TemplatedFormDef( name="discount_pricing", form_class=DiscountPricingForm, template_name="shoop/admin/discount_pricing/form_part.jinja", required=False, kwargs={"product": self.object} ) def form_valid(self, form): form["discount_pricing"].save() <|fim▁end|>
name = self._get_field_name(shop) return self[name]
<|file_name|>admin_form_part.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- # This file is part of Shoop. # # Copyright (c) 2012-2015, Shoop Ltd. All rights reserved. # # This source code is licensed under the AGPLv3 license found in the # LICENSE file in the root directory of this source tree. from __future__ import unicode_literals from django import forms from django.utils.translation import ugettext_lazy as _ from shoop.admin.form_part import FormPart, TemplatedFormDef from shoop.core.models import Shop from shoop.discount_pricing.models import DiscountedProductPrice class DiscountPricingForm(forms.Form): def __init__(self, **kwargs): self.product = kwargs.pop("product") super(DiscountPricingForm, self).__init__(**kwargs) self.shops = [] if self.product: self._build_fields() def _build_fields(self): self.shops = list(Shop.objects.all()) prices_by_shop_and_group = dict( (shop_id, price) for (shop_id, price) in DiscountedProductPrice.objects.filter(product=self.product) .values_list("shop_id", "price_value") ) for shop in self.shops: name = self._get_field_name(shop) price = prices_by_shop_and_group.get(shop.id) price_field = forms.DecimalField( min_value=0, initial=price, label=_("Price (%s)") % shop, required=False ) self.fields[name] = price_field def _get_field_name(self, shop): return "s_%d" % shop.id def _process_single_save(self, shop): name = self._get_field_name(shop) value = self.cleaned_data.get(name) clear = (value is None or value < 0) if clear: DiscountedProductPrice.objects.filter(product=self.product, shop=shop).delete() else: (spp, created) = DiscountedProductPrice.objects.get_or_create( product=self.product, shop=shop, defaults={'price_value': value}) if not created: spp.price_value = value spp.save() def save(self): if not self.has_changed(): # No changes, so no need to do anything. return for shop in self.shops: self._process_single_save(shop) def get_shop_field(self, shop): name = self._get_field_name(shop) return self[name] class DiscountPricingFormPart(FormPart): <|fim_middle|> <|fim▁end|>
priority = 10 def get_form_defs(self): yield TemplatedFormDef( name="discount_pricing", form_class=DiscountPricingForm, template_name="shoop/admin/discount_pricing/form_part.jinja", required=False, kwargs={"product": self.object} ) def form_valid(self, form): form["discount_pricing"].save()
<|file_name|>admin_form_part.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- # This file is part of Shoop. # # Copyright (c) 2012-2015, Shoop Ltd. All rights reserved. # # This source code is licensed under the AGPLv3 license found in the # LICENSE file in the root directory of this source tree. from __future__ import unicode_literals from django import forms from django.utils.translation import ugettext_lazy as _ from shoop.admin.form_part import FormPart, TemplatedFormDef from shoop.core.models import Shop from shoop.discount_pricing.models import DiscountedProductPrice class DiscountPricingForm(forms.Form): def __init__(self, **kwargs): self.product = kwargs.pop("product") super(DiscountPricingForm, self).__init__(**kwargs) self.shops = [] if self.product: self._build_fields() def _build_fields(self): self.shops = list(Shop.objects.all()) prices_by_shop_and_group = dict( (shop_id, price) for (shop_id, price) in DiscountedProductPrice.objects.filter(product=self.product) .values_list("shop_id", "price_value") ) for shop in self.shops: name = self._get_field_name(shop) price = prices_by_shop_and_group.get(shop.id) price_field = forms.DecimalField( min_value=0, initial=price, label=_("Price (%s)") % shop, required=False ) self.fields[name] = price_field def _get_field_name(self, shop): return "s_%d" % shop.id def _process_single_save(self, shop): name = self._get_field_name(shop) value = self.cleaned_data.get(name) clear = (value is None or value < 0) if clear: DiscountedProductPrice.objects.filter(product=self.product, shop=shop).delete() else: (spp, created) = DiscountedProductPrice.objects.get_or_create( product=self.product, shop=shop, defaults={'price_value': value}) if not created: spp.price_value = value spp.save() def save(self): if not self.has_changed(): # No changes, so no need to do anything. return for shop in self.shops: self._process_single_save(shop) def get_shop_field(self, shop): name = self._get_field_name(shop) return self[name] class DiscountPricingFormPart(FormPart): priority = 10 def get_form_defs(self): <|fim_middle|> def form_valid(self, form): form["discount_pricing"].save() <|fim▁end|>
yield TemplatedFormDef( name="discount_pricing", form_class=DiscountPricingForm, template_name="shoop/admin/discount_pricing/form_part.jinja", required=False, kwargs={"product": self.object} )
<|file_name|>admin_form_part.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- # This file is part of Shoop. # # Copyright (c) 2012-2015, Shoop Ltd. All rights reserved. # # This source code is licensed under the AGPLv3 license found in the # LICENSE file in the root directory of this source tree. from __future__ import unicode_literals from django import forms from django.utils.translation import ugettext_lazy as _ from shoop.admin.form_part import FormPart, TemplatedFormDef from shoop.core.models import Shop from shoop.discount_pricing.models import DiscountedProductPrice class DiscountPricingForm(forms.Form): def __init__(self, **kwargs): self.product = kwargs.pop("product") super(DiscountPricingForm, self).__init__(**kwargs) self.shops = [] if self.product: self._build_fields() def _build_fields(self): self.shops = list(Shop.objects.all()) prices_by_shop_and_group = dict( (shop_id, price) for (shop_id, price) in DiscountedProductPrice.objects.filter(product=self.product) .values_list("shop_id", "price_value") ) for shop in self.shops: name = self._get_field_name(shop) price = prices_by_shop_and_group.get(shop.id) price_field = forms.DecimalField( min_value=0, initial=price, label=_("Price (%s)") % shop, required=False ) self.fields[name] = price_field def _get_field_name(self, shop): return "s_%d" % shop.id def _process_single_save(self, shop): name = self._get_field_name(shop) value = self.cleaned_data.get(name) clear = (value is None or value < 0) if clear: DiscountedProductPrice.objects.filter(product=self.product, shop=shop).delete() else: (spp, created) = DiscountedProductPrice.objects.get_or_create( product=self.product, shop=shop, defaults={'price_value': value}) if not created: spp.price_value = value spp.save() def save(self): if not self.has_changed(): # No changes, so no need to do anything. return for shop in self.shops: self._process_single_save(shop) def get_shop_field(self, shop): name = self._get_field_name(shop) return self[name] class DiscountPricingFormPart(FormPart): priority = 10 def get_form_defs(self): yield TemplatedFormDef( name="discount_pricing", form_class=DiscountPricingForm, template_name="shoop/admin/discount_pricing/form_part.jinja", required=False, kwargs={"product": self.object} ) def form_valid(self, form): <|fim_middle|> <|fim▁end|>
form["discount_pricing"].save()
<|file_name|>admin_form_part.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- # This file is part of Shoop. # # Copyright (c) 2012-2015, Shoop Ltd. All rights reserved. # # This source code is licensed under the AGPLv3 license found in the # LICENSE file in the root directory of this source tree. from __future__ import unicode_literals from django import forms from django.utils.translation import ugettext_lazy as _ from shoop.admin.form_part import FormPart, TemplatedFormDef from shoop.core.models import Shop from shoop.discount_pricing.models import DiscountedProductPrice class DiscountPricingForm(forms.Form): def __init__(self, **kwargs): self.product = kwargs.pop("product") super(DiscountPricingForm, self).__init__(**kwargs) self.shops = [] if self.product: <|fim_middle|> def _build_fields(self): self.shops = list(Shop.objects.all()) prices_by_shop_and_group = dict( (shop_id, price) for (shop_id, price) in DiscountedProductPrice.objects.filter(product=self.product) .values_list("shop_id", "price_value") ) for shop in self.shops: name = self._get_field_name(shop) price = prices_by_shop_and_group.get(shop.id) price_field = forms.DecimalField( min_value=0, initial=price, label=_("Price (%s)") % shop, required=False ) self.fields[name] = price_field def _get_field_name(self, shop): return "s_%d" % shop.id def _process_single_save(self, shop): name = self._get_field_name(shop) value = self.cleaned_data.get(name) clear = (value is None or value < 0) if clear: DiscountedProductPrice.objects.filter(product=self.product, shop=shop).delete() else: (spp, created) = DiscountedProductPrice.objects.get_or_create( product=self.product, shop=shop, defaults={'price_value': value}) if not created: spp.price_value = value spp.save() def save(self): if not self.has_changed(): # No changes, so no need to do anything. return for shop in self.shops: self._process_single_save(shop) def get_shop_field(self, shop): name = self._get_field_name(shop) return self[name] class DiscountPricingFormPart(FormPart): priority = 10 def get_form_defs(self): yield TemplatedFormDef( name="discount_pricing", form_class=DiscountPricingForm, template_name="shoop/admin/discount_pricing/form_part.jinja", required=False, kwargs={"product": self.object} ) def form_valid(self, form): form["discount_pricing"].save() <|fim▁end|>
self._build_fields()
<|file_name|>admin_form_part.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- # This file is part of Shoop. # # Copyright (c) 2012-2015, Shoop Ltd. All rights reserved. # # This source code is licensed under the AGPLv3 license found in the # LICENSE file in the root directory of this source tree. from __future__ import unicode_literals from django import forms from django.utils.translation import ugettext_lazy as _ from shoop.admin.form_part import FormPart, TemplatedFormDef from shoop.core.models import Shop from shoop.discount_pricing.models import DiscountedProductPrice class DiscountPricingForm(forms.Form): def __init__(self, **kwargs): self.product = kwargs.pop("product") super(DiscountPricingForm, self).__init__(**kwargs) self.shops = [] if self.product: self._build_fields() def _build_fields(self): self.shops = list(Shop.objects.all()) prices_by_shop_and_group = dict( (shop_id, price) for (shop_id, price) in DiscountedProductPrice.objects.filter(product=self.product) .values_list("shop_id", "price_value") ) for shop in self.shops: name = self._get_field_name(shop) price = prices_by_shop_and_group.get(shop.id) price_field = forms.DecimalField( min_value=0, initial=price, label=_("Price (%s)") % shop, required=False ) self.fields[name] = price_field def _get_field_name(self, shop): return "s_%d" % shop.id def _process_single_save(self, shop): name = self._get_field_name(shop) value = self.cleaned_data.get(name) clear = (value is None or value < 0) if clear: <|fim_middle|> else: (spp, created) = DiscountedProductPrice.objects.get_or_create( product=self.product, shop=shop, defaults={'price_value': value}) if not created: spp.price_value = value spp.save() def save(self): if not self.has_changed(): # No changes, so no need to do anything. return for shop in self.shops: self._process_single_save(shop) def get_shop_field(self, shop): name = self._get_field_name(shop) return self[name] class DiscountPricingFormPart(FormPart): priority = 10 def get_form_defs(self): yield TemplatedFormDef( name="discount_pricing", form_class=DiscountPricingForm, template_name="shoop/admin/discount_pricing/form_part.jinja", required=False, kwargs={"product": self.object} ) def form_valid(self, form): form["discount_pricing"].save() <|fim▁end|>
DiscountedProductPrice.objects.filter(product=self.product, shop=shop).delete()
<|file_name|>admin_form_part.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- # This file is part of Shoop. # # Copyright (c) 2012-2015, Shoop Ltd. All rights reserved. # # This source code is licensed under the AGPLv3 license found in the # LICENSE file in the root directory of this source tree. from __future__ import unicode_literals from django import forms from django.utils.translation import ugettext_lazy as _ from shoop.admin.form_part import FormPart, TemplatedFormDef from shoop.core.models import Shop from shoop.discount_pricing.models import DiscountedProductPrice class DiscountPricingForm(forms.Form): def __init__(self, **kwargs): self.product = kwargs.pop("product") super(DiscountPricingForm, self).__init__(**kwargs) self.shops = [] if self.product: self._build_fields() def _build_fields(self): self.shops = list(Shop.objects.all()) prices_by_shop_and_group = dict( (shop_id, price) for (shop_id, price) in DiscountedProductPrice.objects.filter(product=self.product) .values_list("shop_id", "price_value") ) for shop in self.shops: name = self._get_field_name(shop) price = prices_by_shop_and_group.get(shop.id) price_field = forms.DecimalField( min_value=0, initial=price, label=_("Price (%s)") % shop, required=False ) self.fields[name] = price_field def _get_field_name(self, shop): return "s_%d" % shop.id def _process_single_save(self, shop): name = self._get_field_name(shop) value = self.cleaned_data.get(name) clear = (value is None or value < 0) if clear: DiscountedProductPrice.objects.filter(product=self.product, shop=shop).delete() else: <|fim_middle|> def save(self): if not self.has_changed(): # No changes, so no need to do anything. return for shop in self.shops: self._process_single_save(shop) def get_shop_field(self, shop): name = self._get_field_name(shop) return self[name] class DiscountPricingFormPart(FormPart): priority = 10 def get_form_defs(self): yield TemplatedFormDef( name="discount_pricing", form_class=DiscountPricingForm, template_name="shoop/admin/discount_pricing/form_part.jinja", required=False, kwargs={"product": self.object} ) def form_valid(self, form): form["discount_pricing"].save() <|fim▁end|>
(spp, created) = DiscountedProductPrice.objects.get_or_create( product=self.product, shop=shop, defaults={'price_value': value}) if not created: spp.price_value = value spp.save()
<|file_name|>admin_form_part.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- # This file is part of Shoop. # # Copyright (c) 2012-2015, Shoop Ltd. All rights reserved. # # This source code is licensed under the AGPLv3 license found in the # LICENSE file in the root directory of this source tree. from __future__ import unicode_literals from django import forms from django.utils.translation import ugettext_lazy as _ from shoop.admin.form_part import FormPart, TemplatedFormDef from shoop.core.models import Shop from shoop.discount_pricing.models import DiscountedProductPrice class DiscountPricingForm(forms.Form): def __init__(self, **kwargs): self.product = kwargs.pop("product") super(DiscountPricingForm, self).__init__(**kwargs) self.shops = [] if self.product: self._build_fields() def _build_fields(self): self.shops = list(Shop.objects.all()) prices_by_shop_and_group = dict( (shop_id, price) for (shop_id, price) in DiscountedProductPrice.objects.filter(product=self.product) .values_list("shop_id", "price_value") ) for shop in self.shops: name = self._get_field_name(shop) price = prices_by_shop_and_group.get(shop.id) price_field = forms.DecimalField( min_value=0, initial=price, label=_("Price (%s)") % shop, required=False ) self.fields[name] = price_field def _get_field_name(self, shop): return "s_%d" % shop.id def _process_single_save(self, shop): name = self._get_field_name(shop) value = self.cleaned_data.get(name) clear = (value is None or value < 0) if clear: DiscountedProductPrice.objects.filter(product=self.product, shop=shop).delete() else: (spp, created) = DiscountedProductPrice.objects.get_or_create( product=self.product, shop=shop, defaults={'price_value': value}) if not created: <|fim_middle|> def save(self): if not self.has_changed(): # No changes, so no need to do anything. return for shop in self.shops: self._process_single_save(shop) def get_shop_field(self, shop): name = self._get_field_name(shop) return self[name] class DiscountPricingFormPart(FormPart): priority = 10 def get_form_defs(self): yield TemplatedFormDef( name="discount_pricing", form_class=DiscountPricingForm, template_name="shoop/admin/discount_pricing/form_part.jinja", required=False, kwargs={"product": self.object} ) def form_valid(self, form): form["discount_pricing"].save() <|fim▁end|>
spp.price_value = value spp.save()
<|file_name|>admin_form_part.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- # This file is part of Shoop. # # Copyright (c) 2012-2015, Shoop Ltd. All rights reserved. # # This source code is licensed under the AGPLv3 license found in the # LICENSE file in the root directory of this source tree. from __future__ import unicode_literals from django import forms from django.utils.translation import ugettext_lazy as _ from shoop.admin.form_part import FormPart, TemplatedFormDef from shoop.core.models import Shop from shoop.discount_pricing.models import DiscountedProductPrice class DiscountPricingForm(forms.Form): def __init__(self, **kwargs): self.product = kwargs.pop("product") super(DiscountPricingForm, self).__init__(**kwargs) self.shops = [] if self.product: self._build_fields() def _build_fields(self): self.shops = list(Shop.objects.all()) prices_by_shop_and_group = dict( (shop_id, price) for (shop_id, price) in DiscountedProductPrice.objects.filter(product=self.product) .values_list("shop_id", "price_value") ) for shop in self.shops: name = self._get_field_name(shop) price = prices_by_shop_and_group.get(shop.id) price_field = forms.DecimalField( min_value=0, initial=price, label=_("Price (%s)") % shop, required=False ) self.fields[name] = price_field def _get_field_name(self, shop): return "s_%d" % shop.id def _process_single_save(self, shop): name = self._get_field_name(shop) value = self.cleaned_data.get(name) clear = (value is None or value < 0) if clear: DiscountedProductPrice.objects.filter(product=self.product, shop=shop).delete() else: (spp, created) = DiscountedProductPrice.objects.get_or_create( product=self.product, shop=shop, defaults={'price_value': value}) if not created: spp.price_value = value spp.save() def save(self): if not self.has_changed(): # No changes, so no need to do anything. <|fim_middle|> for shop in self.shops: self._process_single_save(shop) def get_shop_field(self, shop): name = self._get_field_name(shop) return self[name] class DiscountPricingFormPart(FormPart): priority = 10 def get_form_defs(self): yield TemplatedFormDef( name="discount_pricing", form_class=DiscountPricingForm, template_name="shoop/admin/discount_pricing/form_part.jinja", required=False, kwargs={"product": self.object} ) def form_valid(self, form): form["discount_pricing"].save() <|fim▁end|>
return
<|file_name|>admin_form_part.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- # This file is part of Shoop. # # Copyright (c) 2012-2015, Shoop Ltd. All rights reserved. # # This source code is licensed under the AGPLv3 license found in the # LICENSE file in the root directory of this source tree. from __future__ import unicode_literals from django import forms from django.utils.translation import ugettext_lazy as _ from shoop.admin.form_part import FormPart, TemplatedFormDef from shoop.core.models import Shop from shoop.discount_pricing.models import DiscountedProductPrice class DiscountPricingForm(forms.Form): def <|fim_middle|>(self, **kwargs): self.product = kwargs.pop("product") super(DiscountPricingForm, self).__init__(**kwargs) self.shops = [] if self.product: self._build_fields() def _build_fields(self): self.shops = list(Shop.objects.all()) prices_by_shop_and_group = dict( (shop_id, price) for (shop_id, price) in DiscountedProductPrice.objects.filter(product=self.product) .values_list("shop_id", "price_value") ) for shop in self.shops: name = self._get_field_name(shop) price = prices_by_shop_and_group.get(shop.id) price_field = forms.DecimalField( min_value=0, initial=price, label=_("Price (%s)") % shop, required=False ) self.fields[name] = price_field def _get_field_name(self, shop): return "s_%d" % shop.id def _process_single_save(self, shop): name = self._get_field_name(shop) value = self.cleaned_data.get(name) clear = (value is None or value < 0) if clear: DiscountedProductPrice.objects.filter(product=self.product, shop=shop).delete() else: (spp, created) = DiscountedProductPrice.objects.get_or_create( product=self.product, shop=shop, defaults={'price_value': value}) if not created: spp.price_value = value spp.save() def save(self): if not self.has_changed(): # No changes, so no need to do anything. return for shop in self.shops: self._process_single_save(shop) def get_shop_field(self, shop): name = self._get_field_name(shop) return self[name] class DiscountPricingFormPart(FormPart): priority = 10 def get_form_defs(self): yield TemplatedFormDef( name="discount_pricing", form_class=DiscountPricingForm, template_name="shoop/admin/discount_pricing/form_part.jinja", required=False, kwargs={"product": self.object} ) def form_valid(self, form): form["discount_pricing"].save() <|fim▁end|>
__init__
<|file_name|>admin_form_part.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- # This file is part of Shoop. # # Copyright (c) 2012-2015, Shoop Ltd. All rights reserved. # # This source code is licensed under the AGPLv3 license found in the # LICENSE file in the root directory of this source tree. from __future__ import unicode_literals from django import forms from django.utils.translation import ugettext_lazy as _ from shoop.admin.form_part import FormPart, TemplatedFormDef from shoop.core.models import Shop from shoop.discount_pricing.models import DiscountedProductPrice class DiscountPricingForm(forms.Form): def __init__(self, **kwargs): self.product = kwargs.pop("product") super(DiscountPricingForm, self).__init__(**kwargs) self.shops = [] if self.product: self._build_fields() def <|fim_middle|>(self): self.shops = list(Shop.objects.all()) prices_by_shop_and_group = dict( (shop_id, price) for (shop_id, price) in DiscountedProductPrice.objects.filter(product=self.product) .values_list("shop_id", "price_value") ) for shop in self.shops: name = self._get_field_name(shop) price = prices_by_shop_and_group.get(shop.id) price_field = forms.DecimalField( min_value=0, initial=price, label=_("Price (%s)") % shop, required=False ) self.fields[name] = price_field def _get_field_name(self, shop): return "s_%d" % shop.id def _process_single_save(self, shop): name = self._get_field_name(shop) value = self.cleaned_data.get(name) clear = (value is None or value < 0) if clear: DiscountedProductPrice.objects.filter(product=self.product, shop=shop).delete() else: (spp, created) = DiscountedProductPrice.objects.get_or_create( product=self.product, shop=shop, defaults={'price_value': value}) if not created: spp.price_value = value spp.save() def save(self): if not self.has_changed(): # No changes, so no need to do anything. return for shop in self.shops: self._process_single_save(shop) def get_shop_field(self, shop): name = self._get_field_name(shop) return self[name] class DiscountPricingFormPart(FormPart): priority = 10 def get_form_defs(self): yield TemplatedFormDef( name="discount_pricing", form_class=DiscountPricingForm, template_name="shoop/admin/discount_pricing/form_part.jinja", required=False, kwargs={"product": self.object} ) def form_valid(self, form): form["discount_pricing"].save() <|fim▁end|>
_build_fields
<|file_name|>admin_form_part.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- # This file is part of Shoop. # # Copyright (c) 2012-2015, Shoop Ltd. All rights reserved. # # This source code is licensed under the AGPLv3 license found in the # LICENSE file in the root directory of this source tree. from __future__ import unicode_literals from django import forms from django.utils.translation import ugettext_lazy as _ from shoop.admin.form_part import FormPart, TemplatedFormDef from shoop.core.models import Shop from shoop.discount_pricing.models import DiscountedProductPrice class DiscountPricingForm(forms.Form): def __init__(self, **kwargs): self.product = kwargs.pop("product") super(DiscountPricingForm, self).__init__(**kwargs) self.shops = [] if self.product: self._build_fields() def _build_fields(self): self.shops = list(Shop.objects.all()) prices_by_shop_and_group = dict( (shop_id, price) for (shop_id, price) in DiscountedProductPrice.objects.filter(product=self.product) .values_list("shop_id", "price_value") ) for shop in self.shops: name = self._get_field_name(shop) price = prices_by_shop_and_group.get(shop.id) price_field = forms.DecimalField( min_value=0, initial=price, label=_("Price (%s)") % shop, required=False ) self.fields[name] = price_field def <|fim_middle|>(self, shop): return "s_%d" % shop.id def _process_single_save(self, shop): name = self._get_field_name(shop) value = self.cleaned_data.get(name) clear = (value is None or value < 0) if clear: DiscountedProductPrice.objects.filter(product=self.product, shop=shop).delete() else: (spp, created) = DiscountedProductPrice.objects.get_or_create( product=self.product, shop=shop, defaults={'price_value': value}) if not created: spp.price_value = value spp.save() def save(self): if not self.has_changed(): # No changes, so no need to do anything. return for shop in self.shops: self._process_single_save(shop) def get_shop_field(self, shop): name = self._get_field_name(shop) return self[name] class DiscountPricingFormPart(FormPart): priority = 10 def get_form_defs(self): yield TemplatedFormDef( name="discount_pricing", form_class=DiscountPricingForm, template_name="shoop/admin/discount_pricing/form_part.jinja", required=False, kwargs={"product": self.object} ) def form_valid(self, form): form["discount_pricing"].save() <|fim▁end|>
_get_field_name
<|file_name|>admin_form_part.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- # This file is part of Shoop. # # Copyright (c) 2012-2015, Shoop Ltd. All rights reserved. # # This source code is licensed under the AGPLv3 license found in the # LICENSE file in the root directory of this source tree. from __future__ import unicode_literals from django import forms from django.utils.translation import ugettext_lazy as _ from shoop.admin.form_part import FormPart, TemplatedFormDef from shoop.core.models import Shop from shoop.discount_pricing.models import DiscountedProductPrice class DiscountPricingForm(forms.Form): def __init__(self, **kwargs): self.product = kwargs.pop("product") super(DiscountPricingForm, self).__init__(**kwargs) self.shops = [] if self.product: self._build_fields() def _build_fields(self): self.shops = list(Shop.objects.all()) prices_by_shop_and_group = dict( (shop_id, price) for (shop_id, price) in DiscountedProductPrice.objects.filter(product=self.product) .values_list("shop_id", "price_value") ) for shop in self.shops: name = self._get_field_name(shop) price = prices_by_shop_and_group.get(shop.id) price_field = forms.DecimalField( min_value=0, initial=price, label=_("Price (%s)") % shop, required=False ) self.fields[name] = price_field def _get_field_name(self, shop): return "s_%d" % shop.id def <|fim_middle|>(self, shop): name = self._get_field_name(shop) value = self.cleaned_data.get(name) clear = (value is None or value < 0) if clear: DiscountedProductPrice.objects.filter(product=self.product, shop=shop).delete() else: (spp, created) = DiscountedProductPrice.objects.get_or_create( product=self.product, shop=shop, defaults={'price_value': value}) if not created: spp.price_value = value spp.save() def save(self): if not self.has_changed(): # No changes, so no need to do anything. return for shop in self.shops: self._process_single_save(shop) def get_shop_field(self, shop): name = self._get_field_name(shop) return self[name] class DiscountPricingFormPart(FormPart): priority = 10 def get_form_defs(self): yield TemplatedFormDef( name="discount_pricing", form_class=DiscountPricingForm, template_name="shoop/admin/discount_pricing/form_part.jinja", required=False, kwargs={"product": self.object} ) def form_valid(self, form): form["discount_pricing"].save() <|fim▁end|>
_process_single_save
<|file_name|>admin_form_part.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- # This file is part of Shoop. # # Copyright (c) 2012-2015, Shoop Ltd. All rights reserved. # # This source code is licensed under the AGPLv3 license found in the # LICENSE file in the root directory of this source tree. from __future__ import unicode_literals from django import forms from django.utils.translation import ugettext_lazy as _ from shoop.admin.form_part import FormPart, TemplatedFormDef from shoop.core.models import Shop from shoop.discount_pricing.models import DiscountedProductPrice class DiscountPricingForm(forms.Form): def __init__(self, **kwargs): self.product = kwargs.pop("product") super(DiscountPricingForm, self).__init__(**kwargs) self.shops = [] if self.product: self._build_fields() def _build_fields(self): self.shops = list(Shop.objects.all()) prices_by_shop_and_group = dict( (shop_id, price) for (shop_id, price) in DiscountedProductPrice.objects.filter(product=self.product) .values_list("shop_id", "price_value") ) for shop in self.shops: name = self._get_field_name(shop) price = prices_by_shop_and_group.get(shop.id) price_field = forms.DecimalField( min_value=0, initial=price, label=_("Price (%s)") % shop, required=False ) self.fields[name] = price_field def _get_field_name(self, shop): return "s_%d" % shop.id def _process_single_save(self, shop): name = self._get_field_name(shop) value = self.cleaned_data.get(name) clear = (value is None or value < 0) if clear: DiscountedProductPrice.objects.filter(product=self.product, shop=shop).delete() else: (spp, created) = DiscountedProductPrice.objects.get_or_create( product=self.product, shop=shop, defaults={'price_value': value}) if not created: spp.price_value = value spp.save() def <|fim_middle|>(self): if not self.has_changed(): # No changes, so no need to do anything. return for shop in self.shops: self._process_single_save(shop) def get_shop_field(self, shop): name = self._get_field_name(shop) return self[name] class DiscountPricingFormPart(FormPart): priority = 10 def get_form_defs(self): yield TemplatedFormDef( name="discount_pricing", form_class=DiscountPricingForm, template_name="shoop/admin/discount_pricing/form_part.jinja", required=False, kwargs={"product": self.object} ) def form_valid(self, form): form["discount_pricing"].save() <|fim▁end|>
save
<|file_name|>admin_form_part.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- # This file is part of Shoop. # # Copyright (c) 2012-2015, Shoop Ltd. All rights reserved. # # This source code is licensed under the AGPLv3 license found in the # LICENSE file in the root directory of this source tree. from __future__ import unicode_literals from django import forms from django.utils.translation import ugettext_lazy as _ from shoop.admin.form_part import FormPart, TemplatedFormDef from shoop.core.models import Shop from shoop.discount_pricing.models import DiscountedProductPrice class DiscountPricingForm(forms.Form): def __init__(self, **kwargs): self.product = kwargs.pop("product") super(DiscountPricingForm, self).__init__(**kwargs) self.shops = [] if self.product: self._build_fields() def _build_fields(self): self.shops = list(Shop.objects.all()) prices_by_shop_and_group = dict( (shop_id, price) for (shop_id, price) in DiscountedProductPrice.objects.filter(product=self.product) .values_list("shop_id", "price_value") ) for shop in self.shops: name = self._get_field_name(shop) price = prices_by_shop_and_group.get(shop.id) price_field = forms.DecimalField( min_value=0, initial=price, label=_("Price (%s)") % shop, required=False ) self.fields[name] = price_field def _get_field_name(self, shop): return "s_%d" % shop.id def _process_single_save(self, shop): name = self._get_field_name(shop) value = self.cleaned_data.get(name) clear = (value is None or value < 0) if clear: DiscountedProductPrice.objects.filter(product=self.product, shop=shop).delete() else: (spp, created) = DiscountedProductPrice.objects.get_or_create( product=self.product, shop=shop, defaults={'price_value': value}) if not created: spp.price_value = value spp.save() def save(self): if not self.has_changed(): # No changes, so no need to do anything. return for shop in self.shops: self._process_single_save(shop) def <|fim_middle|>(self, shop): name = self._get_field_name(shop) return self[name] class DiscountPricingFormPart(FormPart): priority = 10 def get_form_defs(self): yield TemplatedFormDef( name="discount_pricing", form_class=DiscountPricingForm, template_name="shoop/admin/discount_pricing/form_part.jinja", required=False, kwargs={"product": self.object} ) def form_valid(self, form): form["discount_pricing"].save() <|fim▁end|>
get_shop_field
<|file_name|>admin_form_part.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- # This file is part of Shoop. # # Copyright (c) 2012-2015, Shoop Ltd. All rights reserved. # # This source code is licensed under the AGPLv3 license found in the # LICENSE file in the root directory of this source tree. from __future__ import unicode_literals from django import forms from django.utils.translation import ugettext_lazy as _ from shoop.admin.form_part import FormPart, TemplatedFormDef from shoop.core.models import Shop from shoop.discount_pricing.models import DiscountedProductPrice class DiscountPricingForm(forms.Form): def __init__(self, **kwargs): self.product = kwargs.pop("product") super(DiscountPricingForm, self).__init__(**kwargs) self.shops = [] if self.product: self._build_fields() def _build_fields(self): self.shops = list(Shop.objects.all()) prices_by_shop_and_group = dict( (shop_id, price) for (shop_id, price) in DiscountedProductPrice.objects.filter(product=self.product) .values_list("shop_id", "price_value") ) for shop in self.shops: name = self._get_field_name(shop) price = prices_by_shop_and_group.get(shop.id) price_field = forms.DecimalField( min_value=0, initial=price, label=_("Price (%s)") % shop, required=False ) self.fields[name] = price_field def _get_field_name(self, shop): return "s_%d" % shop.id def _process_single_save(self, shop): name = self._get_field_name(shop) value = self.cleaned_data.get(name) clear = (value is None or value < 0) if clear: DiscountedProductPrice.objects.filter(product=self.product, shop=shop).delete() else: (spp, created) = DiscountedProductPrice.objects.get_or_create( product=self.product, shop=shop, defaults={'price_value': value}) if not created: spp.price_value = value spp.save() def save(self): if not self.has_changed(): # No changes, so no need to do anything. return for shop in self.shops: self._process_single_save(shop) def get_shop_field(self, shop): name = self._get_field_name(shop) return self[name] class DiscountPricingFormPart(FormPart): priority = 10 def <|fim_middle|>(self): yield TemplatedFormDef( name="discount_pricing", form_class=DiscountPricingForm, template_name="shoop/admin/discount_pricing/form_part.jinja", required=False, kwargs={"product": self.object} ) def form_valid(self, form): form["discount_pricing"].save() <|fim▁end|>
get_form_defs
<|file_name|>admin_form_part.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- # This file is part of Shoop. # # Copyright (c) 2012-2015, Shoop Ltd. All rights reserved. # # This source code is licensed under the AGPLv3 license found in the # LICENSE file in the root directory of this source tree. from __future__ import unicode_literals from django import forms from django.utils.translation import ugettext_lazy as _ from shoop.admin.form_part import FormPart, TemplatedFormDef from shoop.core.models import Shop from shoop.discount_pricing.models import DiscountedProductPrice class DiscountPricingForm(forms.Form): def __init__(self, **kwargs): self.product = kwargs.pop("product") super(DiscountPricingForm, self).__init__(**kwargs) self.shops = [] if self.product: self._build_fields() def _build_fields(self): self.shops = list(Shop.objects.all()) prices_by_shop_and_group = dict( (shop_id, price) for (shop_id, price) in DiscountedProductPrice.objects.filter(product=self.product) .values_list("shop_id", "price_value") ) for shop in self.shops: name = self._get_field_name(shop) price = prices_by_shop_and_group.get(shop.id) price_field = forms.DecimalField( min_value=0, initial=price, label=_("Price (%s)") % shop, required=False ) self.fields[name] = price_field def _get_field_name(self, shop): return "s_%d" % shop.id def _process_single_save(self, shop): name = self._get_field_name(shop) value = self.cleaned_data.get(name) clear = (value is None or value < 0) if clear: DiscountedProductPrice.objects.filter(product=self.product, shop=shop).delete() else: (spp, created) = DiscountedProductPrice.objects.get_or_create( product=self.product, shop=shop, defaults={'price_value': value}) if not created: spp.price_value = value spp.save() def save(self): if not self.has_changed(): # No changes, so no need to do anything. return for shop in self.shops: self._process_single_save(shop) def get_shop_field(self, shop): name = self._get_field_name(shop) return self[name] class DiscountPricingFormPart(FormPart): priority = 10 def get_form_defs(self): yield TemplatedFormDef( name="discount_pricing", form_class=DiscountPricingForm, template_name="shoop/admin/discount_pricing/form_part.jinja", required=False, kwargs={"product": self.object} ) def <|fim_middle|>(self, form): form["discount_pricing"].save() <|fim▁end|>
form_valid
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|>from flask import Flask from flask import render_template, request app = Flask(__name__) @app.route("/") def main(): room = request.args.get('room', '') if room: return render_template('watch.html') return render_template('index.html') <|fim▁hole|> app.run(host='0.0.0.0', debug=True)<|fim▁end|>
if __name__ == "__main__":
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|>from flask import Flask from flask import render_template, request app = Flask(__name__) @app.route("/") def main(): <|fim_middle|> if __name__ == "__main__": app.run(host='0.0.0.0', debug=True) <|fim▁end|>
room = request.args.get('room', '') if room: return render_template('watch.html') return render_template('index.html')
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|>from flask import Flask from flask import render_template, request app = Flask(__name__) @app.route("/") def main(): room = request.args.get('room', '') if room: <|fim_middle|> return render_template('index.html') if __name__ == "__main__": app.run(host='0.0.0.0', debug=True) <|fim▁end|>
return render_template('watch.html')
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|>from flask import Flask from flask import render_template, request app = Flask(__name__) @app.route("/") def main(): room = request.args.get('room', '') if room: return render_template('watch.html') return render_template('index.html') if __name__ == "__main__": <|fim_middle|> <|fim▁end|>
app.run(host='0.0.0.0', debug=True)
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|>from flask import Flask from flask import render_template, request app = Flask(__name__) @app.route("/") def <|fim_middle|>(): room = request.args.get('room', '') if room: return render_template('watch.html') return render_template('index.html') if __name__ == "__main__": app.run(host='0.0.0.0', debug=True) <|fim▁end|>
main
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- #------------------------------------------------------------------------------ # file: $Id$ # auth: metagriffin <mg.github@uberdev.org> # date: 2012/04/20 # copy: (C) Copyright 2012-EOT metagriffin -- see LICENSE.txt #------------------------------------------------------------------------------ # This software is free software: you can redistribute it and/or # modify it under the terms of the GNU General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version.<|fim▁hole|># # This software is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see http://www.gnu.org/licenses/. #------------------------------------------------------------------------------ from .tracker import * from .merger import * #------------------------------------------------------------------------------ # end of $Id$ #------------------------------------------------------------------------------<|fim▁end|>
<|file_name|>19180cf98af6_nsx_gw_devices.py<|end_file_name|><|fim▁begin|># Copyright 2014 OpenStack Foundation # # 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. # """nsx_gw_devices Revision ID: 19180cf98af6 Revises: 117643811bca Create Date: 2014-02-26 02:46:26.151741 """ # revision identifiers, used by Alembic. revision = '19180cf98af6' down_revision = '117643811bca' # Change to ['*'] if this migration applies to all plugins migration_for_plugins = [ 'neutron.plugins.nicira.NeutronPlugin.NvpPluginV2', 'neutron.plugins.nicira.NeutronServicePlugin.NvpAdvancedPlugin', 'neutron.plugins.vmware.plugin.NsxPlugin', 'neutron.plugins.vmware.plugin.NsxServicePlugin' ] from alembic import op import sqlalchemy as sa from neutron.db import migration def upgrade(active_plugins=None, options=None): if not migration.should_run(active_plugins, migration_for_plugins): return op.create_table( 'networkgatewaydevicereferences', sa.Column('id', sa.String(length=36), nullable=False),<|fim▁hole|> ondelete='CASCADE'), sa.PrimaryKeyConstraint('id', 'network_gateway_id', 'interface_name'), mysql_engine='InnoDB') # Copy data from networkgatewaydevices into networkgatewaydevicereference op.execute("INSERT INTO networkgatewaydevicereferences SELECT " "id, network_gateway_id, interface_name FROM " "networkgatewaydevices") # drop networkgatewaydevices op.drop_table('networkgatewaydevices') op.create_table( 'networkgatewaydevices', sa.Column('tenant_id', sa.String(length=255), nullable=True), sa.Column('id', sa.String(length=36), nullable=False), sa.Column('nsx_id', sa.String(length=36), nullable=True), sa.Column('name', sa.String(length=255), nullable=True), sa.Column('connector_type', sa.String(length=10), nullable=True), sa.Column('connector_ip', sa.String(length=64), nullable=True), sa.Column('status', sa.String(length=16), nullable=True), sa.PrimaryKeyConstraint('id'), mysql_engine='InnoDB') # Create a networkgatewaydevice for each existing reference. # For existing references nsx_id == neutron_id # Do not fill conenctor info as they would be unknown op.execute("INSERT INTO networkgatewaydevices (id, nsx_id) SELECT " "id, id as nsx_id FROM networkgatewaydevicereferences") def downgrade(active_plugins=None, options=None): if not migration.should_run(active_plugins, migration_for_plugins): return op.drop_table('networkgatewaydevices') # Re-create previous version of networkgatewaydevices table op.create_table( 'networkgatewaydevices', sa.Column('id', sa.String(length=36), nullable=False), sa.Column('network_gateway_id', sa.String(length=36), nullable=True), sa.Column('interface_name', sa.String(length=64), nullable=True), sa.ForeignKeyConstraint(['network_gateway_id'], ['networkgateways.id'], ondelete='CASCADE'), sa.PrimaryKeyConstraint('id'), mysql_engine='InnoDB') # Copy from networkgatewaydevicereferences to networkgatewaydevices op.execute("INSERT INTO networkgatewaydevices SELECT " "id, network_gateway_id, interface_name FROM " "networkgatewaydevicereferences") # Dropt networkgatewaydevicereferences op.drop_table('networkgatewaydevicereferences')<|fim▁end|>
sa.Column('network_gateway_id', sa.String(length=36), nullable=True), sa.Column('interface_name', sa.String(length=64), nullable=True), sa.ForeignKeyConstraint(['network_gateway_id'], ['networkgateways.id'],
<|file_name|>19180cf98af6_nsx_gw_devices.py<|end_file_name|><|fim▁begin|># Copyright 2014 OpenStack Foundation # # 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. # """nsx_gw_devices Revision ID: 19180cf98af6 Revises: 117643811bca Create Date: 2014-02-26 02:46:26.151741 """ # revision identifiers, used by Alembic. revision = '19180cf98af6' down_revision = '117643811bca' # Change to ['*'] if this migration applies to all plugins migration_for_plugins = [ 'neutron.plugins.nicira.NeutronPlugin.NvpPluginV2', 'neutron.plugins.nicira.NeutronServicePlugin.NvpAdvancedPlugin', 'neutron.plugins.vmware.plugin.NsxPlugin', 'neutron.plugins.vmware.plugin.NsxServicePlugin' ] from alembic import op import sqlalchemy as sa from neutron.db import migration def upgrade(active_plugins=None, options=None): <|fim_middle|> def downgrade(active_plugins=None, options=None): if not migration.should_run(active_plugins, migration_for_plugins): return op.drop_table('networkgatewaydevices') # Re-create previous version of networkgatewaydevices table op.create_table( 'networkgatewaydevices', sa.Column('id', sa.String(length=36), nullable=False), sa.Column('network_gateway_id', sa.String(length=36), nullable=True), sa.Column('interface_name', sa.String(length=64), nullable=True), sa.ForeignKeyConstraint(['network_gateway_id'], ['networkgateways.id'], ondelete='CASCADE'), sa.PrimaryKeyConstraint('id'), mysql_engine='InnoDB') # Copy from networkgatewaydevicereferences to networkgatewaydevices op.execute("INSERT INTO networkgatewaydevices SELECT " "id, network_gateway_id, interface_name FROM " "networkgatewaydevicereferences") # Dropt networkgatewaydevicereferences op.drop_table('networkgatewaydevicereferences') <|fim▁end|>
if not migration.should_run(active_plugins, migration_for_plugins): return op.create_table( 'networkgatewaydevicereferences', sa.Column('id', sa.String(length=36), nullable=False), sa.Column('network_gateway_id', sa.String(length=36), nullable=True), sa.Column('interface_name', sa.String(length=64), nullable=True), sa.ForeignKeyConstraint(['network_gateway_id'], ['networkgateways.id'], ondelete='CASCADE'), sa.PrimaryKeyConstraint('id', 'network_gateway_id', 'interface_name'), mysql_engine='InnoDB') # Copy data from networkgatewaydevices into networkgatewaydevicereference op.execute("INSERT INTO networkgatewaydevicereferences SELECT " "id, network_gateway_id, interface_name FROM " "networkgatewaydevices") # drop networkgatewaydevices op.drop_table('networkgatewaydevices') op.create_table( 'networkgatewaydevices', sa.Column('tenant_id', sa.String(length=255), nullable=True), sa.Column('id', sa.String(length=36), nullable=False), sa.Column('nsx_id', sa.String(length=36), nullable=True), sa.Column('name', sa.String(length=255), nullable=True), sa.Column('connector_type', sa.String(length=10), nullable=True), sa.Column('connector_ip', sa.String(length=64), nullable=True), sa.Column('status', sa.String(length=16), nullable=True), sa.PrimaryKeyConstraint('id'), mysql_engine='InnoDB') # Create a networkgatewaydevice for each existing reference. # For existing references nsx_id == neutron_id # Do not fill conenctor info as they would be unknown op.execute("INSERT INTO networkgatewaydevices (id, nsx_id) SELECT " "id, id as nsx_id FROM networkgatewaydevicereferences")
<|file_name|>19180cf98af6_nsx_gw_devices.py<|end_file_name|><|fim▁begin|># Copyright 2014 OpenStack Foundation # # 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. # """nsx_gw_devices Revision ID: 19180cf98af6 Revises: 117643811bca Create Date: 2014-02-26 02:46:26.151741 """ # revision identifiers, used by Alembic. revision = '19180cf98af6' down_revision = '117643811bca' # Change to ['*'] if this migration applies to all plugins migration_for_plugins = [ 'neutron.plugins.nicira.NeutronPlugin.NvpPluginV2', 'neutron.plugins.nicira.NeutronServicePlugin.NvpAdvancedPlugin', 'neutron.plugins.vmware.plugin.NsxPlugin', 'neutron.plugins.vmware.plugin.NsxServicePlugin' ] from alembic import op import sqlalchemy as sa from neutron.db import migration def upgrade(active_plugins=None, options=None): if not migration.should_run(active_plugins, migration_for_plugins): return op.create_table( 'networkgatewaydevicereferences', sa.Column('id', sa.String(length=36), nullable=False), sa.Column('network_gateway_id', sa.String(length=36), nullable=True), sa.Column('interface_name', sa.String(length=64), nullable=True), sa.ForeignKeyConstraint(['network_gateway_id'], ['networkgateways.id'], ondelete='CASCADE'), sa.PrimaryKeyConstraint('id', 'network_gateway_id', 'interface_name'), mysql_engine='InnoDB') # Copy data from networkgatewaydevices into networkgatewaydevicereference op.execute("INSERT INTO networkgatewaydevicereferences SELECT " "id, network_gateway_id, interface_name FROM " "networkgatewaydevices") # drop networkgatewaydevices op.drop_table('networkgatewaydevices') op.create_table( 'networkgatewaydevices', sa.Column('tenant_id', sa.String(length=255), nullable=True), sa.Column('id', sa.String(length=36), nullable=False), sa.Column('nsx_id', sa.String(length=36), nullable=True), sa.Column('name', sa.String(length=255), nullable=True), sa.Column('connector_type', sa.String(length=10), nullable=True), sa.Column('connector_ip', sa.String(length=64), nullable=True), sa.Column('status', sa.String(length=16), nullable=True), sa.PrimaryKeyConstraint('id'), mysql_engine='InnoDB') # Create a networkgatewaydevice for each existing reference. # For existing references nsx_id == neutron_id # Do not fill conenctor info as they would be unknown op.execute("INSERT INTO networkgatewaydevices (id, nsx_id) SELECT " "id, id as nsx_id FROM networkgatewaydevicereferences") def downgrade(active_plugins=None, options=None): <|fim_middle|> <|fim▁end|>
if not migration.should_run(active_plugins, migration_for_plugins): return op.drop_table('networkgatewaydevices') # Re-create previous version of networkgatewaydevices table op.create_table( 'networkgatewaydevices', sa.Column('id', sa.String(length=36), nullable=False), sa.Column('network_gateway_id', sa.String(length=36), nullable=True), sa.Column('interface_name', sa.String(length=64), nullable=True), sa.ForeignKeyConstraint(['network_gateway_id'], ['networkgateways.id'], ondelete='CASCADE'), sa.PrimaryKeyConstraint('id'), mysql_engine='InnoDB') # Copy from networkgatewaydevicereferences to networkgatewaydevices op.execute("INSERT INTO networkgatewaydevices SELECT " "id, network_gateway_id, interface_name FROM " "networkgatewaydevicereferences") # Dropt networkgatewaydevicereferences op.drop_table('networkgatewaydevicereferences')
<|file_name|>19180cf98af6_nsx_gw_devices.py<|end_file_name|><|fim▁begin|># Copyright 2014 OpenStack Foundation # # 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. # """nsx_gw_devices Revision ID: 19180cf98af6 Revises: 117643811bca Create Date: 2014-02-26 02:46:26.151741 """ # revision identifiers, used by Alembic. revision = '19180cf98af6' down_revision = '117643811bca' # Change to ['*'] if this migration applies to all plugins migration_for_plugins = [ 'neutron.plugins.nicira.NeutronPlugin.NvpPluginV2', 'neutron.plugins.nicira.NeutronServicePlugin.NvpAdvancedPlugin', 'neutron.plugins.vmware.plugin.NsxPlugin', 'neutron.plugins.vmware.plugin.NsxServicePlugin' ] from alembic import op import sqlalchemy as sa from neutron.db import migration def upgrade(active_plugins=None, options=None): if not migration.should_run(active_plugins, migration_for_plugins): <|fim_middle|> op.create_table( 'networkgatewaydevicereferences', sa.Column('id', sa.String(length=36), nullable=False), sa.Column('network_gateway_id', sa.String(length=36), nullable=True), sa.Column('interface_name', sa.String(length=64), nullable=True), sa.ForeignKeyConstraint(['network_gateway_id'], ['networkgateways.id'], ondelete='CASCADE'), sa.PrimaryKeyConstraint('id', 'network_gateway_id', 'interface_name'), mysql_engine='InnoDB') # Copy data from networkgatewaydevices into networkgatewaydevicereference op.execute("INSERT INTO networkgatewaydevicereferences SELECT " "id, network_gateway_id, interface_name FROM " "networkgatewaydevices") # drop networkgatewaydevices op.drop_table('networkgatewaydevices') op.create_table( 'networkgatewaydevices', sa.Column('tenant_id', sa.String(length=255), nullable=True), sa.Column('id', sa.String(length=36), nullable=False), sa.Column('nsx_id', sa.String(length=36), nullable=True), sa.Column('name', sa.String(length=255), nullable=True), sa.Column('connector_type', sa.String(length=10), nullable=True), sa.Column('connector_ip', sa.String(length=64), nullable=True), sa.Column('status', sa.String(length=16), nullable=True), sa.PrimaryKeyConstraint('id'), mysql_engine='InnoDB') # Create a networkgatewaydevice for each existing reference. # For existing references nsx_id == neutron_id # Do not fill conenctor info as they would be unknown op.execute("INSERT INTO networkgatewaydevices (id, nsx_id) SELECT " "id, id as nsx_id FROM networkgatewaydevicereferences") def downgrade(active_plugins=None, options=None): if not migration.should_run(active_plugins, migration_for_plugins): return op.drop_table('networkgatewaydevices') # Re-create previous version of networkgatewaydevices table op.create_table( 'networkgatewaydevices', sa.Column('id', sa.String(length=36), nullable=False), sa.Column('network_gateway_id', sa.String(length=36), nullable=True), sa.Column('interface_name', sa.String(length=64), nullable=True), sa.ForeignKeyConstraint(['network_gateway_id'], ['networkgateways.id'], ondelete='CASCADE'), sa.PrimaryKeyConstraint('id'), mysql_engine='InnoDB') # Copy from networkgatewaydevicereferences to networkgatewaydevices op.execute("INSERT INTO networkgatewaydevices SELECT " "id, network_gateway_id, interface_name FROM " "networkgatewaydevicereferences") # Dropt networkgatewaydevicereferences op.drop_table('networkgatewaydevicereferences') <|fim▁end|>
return
<|file_name|>19180cf98af6_nsx_gw_devices.py<|end_file_name|><|fim▁begin|># Copyright 2014 OpenStack Foundation # # 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. # """nsx_gw_devices Revision ID: 19180cf98af6 Revises: 117643811bca Create Date: 2014-02-26 02:46:26.151741 """ # revision identifiers, used by Alembic. revision = '19180cf98af6' down_revision = '117643811bca' # Change to ['*'] if this migration applies to all plugins migration_for_plugins = [ 'neutron.plugins.nicira.NeutronPlugin.NvpPluginV2', 'neutron.plugins.nicira.NeutronServicePlugin.NvpAdvancedPlugin', 'neutron.plugins.vmware.plugin.NsxPlugin', 'neutron.plugins.vmware.plugin.NsxServicePlugin' ] from alembic import op import sqlalchemy as sa from neutron.db import migration def upgrade(active_plugins=None, options=None): if not migration.should_run(active_plugins, migration_for_plugins): return op.create_table( 'networkgatewaydevicereferences', sa.Column('id', sa.String(length=36), nullable=False), sa.Column('network_gateway_id', sa.String(length=36), nullable=True), sa.Column('interface_name', sa.String(length=64), nullable=True), sa.ForeignKeyConstraint(['network_gateway_id'], ['networkgateways.id'], ondelete='CASCADE'), sa.PrimaryKeyConstraint('id', 'network_gateway_id', 'interface_name'), mysql_engine='InnoDB') # Copy data from networkgatewaydevices into networkgatewaydevicereference op.execute("INSERT INTO networkgatewaydevicereferences SELECT " "id, network_gateway_id, interface_name FROM " "networkgatewaydevices") # drop networkgatewaydevices op.drop_table('networkgatewaydevices') op.create_table( 'networkgatewaydevices', sa.Column('tenant_id', sa.String(length=255), nullable=True), sa.Column('id', sa.String(length=36), nullable=False), sa.Column('nsx_id', sa.String(length=36), nullable=True), sa.Column('name', sa.String(length=255), nullable=True), sa.Column('connector_type', sa.String(length=10), nullable=True), sa.Column('connector_ip', sa.String(length=64), nullable=True), sa.Column('status', sa.String(length=16), nullable=True), sa.PrimaryKeyConstraint('id'), mysql_engine='InnoDB') # Create a networkgatewaydevice for each existing reference. # For existing references nsx_id == neutron_id # Do not fill conenctor info as they would be unknown op.execute("INSERT INTO networkgatewaydevices (id, nsx_id) SELECT " "id, id as nsx_id FROM networkgatewaydevicereferences") def downgrade(active_plugins=None, options=None): if not migration.should_run(active_plugins, migration_for_plugins): <|fim_middle|> op.drop_table('networkgatewaydevices') # Re-create previous version of networkgatewaydevices table op.create_table( 'networkgatewaydevices', sa.Column('id', sa.String(length=36), nullable=False), sa.Column('network_gateway_id', sa.String(length=36), nullable=True), sa.Column('interface_name', sa.String(length=64), nullable=True), sa.ForeignKeyConstraint(['network_gateway_id'], ['networkgateways.id'], ondelete='CASCADE'), sa.PrimaryKeyConstraint('id'), mysql_engine='InnoDB') # Copy from networkgatewaydevicereferences to networkgatewaydevices op.execute("INSERT INTO networkgatewaydevices SELECT " "id, network_gateway_id, interface_name FROM " "networkgatewaydevicereferences") # Dropt networkgatewaydevicereferences op.drop_table('networkgatewaydevicereferences') <|fim▁end|>
return
<|file_name|>19180cf98af6_nsx_gw_devices.py<|end_file_name|><|fim▁begin|># Copyright 2014 OpenStack Foundation # # 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. # """nsx_gw_devices Revision ID: 19180cf98af6 Revises: 117643811bca Create Date: 2014-02-26 02:46:26.151741 """ # revision identifiers, used by Alembic. revision = '19180cf98af6' down_revision = '117643811bca' # Change to ['*'] if this migration applies to all plugins migration_for_plugins = [ 'neutron.plugins.nicira.NeutronPlugin.NvpPluginV2', 'neutron.plugins.nicira.NeutronServicePlugin.NvpAdvancedPlugin', 'neutron.plugins.vmware.plugin.NsxPlugin', 'neutron.plugins.vmware.plugin.NsxServicePlugin' ] from alembic import op import sqlalchemy as sa from neutron.db import migration def <|fim_middle|>(active_plugins=None, options=None): if not migration.should_run(active_plugins, migration_for_plugins): return op.create_table( 'networkgatewaydevicereferences', sa.Column('id', sa.String(length=36), nullable=False), sa.Column('network_gateway_id', sa.String(length=36), nullable=True), sa.Column('interface_name', sa.String(length=64), nullable=True), sa.ForeignKeyConstraint(['network_gateway_id'], ['networkgateways.id'], ondelete='CASCADE'), sa.PrimaryKeyConstraint('id', 'network_gateway_id', 'interface_name'), mysql_engine='InnoDB') # Copy data from networkgatewaydevices into networkgatewaydevicereference op.execute("INSERT INTO networkgatewaydevicereferences SELECT " "id, network_gateway_id, interface_name FROM " "networkgatewaydevices") # drop networkgatewaydevices op.drop_table('networkgatewaydevices') op.create_table( 'networkgatewaydevices', sa.Column('tenant_id', sa.String(length=255), nullable=True), sa.Column('id', sa.String(length=36), nullable=False), sa.Column('nsx_id', sa.String(length=36), nullable=True), sa.Column('name', sa.String(length=255), nullable=True), sa.Column('connector_type', sa.String(length=10), nullable=True), sa.Column('connector_ip', sa.String(length=64), nullable=True), sa.Column('status', sa.String(length=16), nullable=True), sa.PrimaryKeyConstraint('id'), mysql_engine='InnoDB') # Create a networkgatewaydevice for each existing reference. # For existing references nsx_id == neutron_id # Do not fill conenctor info as they would be unknown op.execute("INSERT INTO networkgatewaydevices (id, nsx_id) SELECT " "id, id as nsx_id FROM networkgatewaydevicereferences") def downgrade(active_plugins=None, options=None): if not migration.should_run(active_plugins, migration_for_plugins): return op.drop_table('networkgatewaydevices') # Re-create previous version of networkgatewaydevices table op.create_table( 'networkgatewaydevices', sa.Column('id', sa.String(length=36), nullable=False), sa.Column('network_gateway_id', sa.String(length=36), nullable=True), sa.Column('interface_name', sa.String(length=64), nullable=True), sa.ForeignKeyConstraint(['network_gateway_id'], ['networkgateways.id'], ondelete='CASCADE'), sa.PrimaryKeyConstraint('id'), mysql_engine='InnoDB') # Copy from networkgatewaydevicereferences to networkgatewaydevices op.execute("INSERT INTO networkgatewaydevices SELECT " "id, network_gateway_id, interface_name FROM " "networkgatewaydevicereferences") # Dropt networkgatewaydevicereferences op.drop_table('networkgatewaydevicereferences') <|fim▁end|>
upgrade
<|file_name|>19180cf98af6_nsx_gw_devices.py<|end_file_name|><|fim▁begin|># Copyright 2014 OpenStack Foundation # # 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. # """nsx_gw_devices Revision ID: 19180cf98af6 Revises: 117643811bca Create Date: 2014-02-26 02:46:26.151741 """ # revision identifiers, used by Alembic. revision = '19180cf98af6' down_revision = '117643811bca' # Change to ['*'] if this migration applies to all plugins migration_for_plugins = [ 'neutron.plugins.nicira.NeutronPlugin.NvpPluginV2', 'neutron.plugins.nicira.NeutronServicePlugin.NvpAdvancedPlugin', 'neutron.plugins.vmware.plugin.NsxPlugin', 'neutron.plugins.vmware.plugin.NsxServicePlugin' ] from alembic import op import sqlalchemy as sa from neutron.db import migration def upgrade(active_plugins=None, options=None): if not migration.should_run(active_plugins, migration_for_plugins): return op.create_table( 'networkgatewaydevicereferences', sa.Column('id', sa.String(length=36), nullable=False), sa.Column('network_gateway_id', sa.String(length=36), nullable=True), sa.Column('interface_name', sa.String(length=64), nullable=True), sa.ForeignKeyConstraint(['network_gateway_id'], ['networkgateways.id'], ondelete='CASCADE'), sa.PrimaryKeyConstraint('id', 'network_gateway_id', 'interface_name'), mysql_engine='InnoDB') # Copy data from networkgatewaydevices into networkgatewaydevicereference op.execute("INSERT INTO networkgatewaydevicereferences SELECT " "id, network_gateway_id, interface_name FROM " "networkgatewaydevices") # drop networkgatewaydevices op.drop_table('networkgatewaydevices') op.create_table( 'networkgatewaydevices', sa.Column('tenant_id', sa.String(length=255), nullable=True), sa.Column('id', sa.String(length=36), nullable=False), sa.Column('nsx_id', sa.String(length=36), nullable=True), sa.Column('name', sa.String(length=255), nullable=True), sa.Column('connector_type', sa.String(length=10), nullable=True), sa.Column('connector_ip', sa.String(length=64), nullable=True), sa.Column('status', sa.String(length=16), nullable=True), sa.PrimaryKeyConstraint('id'), mysql_engine='InnoDB') # Create a networkgatewaydevice for each existing reference. # For existing references nsx_id == neutron_id # Do not fill conenctor info as they would be unknown op.execute("INSERT INTO networkgatewaydevices (id, nsx_id) SELECT " "id, id as nsx_id FROM networkgatewaydevicereferences") def <|fim_middle|>(active_plugins=None, options=None): if not migration.should_run(active_plugins, migration_for_plugins): return op.drop_table('networkgatewaydevices') # Re-create previous version of networkgatewaydevices table op.create_table( 'networkgatewaydevices', sa.Column('id', sa.String(length=36), nullable=False), sa.Column('network_gateway_id', sa.String(length=36), nullable=True), sa.Column('interface_name', sa.String(length=64), nullable=True), sa.ForeignKeyConstraint(['network_gateway_id'], ['networkgateways.id'], ondelete='CASCADE'), sa.PrimaryKeyConstraint('id'), mysql_engine='InnoDB') # Copy from networkgatewaydevicereferences to networkgatewaydevices op.execute("INSERT INTO networkgatewaydevices SELECT " "id, network_gateway_id, interface_name FROM " "networkgatewaydevicereferences") # Dropt networkgatewaydevicereferences op.drop_table('networkgatewaydevicereferences') <|fim▁end|>
downgrade
<|file_name|>train_word2vec_rf.py<|end_file_name|><|fim▁begin|>""" train supervised classifier with what's cooking recipe data objective - determine recipe type categorical value from 20 """ import time from features_bow import * from features_word2vec import * from sklearn.preprocessing import StandardScaler from sklearn.ensemble import RandomForestClassifier, ExtraTreesClassifier from sklearn.linear_model import SGDClassifier from sklearn.cross_validation import cross_val_score """ main entry method """ def main(use_idf=False, random_state=None, std=False, n_jobs=-1, verbose=2): wc_idf_map = None if use_idf: # ingredients inverse document frequencies wc_components = build_tfidf_wc(verbose=(verbose > 0)) wc_idf = wc_components['model'].idf_ wc_idf_words = wc_components['model'].get_feature_names() wc_idf_map = dict(zip(wc_idf_words, wc_idf)) # word2vec recipe feature vectors wc_components = build_word2vec_wc(feature_vec_size=120, avg=True, idf=wc_idf_map, verbose=(verbose > 0)) y_train = wc_components['train']['df']['cuisine_code'].as_matrix() X_train = wc_components['train']['features_matrix'] # standardize features aka mean ~ 0, std ~ 1 if std: scaler = StandardScaler() scaler.fit(X_train) X_train = scaler.transform(X_train) # random forest supervised classifier time_0 = time.time() clf = RandomForestClassifier(n_estimators=100, max_depth=None, n_jobs=n_jobs, random_state=random_state, verbose=verbose) # perform cross validation cv_n_fold = 8<|fim▁hole|> time_1 = time.time() elapsed_time = time_1 - time_0 print 'cross validation took %.3f seconds' % elapsed_time if __name__ == '__main__': main()<|fim▁end|>
print 'cross validating %s ways...' % cv_n_fold scores_cv = cross_val_score(clf, X_train, y_train, cv=cv_n_fold, n_jobs=-1) print 'accuracy: %0.5f (+/- %0.5f)' % (scores_cv.mean(), scores_cv.std() * 2)
<|file_name|>train_word2vec_rf.py<|end_file_name|><|fim▁begin|>""" train supervised classifier with what's cooking recipe data objective - determine recipe type categorical value from 20 """ import time from features_bow import * from features_word2vec import * from sklearn.preprocessing import StandardScaler from sklearn.ensemble import RandomForestClassifier, ExtraTreesClassifier from sklearn.linear_model import SGDClassifier from sklearn.cross_validation import cross_val_score """ main entry method """ def main(use_idf=False, random_state=None, std=False, n_jobs=-1, verbose=2): <|fim_middle|> if __name__ == '__main__': main() <|fim▁end|>
wc_idf_map = None if use_idf: # ingredients inverse document frequencies wc_components = build_tfidf_wc(verbose=(verbose > 0)) wc_idf = wc_components['model'].idf_ wc_idf_words = wc_components['model'].get_feature_names() wc_idf_map = dict(zip(wc_idf_words, wc_idf)) # word2vec recipe feature vectors wc_components = build_word2vec_wc(feature_vec_size=120, avg=True, idf=wc_idf_map, verbose=(verbose > 0)) y_train = wc_components['train']['df']['cuisine_code'].as_matrix() X_train = wc_components['train']['features_matrix'] # standardize features aka mean ~ 0, std ~ 1 if std: scaler = StandardScaler() scaler.fit(X_train) X_train = scaler.transform(X_train) # random forest supervised classifier time_0 = time.time() clf = RandomForestClassifier(n_estimators=100, max_depth=None, n_jobs=n_jobs, random_state=random_state, verbose=verbose) # perform cross validation cv_n_fold = 8 print 'cross validating %s ways...' % cv_n_fold scores_cv = cross_val_score(clf, X_train, y_train, cv=cv_n_fold, n_jobs=-1) print 'accuracy: %0.5f (+/- %0.5f)' % (scores_cv.mean(), scores_cv.std() * 2) time_1 = time.time() elapsed_time = time_1 - time_0 print 'cross validation took %.3f seconds' % elapsed_time
<|file_name|>train_word2vec_rf.py<|end_file_name|><|fim▁begin|>""" train supervised classifier with what's cooking recipe data objective - determine recipe type categorical value from 20 """ import time from features_bow import * from features_word2vec import * from sklearn.preprocessing import StandardScaler from sklearn.ensemble import RandomForestClassifier, ExtraTreesClassifier from sklearn.linear_model import SGDClassifier from sklearn.cross_validation import cross_val_score """ main entry method """ def main(use_idf=False, random_state=None, std=False, n_jobs=-1, verbose=2): wc_idf_map = None if use_idf: # ingredients inverse document frequencies <|fim_middle|> # word2vec recipe feature vectors wc_components = build_word2vec_wc(feature_vec_size=120, avg=True, idf=wc_idf_map, verbose=(verbose > 0)) y_train = wc_components['train']['df']['cuisine_code'].as_matrix() X_train = wc_components['train']['features_matrix'] # standardize features aka mean ~ 0, std ~ 1 if std: scaler = StandardScaler() scaler.fit(X_train) X_train = scaler.transform(X_train) # random forest supervised classifier time_0 = time.time() clf = RandomForestClassifier(n_estimators=100, max_depth=None, n_jobs=n_jobs, random_state=random_state, verbose=verbose) # perform cross validation cv_n_fold = 8 print 'cross validating %s ways...' % cv_n_fold scores_cv = cross_val_score(clf, X_train, y_train, cv=cv_n_fold, n_jobs=-1) print 'accuracy: %0.5f (+/- %0.5f)' % (scores_cv.mean(), scores_cv.std() * 2) time_1 = time.time() elapsed_time = time_1 - time_0 print 'cross validation took %.3f seconds' % elapsed_time if __name__ == '__main__': main() <|fim▁end|>
wc_components = build_tfidf_wc(verbose=(verbose > 0)) wc_idf = wc_components['model'].idf_ wc_idf_words = wc_components['model'].get_feature_names() wc_idf_map = dict(zip(wc_idf_words, wc_idf))
<|file_name|>train_word2vec_rf.py<|end_file_name|><|fim▁begin|>""" train supervised classifier with what's cooking recipe data objective - determine recipe type categorical value from 20 """ import time from features_bow import * from features_word2vec import * from sklearn.preprocessing import StandardScaler from sklearn.ensemble import RandomForestClassifier, ExtraTreesClassifier from sklearn.linear_model import SGDClassifier from sklearn.cross_validation import cross_val_score """ main entry method """ def main(use_idf=False, random_state=None, std=False, n_jobs=-1, verbose=2): wc_idf_map = None if use_idf: # ingredients inverse document frequencies wc_components = build_tfidf_wc(verbose=(verbose > 0)) wc_idf = wc_components['model'].idf_ wc_idf_words = wc_components['model'].get_feature_names() wc_idf_map = dict(zip(wc_idf_words, wc_idf)) # word2vec recipe feature vectors wc_components = build_word2vec_wc(feature_vec_size=120, avg=True, idf=wc_idf_map, verbose=(verbose > 0)) y_train = wc_components['train']['df']['cuisine_code'].as_matrix() X_train = wc_components['train']['features_matrix'] # standardize features aka mean ~ 0, std ~ 1 if std: <|fim_middle|> # random forest supervised classifier time_0 = time.time() clf = RandomForestClassifier(n_estimators=100, max_depth=None, n_jobs=n_jobs, random_state=random_state, verbose=verbose) # perform cross validation cv_n_fold = 8 print 'cross validating %s ways...' % cv_n_fold scores_cv = cross_val_score(clf, X_train, y_train, cv=cv_n_fold, n_jobs=-1) print 'accuracy: %0.5f (+/- %0.5f)' % (scores_cv.mean(), scores_cv.std() * 2) time_1 = time.time() elapsed_time = time_1 - time_0 print 'cross validation took %.3f seconds' % elapsed_time if __name__ == '__main__': main() <|fim▁end|>
scaler = StandardScaler() scaler.fit(X_train) X_train = scaler.transform(X_train)
<|file_name|>train_word2vec_rf.py<|end_file_name|><|fim▁begin|>""" train supervised classifier with what's cooking recipe data objective - determine recipe type categorical value from 20 """ import time from features_bow import * from features_word2vec import * from sklearn.preprocessing import StandardScaler from sklearn.ensemble import RandomForestClassifier, ExtraTreesClassifier from sklearn.linear_model import SGDClassifier from sklearn.cross_validation import cross_val_score """ main entry method """ def main(use_idf=False, random_state=None, std=False, n_jobs=-1, verbose=2): wc_idf_map = None if use_idf: # ingredients inverse document frequencies wc_components = build_tfidf_wc(verbose=(verbose > 0)) wc_idf = wc_components['model'].idf_ wc_idf_words = wc_components['model'].get_feature_names() wc_idf_map = dict(zip(wc_idf_words, wc_idf)) # word2vec recipe feature vectors wc_components = build_word2vec_wc(feature_vec_size=120, avg=True, idf=wc_idf_map, verbose=(verbose > 0)) y_train = wc_components['train']['df']['cuisine_code'].as_matrix() X_train = wc_components['train']['features_matrix'] # standardize features aka mean ~ 0, std ~ 1 if std: scaler = StandardScaler() scaler.fit(X_train) X_train = scaler.transform(X_train) # random forest supervised classifier time_0 = time.time() clf = RandomForestClassifier(n_estimators=100, max_depth=None, n_jobs=n_jobs, random_state=random_state, verbose=verbose) # perform cross validation cv_n_fold = 8 print 'cross validating %s ways...' % cv_n_fold scores_cv = cross_val_score(clf, X_train, y_train, cv=cv_n_fold, n_jobs=-1) print 'accuracy: %0.5f (+/- %0.5f)' % (scores_cv.mean(), scores_cv.std() * 2) time_1 = time.time() elapsed_time = time_1 - time_0 print 'cross validation took %.3f seconds' % elapsed_time if __name__ == '__main__': <|fim_middle|> <|fim▁end|>
main()
<|file_name|>train_word2vec_rf.py<|end_file_name|><|fim▁begin|>""" train supervised classifier with what's cooking recipe data objective - determine recipe type categorical value from 20 """ import time from features_bow import * from features_word2vec import * from sklearn.preprocessing import StandardScaler from sklearn.ensemble import RandomForestClassifier, ExtraTreesClassifier from sklearn.linear_model import SGDClassifier from sklearn.cross_validation import cross_val_score """ main entry method """ def <|fim_middle|>(use_idf=False, random_state=None, std=False, n_jobs=-1, verbose=2): wc_idf_map = None if use_idf: # ingredients inverse document frequencies wc_components = build_tfidf_wc(verbose=(verbose > 0)) wc_idf = wc_components['model'].idf_ wc_idf_words = wc_components['model'].get_feature_names() wc_idf_map = dict(zip(wc_idf_words, wc_idf)) # word2vec recipe feature vectors wc_components = build_word2vec_wc(feature_vec_size=120, avg=True, idf=wc_idf_map, verbose=(verbose > 0)) y_train = wc_components['train']['df']['cuisine_code'].as_matrix() X_train = wc_components['train']['features_matrix'] # standardize features aka mean ~ 0, std ~ 1 if std: scaler = StandardScaler() scaler.fit(X_train) X_train = scaler.transform(X_train) # random forest supervised classifier time_0 = time.time() clf = RandomForestClassifier(n_estimators=100, max_depth=None, n_jobs=n_jobs, random_state=random_state, verbose=verbose) # perform cross validation cv_n_fold = 8 print 'cross validating %s ways...' % cv_n_fold scores_cv = cross_val_score(clf, X_train, y_train, cv=cv_n_fold, n_jobs=-1) print 'accuracy: %0.5f (+/- %0.5f)' % (scores_cv.mean(), scores_cv.std() * 2) time_1 = time.time() elapsed_time = time_1 - time_0 print 'cross validation took %.3f seconds' % elapsed_time if __name__ == '__main__': main() <|fim▁end|>
main