internlm/SWE-Fixer-Train-110K huggingface dataset:
Repository: open-telemetry/opentelemetry-python

Issue:
Flask instrumentation example doesn't work
**Describe your environment**
Running on MacOS against the latest `mater` version of the `opentelemetry-*` packages.

**Steps to reproduce**
Instrument the app as described in the [docs](https://open-telemetry.github.io/opentelemetry-python/ext/flask/flask.html) and [docstring](https://github.com/open-telemetry/opentelemetry-python/blob/master/ext/opentelemetry-ext-flask/src/opentelemetry/ext/flask/__init__.py) -

```python
from flask import Flask
from opentelemetry.ext.flask import instrument_app
    
app = Flask(__name__)
instrument_app(app)
````

**What is the expected behavior?**
I would expect the flask app to start without any errors when running it locally.

**What is the actual behavior?**
I get an error running the app -

```
    from opentelemetry.ext.flask import instrument_app
E   ImportError: cannot import name 'instrument_app'
```

This is consistent with the fact that the `instrument_app` symbol no longer appears to be in [`opentelemetry.ext.flask`](https://github.com/open-telemetry/opentelemetry-python/blob/master/ext/opentelemetry-ext-flask/src/opentelemetry/ext/flask/__init__.py).

<hr>
The last time I ran this code was against v0.3 of the packages, so I imagine a lot has changed since then. It would be helpful to document the new correct way to instrument flask apps as it isn't currently clear to me what the correct way to do this is from looking at the docs and the code. Thanks! 



Discussion:

Resolving patch:
diff --git a/ext/opentelemetry-ext-flask/src/opentelemetry/ext/flask/__init__.py b/ext/opentelemetry-ext-flask/src/opentelemetry/ext/flask/__init__.py
--- a/ext/opentelemetry-ext-flask/src/opentelemetry/ext/flask/__init__.py
+++ b/ext/opentelemetry-ext-flask/src/opentelemetry/ext/flask/__init__.py
@@ -29,11 +29,11 @@
 
 .. code-block:: python
 
+    from opentelemetry.ext.flask import FlaskInstrumentor
+    FlaskInstrumentor().instrument()  # This needs to be executed before importing Flask
     from flask import Flask
-    from opentelemetry.ext.flask import instrument_app
 
     app = Flask(__name__)
-    instrument_app(app)  # This is where the magic happens. ✨
 
     @app.route("/")
     def hello():


Test patch:
Repository: open-telemetry/opentelemetry-python

Issue:
Remove unnecessary Flask app
The current auto instrumentation example includes an unnecessary Flask app in its client, remove that.


Discussion:

Resolving patch:
diff --git a/docs/examples/auto-instrumentation/client.py b/docs/examples/auto-instrumentation/client.py
--- a/docs/examples/auto-instrumentation/client.py
+++ b/docs/examples/auto-instrumentation/client.py
@@ -14,7 +14,6 @@
 
 from sys import argv
 
-from flask import Flask
 from requests import get
 
 from opentelemetry import propagators, trace
@@ -24,8 +23,6 @@
     SimpleExportSpanProcessor,
 )
 
-app = Flask(__name__)
-
 trace.set_tracer_provider(TracerProvider())
 tracer = trace.get_tracer_provider().get_tracer(__name__)
 


Test patch:
Repository: open-telemetry/opentelemetry-python

Issue:
Bug in b3 propagation
When configuring b3 propagation, if the parent of a Span is an instance of a SpanContext, the following error occurs:

`'SpanContext' object has no attribute 'context'`



Discussion:

Resolving patch:
diff --git a/opentelemetry-sdk/src/opentelemetry/sdk/trace/propagation/b3_format.py b/opentelemetry-sdk/src/opentelemetry/sdk/trace/propagation/b3_format.py
--- a/opentelemetry-sdk/src/opentelemetry/sdk/trace/propagation/b3_format.py
+++ b/opentelemetry-sdk/src/opentelemetry/sdk/trace/propagation/b3_format.py
@@ -137,7 +137,7 @@ def inject(
             set_in_carrier(
                 carrier,
                 self.PARENT_SPAN_ID_KEY,
-                format_span_id(span.parent.context.span_id),
+                format_span_id(span.parent.span_id),
             )
         set_in_carrier(carrier, self.SAMPLED_KEY, "1" if sampled else "0")
 


Test patch:
diff --git a/opentelemetry-sdk/tests/trace/propagation/test_b3_format.py b/opentelemetry-sdk/tests/trace/propagation/test_b3_format.py
--- a/opentelemetry-sdk/tests/trace/propagation/test_b3_format.py
+++ b/opentelemetry-sdk/tests/trace/propagation/test_b3_format.py
@@ -45,7 +45,7 @@ def get_child_parent_new_carrier(old_carrier):
             trace_flags=parent_context.trace_flags,
             trace_state=parent_context.trace_state,
         ),
-        parent=parent,
+        parent=parent.get_context(),
     )
 
     new_carrier = {}
Repository: open-telemetry/opentelemetry-python

Issue:
sdk: Span.resource should default to an empty resource
Right now, A resource object attached to a Span can be None:

https://github.com/open-telemetry/opentelemetry-python/blob/master/opentelemetry-sdk/src/opentelemetry/sdk/trace/__init__.py#L267 

(also type is incorrect as it should also be a Resource object)

That means that there's two similar objects that refer to an empty resource: None, and the _EMPTY_RESOURCE global.

For simplicity I would argue that we should just always default to the _EMPTY_RESOURCE object: this avoids None checks in exporters. 

We didn't use Resources in a meaningful way previously, which is why I believe this didn't come up before.


Discussion:

Resolving patch:
diff --git a/ext/opentelemetry-ext-jaeger/src/opentelemetry/ext/jaeger/__init__.py b/ext/opentelemetry-ext-jaeger/src/opentelemetry/ext/jaeger/__init__.py
--- a/ext/opentelemetry-ext-jaeger/src/opentelemetry/ext/jaeger/__init__.py
+++ b/ext/opentelemetry-ext-jaeger/src/opentelemetry/ext/jaeger/__init__.py
@@ -197,8 +197,7 @@ def _translate_to_jaeger(spans: Span):
         parent_id = span.parent.span_id if span.parent else 0
 
         tags = _extract_tags(span.attributes)
-        if span.resource:
-            tags.extend(_extract_tags(span.resource.labels))
+        tags.extend(_extract_tags(span.resource.labels))
 
         tags.extend(
             [
diff --git a/opentelemetry-sdk/src/opentelemetry/sdk/trace/__init__.py b/opentelemetry-sdk/src/opentelemetry/sdk/trace/__init__.py
--- a/opentelemetry-sdk/src/opentelemetry/sdk/trace/__init__.py
+++ b/opentelemetry-sdk/src/opentelemetry/sdk/trace/__init__.py
@@ -264,7 +264,7 @@ def __init__(
         parent: Optional[trace_api.SpanContext] = None,
         sampler: Optional[sampling.Sampler] = None,
         trace_config: None = None,  # TODO
-        resource: None = None,
+        resource: Resource = Resource.create_empty(),
         attributes: types.Attributes = None,  # TODO
         events: Sequence[Event] = None,  # TODO
         links: Sequence[trace_api.Link] = (),


Test patch:
Repository: open-telemetry/opentelemetry-python

Issue:
wsgi: set error status on span
The wsgi instrumentation does not set an error status if an exception is caught while handling a request:

https://github.com/open-telemetry/opentelemetry-python/blob/master/ext/opentelemetry-ext-wsgi/src/opentelemetry/ext/wsgi/__init__.py#L212


Discussion:

Resolving patch:
diff --git a/ext/opentelemetry-ext-wsgi/src/opentelemetry/ext/wsgi/__init__.py b/ext/opentelemetry-ext-wsgi/src/opentelemetry/ext/wsgi/__init__.py
--- a/ext/opentelemetry-ext-wsgi/src/opentelemetry/ext/wsgi/__init__.py
+++ b/ext/opentelemetry-ext-wsgi/src/opentelemetry/ext/wsgi/__init__.py
@@ -11,7 +11,6 @@
 # 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.
-
 """
 This library provides a WSGI middleware that can be used on any WSGI framework
 (such as Django / Flask) to track requests timing through OpenTelemetry.
@@ -211,8 +210,8 @@ def __call__(self, environ, start_response):
                 return _end_span_after_iterating(
                     iterable, span, self.tracer, token
                 )
-        except:  # noqa
-            # TODO Set span status (cf. https://github.com/open-telemetry/opentelemetry-python/issues/292)
+        except Exception as ex:
+            span.set_status(Status(StatusCanonicalCode.INTERNAL, str(ex)))
             span.end()
             context.detach(token)
             raise


Test patch:
diff --git a/ext/opentelemetry-ext-wsgi/tests/test_wsgi_middleware.py b/ext/opentelemetry-ext-wsgi/tests/test_wsgi_middleware.py
--- a/ext/opentelemetry-ext-wsgi/tests/test_wsgi_middleware.py
+++ b/ext/opentelemetry-ext-wsgi/tests/test_wsgi_middleware.py
@@ -21,6 +21,7 @@
 import opentelemetry.ext.wsgi as otel_wsgi
 from opentelemetry import trace as trace_api
 from opentelemetry.test.wsgitestutil import WsgiTestBase
+from opentelemetry.trace.status import StatusCanonicalCode
 
 
 class Response:
@@ -73,6 +74,11 @@ def error_wsgi(environ, start_response):
     return [b"*"]
 
 
+def error_wsgi_unhandled(environ, start_response):
+    assert isinstance(environ, dict)
+    raise ValueError
+
+
 class TestWsgiApplication(WsgiTestBase):
     def validate_response(
         self, response, error=None, span_name="HTTP GET", http_method="GET"
@@ -148,6 +154,15 @@ def test_wsgi_exc_info(self):
         response = app(self.environ, self.start_response)
         self.validate_response(response, error=ValueError)
 
+    def test_wsgi_internal_error(self):
+        app = otel_wsgi.OpenTelemetryMiddleware(error_wsgi_unhandled)
+        self.assertRaises(ValueError, app, self.environ, self.start_response)
+        span_list = self.memory_exporter.get_finished_spans()
+        self.assertEqual(len(span_list), 1)
+        self.assertEqual(
+            span_list[0].status.canonical_code, StatusCanonicalCode.INTERNAL,
+        )
+
     def test_override_span_name(self):
         """Test that span_names can be overwritten by our callback function."""
         span_name = "Dymaxion"
Repository: open-telemetry/opentelemetry-python

Issue:
ext/boto: Could not serialize attribute aws.region to tag when exporting via jaeger
**Describe your environment**
```
opentelemetry-api = "=0.9b0"
opentelemetry-ext-boto = "=0.9b0"
opentelemetry-ext-botocore = "=0.9b0"
opentelemetry-ext-dbapi = "=0.9b0"
opentelemetry-ext-jaeger = "=0.9b0"
opentelemetry-ext-psycopg2= "=0.9b0"
opentelemetry-ext-requests = "=0.9b0"
opentelemetry-instrumentation = "=0.9b0"
opentelemetry-sdk = "=0.9b0"
python = "=3.7.4"
```

**Steps to reproduce**
Install and enable ext/boto with a jaeger exporter configured. I saw the issue with SES, but I assume other calls have the same problem as well.

**What is the expected behavior?**
`aws.region` should be serialized correctly.

**What is the actual behavior?**
`Could not serialize attribute aws.region:('us-east-1',) to tag`

**Additional context**
Not sure how it should be serialized given jaeger doesn't appear to support list types. Probably should be coerced to a string.



Discussion:

Resolving patch:
diff --git a/ext/opentelemetry-ext-jaeger/src/opentelemetry/ext/jaeger/__init__.py b/ext/opentelemetry-ext-jaeger/src/opentelemetry/ext/jaeger/__init__.py
--- a/ext/opentelemetry-ext-jaeger/src/opentelemetry/ext/jaeger/__init__.py
+++ b/ext/opentelemetry-ext-jaeger/src/opentelemetry/ext/jaeger/__init__.py
@@ -314,6 +314,8 @@ def _convert_attribute_to_tag(key, attr):
         return jaeger.Tag(key=key, vLong=attr, vType=jaeger.TagType.LONG)
     if isinstance(attr, float):
         return jaeger.Tag(key=key, vDouble=attr, vType=jaeger.TagType.DOUBLE)
+    if isinstance(attr, tuple):
+        return jaeger.Tag(key=key, vStr=str(attr), vType=jaeger.TagType.STRING)
     logger.warning("Could not serialize attribute %s:%r to tag", key, attr)
     return None
 


Test patch:
diff --git a/ext/opentelemetry-ext-jaeger/tests/test_jaeger_exporter.py b/ext/opentelemetry-ext-jaeger/tests/test_jaeger_exporter.py
--- a/ext/opentelemetry-ext-jaeger/tests/test_jaeger_exporter.py
+++ b/ext/opentelemetry-ext-jaeger/tests/test_jaeger_exporter.py
@@ -200,6 +200,7 @@ def test_translate_to_jaeger(self):
         otel_spans[0].set_attribute("key_bool", False)
         otel_spans[0].set_attribute("key_string", "hello_world")
         otel_spans[0].set_attribute("key_float", 111.22)
+        otel_spans[0].set_attribute("key_tuple", ("tuple_element",))
         otel_spans[0].resource = Resource(
             labels={"key_resource": "some_resource"}
         )
@@ -241,6 +242,11 @@ def test_translate_to_jaeger(self):
                         vType=jaeger.TagType.DOUBLE,
                         vDouble=111.22,
                     ),
+                    jaeger.Tag(
+                        key="key_tuple",
+                        vType=jaeger.TagType.STRING,
+                        vStr="('tuple_element',)",
+                    ),
                     jaeger.Tag(
                         key="key_resource",
                         vType=jaeger.TagType.STRING,
Repository: open-telemetry/opentelemetry-python

Issue:
Fix a few issues in Django example
The Django example has a few issues, fix them.


Discussion:

Resolving patch:
diff --git a/docs/examples/django/pages/views.py b/docs/examples/django/pages/views.py
--- a/docs/examples/django/pages/views.py
+++ b/docs/examples/django/pages/views.py
@@ -21,7 +21,6 @@
 )
 
 trace.set_tracer_provider(TracerProvider())
-tracer = trace.get_tracer_provider().get_tracer(__name__)
 
 trace.get_tracer_provider().add_span_processor(
     SimpleExportSpanProcessor(ConsoleSpanExporter())


Test patch:
Repository: open-telemetry/opentelemetry-python

Issue:
Add HTTP user-agent to WSGI instrumentation
As discussed for ASGI in [#716 (comment)](https://github.com/open-telemetry/opentelemetry-python/pull/716/files#r428364828), the WSGI instrumentation should also set an attribute from the user-agent in a HTTP request. 


Discussion:

Resolving patch:
diff --git a/instrumentation/opentelemetry-instrumentation-wsgi/src/opentelemetry/instrumentation/wsgi/__init__.py b/instrumentation/opentelemetry-instrumentation-wsgi/src/opentelemetry/instrumentation/wsgi/__init__.py
--- a/instrumentation/opentelemetry-instrumentation-wsgi/src/opentelemetry/instrumentation/wsgi/__init__.py
+++ b/instrumentation/opentelemetry-instrumentation-wsgi/src/opentelemetry/instrumentation/wsgi/__init__.py
@@ -117,6 +117,10 @@ def collect_request_attributes(environ):
     if remote_host and remote_host != remote_addr:
         result["net.peer.name"] = remote_host
 
+    user_agent = environ.get("HTTP_USER_AGENT")
+    if user_agent is not None and len(user_agent) > 0:
+        result["http.user_agent"] = user_agent
+
     setifnotnone(result, "net.peer.port", environ.get("REMOTE_PORT"))
     flavor = environ.get("SERVER_PROTOCOL", "")
     if flavor.upper().startswith(_HTTP_VERSION_PREFIX):


Test patch:
diff --git a/instrumentation/opentelemetry-instrumentation-wsgi/tests/test_wsgi_middleware.py b/instrumentation/opentelemetry-instrumentation-wsgi/tests/test_wsgi_middleware.py
--- a/instrumentation/opentelemetry-instrumentation-wsgi/tests/test_wsgi_middleware.py
+++ b/instrumentation/opentelemetry-instrumentation-wsgi/tests/test_wsgi_middleware.py
@@ -313,6 +313,14 @@ def test_request_attributes_with_full_request_uri(self):
             expected.items(),
         )
 
+    def test_http_user_agent_attribute(self):
+        self.environ["HTTP_USER_AGENT"] = "test-useragent"
+        expected = {"http.user_agent": "test-useragent"}
+        self.assertGreaterEqual(
+            otel_wsgi.collect_request_attributes(self.environ).items(),
+            expected.items(),
+        )
+
     def test_response_attributes(self):
         otel_wsgi.add_response_attributes(self.span, "404 Not Found", {})
         expected = (
Repository: open-telemetry/opentelemetry-python

Issue:
Change default port for OTLP exporter
By default the collector OTLP receiver is configured on port 55680, the current default port in the OTLP exporter is still using the old OpenCensus receiver port. This should be changed.


Discussion:

Resolving patch:
diff --git a/exporter/opentelemetry-exporter-otlp/src/opentelemetry/exporter/otlp/__init__.py b/exporter/opentelemetry-exporter-otlp/src/opentelemetry/exporter/otlp/__init__.py
--- a/exporter/opentelemetry-exporter-otlp/src/opentelemetry/exporter/otlp/__init__.py
+++ b/exporter/opentelemetry-exporter-otlp/src/opentelemetry/exporter/otlp/__init__.py
@@ -43,7 +43,7 @@
     trace.set_tracer_provider(TracerProvider(resource=resource)))
     tracer = trace.get_tracer(__name__)
 
-    otlp_exporter = OTLPSpanExporter(endpoint="localhost:55678")
+    otlp_exporter = OTLPSpanExporter(endpoint="localhost:55680")
 
     span_processor = BatchExportSpanProcessor(otlp_exporter)
 
diff --git a/exporter/opentelemetry-exporter-otlp/src/opentelemetry/exporter/otlp/trace_exporter/__init__.py b/exporter/opentelemetry-exporter-otlp/src/opentelemetry/exporter/otlp/trace_exporter/__init__.py
--- a/exporter/opentelemetry-exporter-otlp/src/opentelemetry/exporter/otlp/trace_exporter/__init__.py
+++ b/exporter/opentelemetry-exporter-otlp/src/opentelemetry/exporter/otlp/trace_exporter/__init__.py
@@ -89,7 +89,7 @@ class OTLPSpanExporter(SpanExporter):
 
     def __init__(
         self,
-        endpoint="localhost:55678",
+        endpoint="localhost:55680",
         credentials: ChannelCredentials = None,
         metadata=None,
     ):


Test patch:
diff --git a/exporter/opentelemetry-exporter-otlp/tests/test_otlp_trace_exporter.py b/exporter/opentelemetry-exporter-otlp/tests/test_otlp_trace_exporter.py
--- a/exporter/opentelemetry-exporter-otlp/tests/test_otlp_trace_exporter.py
+++ b/exporter/opentelemetry-exporter-otlp/tests/test_otlp_trace_exporter.py
@@ -98,7 +98,7 @@ def setUp(self):
 
         self.server = server(ThreadPoolExecutor(max_workers=10))
 
-        self.server.add_insecure_port("[::]:55678")
+        self.server.add_insecure_port("[::]:55680")
 
         self.server.start()
Repository: open-telemetry/opentelemetry-python

Issue:
opentelemetry-exporter-jaeger: Trace/span are reported twice if Collector is configured to bypass Agent
**Describe your environment** 
python = "3.6"
opentelemetry-sdk = "0.11b0"
opentelemetry-ext-jaeger = "0.11b0"

**Steps to reproduce**
Configure collector
```python
jaeger_exporter = jaeger.JaegerSpanExporter(
    service_name=config.JAEGER_SERVICE_NAME,
    collector_host_name='localhost',
    collector_port=14268,
    collector_endpoint='/api/traces?format=jaeger.thrift'
)
```

**What is the expected behavior?**
Collector submit trace/span

**What is the actual behavior?**
Trace/span are reported twice by both Agent and Collector




Discussion:

Resolving patch:
diff --git a/exporter/opentelemetry-exporter-jaeger/src/opentelemetry/exporter/jaeger/__init__.py b/exporter/opentelemetry-exporter-jaeger/src/opentelemetry/exporter/jaeger/__init__.py
--- a/exporter/opentelemetry-exporter-jaeger/src/opentelemetry/exporter/jaeger/__init__.py
+++ b/exporter/opentelemetry-exporter-jaeger/src/opentelemetry/exporter/jaeger/__init__.py
@@ -168,7 +168,8 @@ def export(self, spans):
 
         if self.collector is not None:
             self.collector.submit(batch)
-        self.agent_client.emit(batch)
+        else:
+            self.agent_client.emit(batch)
 
         return SpanExportResult.SUCCESS
 


Test patch:
diff --git a/exporter/opentelemetry-exporter-jaeger/tests/test_jaeger_exporter.py b/exporter/opentelemetry-exporter-jaeger/tests/test_jaeger_exporter.py
--- a/exporter/opentelemetry-exporter-jaeger/tests/test_jaeger_exporter.py
+++ b/exporter/opentelemetry-exporter-jaeger/tests/test_jaeger_exporter.py
@@ -367,7 +367,7 @@ def test_export(self):
         exporter._collector = collector_mock
 
         exporter.export((self._test_span,))
-        self.assertEqual(agent_client_mock.emit.call_count, 2)
+        self.assertEqual(agent_client_mock.emit.call_count, 1)
         self.assertEqual(collector_mock.submit.call_count, 1)
 
     def test_agent_client(self):
Repository: open-telemetry/opentelemetry-python

Issue:
Underscore is missing from attribute
An underscore is missing [here](https://github.com/open-telemetry/opentelemetry-python/blob/master/exporter/opentelemetry-exporter-otlp/src/opentelemetry/exporter/otlp/exporter.py#L189).


Discussion:

Resolving patch:
diff --git a/exporter/opentelemetry-exporter-otlp/src/opentelemetry/exporter/otlp/exporter.py b/exporter/opentelemetry-exporter-otlp/src/opentelemetry/exporter/otlp/exporter.py
--- a/exporter/opentelemetry-exporter-otlp/src/opentelemetry/exporter/otlp/exporter.py
+++ b/exporter/opentelemetry-exporter-otlp/src/opentelemetry/exporter/otlp/exporter.py
@@ -186,7 +186,7 @@ def _export(self, data):
                 if error.code() == StatusCode.OK:
                     return self._result.SUCCESS
 
-                return self.result.FAILURE
+                return self._result.FAILURE
 
         return self._result.FAILURE
 


Test patch:
diff --git a/exporter/opentelemetry-exporter-otlp/tests/test_otlp_trace_exporter.py b/exporter/opentelemetry-exporter-otlp/tests/test_otlp_trace_exporter.py
--- a/exporter/opentelemetry-exporter-otlp/tests/test_otlp_trace_exporter.py
+++ b/exporter/opentelemetry-exporter-otlp/tests/test_otlp_trace_exporter.py
@@ -87,6 +87,14 @@ def Export(self, request, context):
         return ExportTraceServiceResponse()
 
 
+class TraceServiceServicerALREADY_EXISTS(TraceServiceServicer):
+    # pylint: disable=invalid-name,unused-argument,no-self-use
+    def Export(self, request, context):
+        context.set_code(StatusCode.ALREADY_EXISTS)
+
+        return ExportTraceServiceResponse()
+
+
 class TestOTLPSpanExporter(TestCase):
     def setUp(self):
         tracer_provider = TracerProvider()
@@ -178,6 +186,14 @@ def test_success(self):
             self.exporter.export([self.span]), SpanExportResult.SUCCESS
         )
 
+    def test_failure(self):
+        add_TraceServiceServicer_to_server(
+            TraceServiceServicerALREADY_EXISTS(), self.server
+        )
+        self.assertEqual(
+            self.exporter.export([self.span]), SpanExportResult.FAILURE
+        )
+
     def test_translate_spans(self):
 
         expected = ExportTraceServiceRequest(