├── .gitignore ├── GuessTheNumber-Auto ├── Dockerfile └── src │ ├── app.py │ ├── requirements.txt │ ├── static │ ├── index.js │ └── style.css │ └── templates │ └── index.html ├── GuessTheNumber-Manual-Lambda ├── Dockerfile └── src │ ├── app.py │ ├── collector-config.yaml │ ├── requirements.txt │ ├── static │ ├── index.js │ └── style.css │ └── templates │ └── index.html ├── GuessTheNumber-Manual ├── .DS_Store ├── Dockerfile ├── collector-config.yaml └── src │ ├── app.py │ ├── requirements.txt │ ├── static │ ├── index.js │ └── style.css │ └── templates │ └── index.html ├── GuessTheNumber-SAM ├── .gitignore ├── README.md ├── __init__.py ├── guess_the_number │ ├── __init__.py │ ├── app.py │ ├── collector-config.yaml │ ├── requirements.txt │ ├── static │ │ ├── index.js │ │ └── style.css │ └── templates │ │ └── index.html └── template.yaml ├── LICENSE ├── README.md ├── Role ├── policy.json └── trust.json ├── build_local.sh └── build_push.sh /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | build/ 12 | develop-eggs/ 13 | dist/ 14 | downloads/ 15 | eggs/ 16 | .eggs/ 17 | lib/ 18 | lib64/ 19 | parts/ 20 | sdist/ 21 | var/ 22 | wheels/ 23 | pip-wheel-metadata/ 24 | share/python-wheels/ 25 | *.egg-info/ 26 | .installed.cfg 27 | *.egg 28 | MANIFEST 29 | 30 | # PyInstaller 31 | # Usually these files are written by a python script from a template 32 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 33 | *.manifest 34 | *.spec 35 | 36 | # Installer logs 37 | pip-log.txt 38 | pip-delete-this-directory.txt 39 | 40 | # Unit test / coverage reports 41 | htmlcov/ 42 | .tox/ 43 | .nox/ 44 | .coverage 45 | .coverage.* 46 | .cache 47 | nosetests.xml 48 | coverage.xml 49 | *.cover 50 | *.py,cover 51 | .hypothesis/ 52 | .pytest_cache/ 53 | 54 | # Translations 55 | *.mo 56 | *.pot 57 | 58 | # Django stuff: 59 | *.log 60 | local_settings.py 61 | db.sqlite3 62 | db.sqlite3-journal 63 | 64 | # Flask stuff: 65 | instance/ 66 | .webassets-cache 67 | 68 | # Scrapy stuff: 69 | .scrapy 70 | 71 | # Sphinx documentation 72 | docs/_build/ 73 | 74 | # PyBuilder 75 | target/ 76 | 77 | # Jupyter Notebook 78 | .ipynb_checkpoints 79 | 80 | # IPython 81 | profile_default/ 82 | ipython_config.py 83 | 84 | # pyenv 85 | .python-version 86 | 87 | # pipenv 88 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. 89 | # However, in case of collaboration, if having platform-specific dependencies or dependencies 90 | # having no cross-platform support, pipenv may install dependencies that don't work, or not 91 | # install all needed dependencies. 92 | #Pipfile.lock 93 | 94 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow 95 | __pypackages__/ 96 | 97 | # Celery stuff 98 | celerybeat-schedule 99 | celerybeat.pid 100 | 101 | # SageMath parsed files 102 | *.sage.py 103 | 104 | # Environments 105 | .env 106 | .venv 107 | env/ 108 | venv/ 109 | ENV/ 110 | env.bak/ 111 | venv.bak/ 112 | 113 | # Spyder project settings 114 | .spyderproject 115 | .spyproject 116 | 117 | # Rope project settings 118 | .ropeproject 119 | 120 | # mkdocs documentation 121 | /site 122 | 123 | # mypy 124 | .mypy_cache/ 125 | .dmypy.json 126 | dmypy.json 127 | 128 | # Pyre type checker 129 | .pyre/ 130 | 131 | # VSCode 132 | .vscode/ -------------------------------------------------------------------------------- /GuessTheNumber-Auto/Dockerfile: -------------------------------------------------------------------------------- 1 | FROM public.ecr.aws/docker/library/python:3.10-slim 2 | 3 | WORKDIR /app 4 | 5 | COPY src/requirements.txt requirements.txt 6 | RUN pip3 install -r requirements.txt 7 | 8 | COPY src . 9 | 10 | RUN opentelemetry-bootstrap -a install 11 | 12 | ENV OTEL_PYTHON_DISABLED_INSTRUMENTATIONS=urllib3 13 | ENV OTEL_RESOURCE_ATTRIBUTES='service.name=guess-the-number' 14 | 15 | CMD OTEL_PROPAGATORS=xray OTEL_PYTHON_ID_GENERATOR=xray opentelemetry-instrument flask run --host=0.0.0.0 --port=8080 16 | 17 | EXPOSE 8080 -------------------------------------------------------------------------------- /GuessTheNumber-Auto/src/app.py: -------------------------------------------------------------------------------- 1 | import random 2 | import time 3 | import uuid 4 | 5 | import flask 6 | from flask import Flask, render_template, jsonify, redirect 7 | 8 | import boto3 9 | from boto3.dynamodb.conditions import Attr 10 | 11 | TABLE_NAME = 'guess-the-number' 12 | QUEUE_NAME = 'guess-the-number-winners' 13 | 14 | TTL = 24 * 60 * 60 # 1 day 15 | 16 | MIN_NUMBER = 1 17 | MAX_NUMBER = 100 18 | 19 | dynamodb = boto3.resource('dynamodb') 20 | sqs = boto3.resource('sqs') 21 | 22 | guess_the_number_table = dynamodb.Table(TABLE_NAME) 23 | guess_the_number_winners_queue = sqs.get_queue_by_name(QueueName=QUEUE_NAME) 24 | 25 | 26 | app = Flask(__name__) 27 | 28 | 29 | @app.route('/') 30 | def index(): 31 | return render_template("index.html") 32 | 33 | 34 | @app.route('/game') 35 | def new_game(): 36 | 37 | game = create_game() 38 | 39 | location = flask.url_for('describe_game', game_id = game['id']) 40 | print("new_game " + location) 41 | return redirect(location) 42 | 43 | 44 | @app.route('/game/') 45 | def describe_game(game_id): 46 | 47 | game = get_game(game_id) 48 | 49 | if game == None or game['won']: 50 | location = flask.url_for('new_game') 51 | print("describe_game " + location) 52 | return redirect(location) 53 | 54 | del game['number'] 55 | return jsonify(game) 56 | 57 | 58 | @app.route('/game//') 59 | def play_game(game_id, guess): 60 | 61 | try: 62 | game = get_game(game_id) 63 | except Exception as e: 64 | s = str(e) 65 | if s == 'GameNotFound' or s == 'GameWon': 66 | location = flask.url_for('new_game') 67 | print("play_game " + location) 68 | return redirect(location) 69 | 70 | won = False 71 | if guess > game['number']: 72 | message = "too big" 73 | attempts = incremet_attempts(game['id']) 74 | elif guess < game['number']: 75 | message = "too small" 76 | attempts = incremet_attempts(game['id']) 77 | else: 78 | attempts = win_game(game['id']) 79 | if attempts > 0: 80 | message = "correct" 81 | won = True 82 | else: 83 | message = "already won" 84 | 85 | response = { 86 | 'message': message, 87 | 'attempts': attempts, 88 | 'won': won 89 | } 90 | 91 | return jsonify(response) 92 | 93 | 94 | def create_game(): 95 | game_id = str(uuid.uuid4()) 96 | 97 | random_number = random.randint(MIN_NUMBER, MAX_NUMBER) 98 | game_ttl = int(time.time()) + TTL 99 | 100 | game = { 101 | 'id': game_id, 102 | 'min': MIN_NUMBER, 103 | 'max': MAX_NUMBER, 104 | 'number': random_number, 105 | 'attempts': 0, 106 | 'won': False, 107 | 'ttl': game_ttl 108 | } 109 | 110 | guess_the_number_table.put_item(Item=game) 111 | 112 | return game 113 | 114 | 115 | def get_game(game_id): 116 | 117 | resp = guess_the_number_table.get_item(Key={'id': game_id}) 118 | 119 | try: 120 | game = resp['Item'] 121 | except KeyError: 122 | game = None 123 | raise Exception('GameNotFound') 124 | 125 | return game 126 | 127 | 128 | def incremet_attempts(game_id): 129 | 130 | resp = guess_the_number_table.update_item( 131 | Key={ 132 | 'id': game_id 133 | }, 134 | ConditionExpression=Attr('won').eq(False), 135 | UpdateExpression='SET attempts = attempts + :val', 136 | ExpressionAttributeValues={ 137 | ':val': 1 138 | }, 139 | ReturnValues='UPDATED_NEW' 140 | ) 141 | 142 | attempts = resp['Attributes']['attempts'] 143 | 144 | return attempts 145 | 146 | 147 | def win_game(game_id): 148 | 149 | resp = guess_the_number_table.update_item( 150 | Key={ 151 | 'id': game_id 152 | }, 153 | ConditionExpression=Attr('won').eq(False), 154 | UpdateExpression='SET won = :val1, attempts = attempts + :val2', 155 | ExpressionAttributeValues={ 156 | ':val1': True, 157 | ':val2': 1 158 | }, 159 | ReturnValues='UPDATED_NEW' 160 | ) 161 | 162 | # Check that the table update worked 163 | try: 164 | attempts = resp['Attributes']['attempts'] 165 | except KeyError: 166 | return 0 167 | 168 | # Send SQS message to winners queue 169 | resp = guess_the_number_winners_queue.send_message( 170 | MessageBody='There is a winner in {} attempts!'.format(attempts) 171 | ) 172 | print(resp.get('MessageId')) 173 | print(resp.get('MD5OfMessageBody')) 174 | 175 | return attempts 176 | -------------------------------------------------------------------------------- /GuessTheNumber-Auto/src/requirements.txt: -------------------------------------------------------------------------------- 1 | boto3 2 | Flask 3 | opentelemetry-distro[otlp] 4 | opentelemetry-sdk-extension-aws 5 | opentelemetry-propagator-aws-xray -------------------------------------------------------------------------------- /GuessTheNumber-Auto/src/static/index.js: -------------------------------------------------------------------------------- 1 | const endpoint = document.getElementById('endpoint') 2 | const gameDiv = document.getElementById('game'); 3 | const startButton = document.getElementById('start'); 4 | 5 | let gameApi = location.href.replace(/\/$/, "") + "/game"; 6 | 7 | endpoint.value = gameApi; 8 | 9 | document.getElementById('endpointForm').addEventListener('submit', async function (e) { 10 | e.preventDefault(); // Stop form from submitting 11 | 12 | const response = await fetch(endpoint.value); 13 | 14 | const game = await response.json(); // Extract JSON from the HTTP response 15 | 16 | if (game.won) { 17 | return; 18 | } 19 | 20 | // Create guess form 21 | const form = document.createElement("form"); 22 | const gameMessage = document.createElement("p"); 23 | gameMessage.innerHTML = "Guess the number between " + game.min + " and " + game.max; 24 | form.appendChild(gameMessage); 25 | const attemptMessage = document.createElement("p"); 26 | attemptMessage.innerHTML = "Attempt 1 "; // First attempt 27 | form.appendChild(attemptMessage); 28 | const guessInput = document.createElement("input"); 29 | guessInput.type = "text"; 30 | form.appendChild(guessInput); 31 | form.appendChild(document.createTextNode(" ")); 32 | const guessSubmit = document.createElement("input"); 33 | guessSubmit.type = "submit"; 34 | guessSubmit.value = "Guess"; 35 | form.appendChild(guessSubmit); 36 | const guessMessage = document.createElement("p"); 37 | form.appendChild(guessMessage); 38 | gameDiv.innerHTML = ""; 39 | gameDiv.appendChild(form); 40 | guessInput.focus() 41 | 42 | // Process guess 43 | form.addEventListener('submit', async function (e) { 44 | e.preventDefault(); // Stop form from submitting 45 | 46 | guessNumber = parseInt(guessInput.value); 47 | if (isNaN(guessNumber)) { 48 | guessMessage.innerHTML = "Please enter a number"; 49 | return; 50 | } 51 | const guessEnpoint = endpoint.value + "/" + game.id + "/" + guessNumber; 52 | const response = await fetch(guessEnpoint); 53 | const guessGame = await response.json(); // Extract JSON from the HTTP response 54 | 55 | if (guessGame.won) { 56 | guessInput.disabled = true; 57 | guessSubmit.disabled = true; 58 | guessMessage.innerHTML = guessNumber + " is " + guessGame.message + " 👏"; 59 | gameMessage.innerHTML = "You won"; 60 | startButton.focus(); 61 | } else { 62 | nextAttempt = parseInt(guessGame.attempts) + 1 63 | attemptMessage.innerHTML = "Attempt " + nextAttempt; 64 | guessMessage.innerHTML = guessNumber + " is " + guessGame.message; 65 | } 66 | guessInput.value = ""; 67 | 68 | }); 69 | }); 70 | 71 | startButton.focus(); -------------------------------------------------------------------------------- /GuessTheNumber-Auto/src/static/style.css: -------------------------------------------------------------------------------- 1 | body { 2 | background-color: white; 3 | font-family: Arial, Helvetica, sans-serif; 4 | text-align: center; 5 | } 6 | 7 | h1 { 8 | color: blue; 9 | font-size: 48px; 10 | } 11 | 12 | p { 13 | color: navy; 14 | font-size: 24px; 15 | } 16 | 17 | input { 18 | background-color: lightyellow; 19 | font-size: 24px; 20 | } 21 | 22 | input[type=submit] { 23 | background-color: lightblue; 24 | font-size: 24px; 25 | } 26 | -------------------------------------------------------------------------------- /GuessTheNumber-Auto/src/templates/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Guess the Number 5 | 6 | 7 | 8 |

Guess the Number

9 |
10 |

API Endpoint

11 | 12 | 13 |
14 |
15 |
16 | 17 | 18 | -------------------------------------------------------------------------------- /GuessTheNumber-Manual-Lambda/Dockerfile: -------------------------------------------------------------------------------- 1 | FROM public.ecr.aws/docker/library/alpine:latest as layer-copy 2 | 3 | ARG AWS_DEFAULT_REGION=${AWS_DEFAULT_REGION:-"eu-west-1"} 4 | ARG AWS_ACCESS_KEY_ID=${AWS_ACCESS_KEY_ID:-""} 5 | ARG AWS_SECRET_ACCESS_KEY=${AWS_SECRET_ACCESS_KEY:-""} 6 | ENV AWS_DEFAULT_REGION=${AWS_DEFAULT_REGION} 7 | ENV AWS_ACCESS_KEY_ID=${AWS_ACCESS_KEY_ID} 8 | ENV AWS_SECRET_ACCESS_KEY=${AWS_SECRET_ACCESS_KEY} 9 | 10 | RUN apk add aws-cli curl unzip 11 | 12 | RUN mkdir -p /opt 13 | 14 | ARG TARGETARCH 15 | RUN curl $(aws lambda get-layer-version-by-arn --arn arn:aws:lambda:${AWS_DEFAULT_REGION}:901920570463:layer:aws-otel-python-${TARGETARCH}-ver-1-14-0:1 --query 'Content.Location' --output text) --output layer.zip 16 | RUN unzip layer.zip -d /opt 17 | 18 | FROM public.ecr.aws/docker/library/python:3.10-slim 19 | COPY --from=public.ecr.aws/awsguru/aws-lambda-adapter:0.5.1 /lambda-adapter /opt/extensions/lambda-adapter 20 | 21 | WORKDIR /opt 22 | COPY --from=layer-copy /opt . 23 | 24 | WORKDIR /app 25 | 26 | COPY src/requirements.txt requirements.txt 27 | RUN pip3 install -r requirements.txt 28 | 29 | COPY src . 30 | 31 | ENV OPENTELEMETRY_COLLECTOR_CONFIG_FILE='/app/collector-config.yaml' 32 | 33 | CMD /opt/otel-instrument flask run --host=0.0.0.0 --port=8080 34 | 35 | EXPOSE 8080 -------------------------------------------------------------------------------- /GuessTheNumber-Manual-Lambda/src/app.py: -------------------------------------------------------------------------------- 1 | # START OpenTelemetry Manual Instrumentation 2 | from opentelemetry import trace 3 | from opentelemetry import metrics 4 | # END OpenTelemetry Manual Instrumentation 5 | 6 | import uuid 7 | import time 8 | import random 9 | 10 | import boto3 11 | from boto3.dynamodb.conditions import Attr 12 | import flask 13 | from flask import Flask, render_template, jsonify, redirect 14 | 15 | # START OpenTelemetry Manual Instrumentation 16 | tracer = trace.get_tracer(__name__) 17 | meter = metrics.get_meter(__name__) 18 | 19 | game_counter = meter.create_counter( 20 | "game.counter", unit="1", description="Counts the number of games" 21 | ) 22 | 23 | game_not_found_counter = meter.create_counter( 24 | "game.notFound", unit="1", description="Counts the number of game IDs not found" 25 | ) 26 | 27 | attempt_counter = meter.create_counter( 28 | "attempt.counter", unit="1", description="Counts the number of attempts" 29 | ) 30 | 31 | won_counter = meter.create_counter( 32 | "won.counter", unit="1", description="Counts the amount of won games" 33 | ) 34 | 35 | already_won_counter = meter.create_counter( 36 | "won.already", unit="1", description="Counts the amount of games already won" 37 | ) 38 | # END OpenTelemetry Manual Instrumentation 39 | 40 | 41 | TABLE_NAME = 'guess-the-number' 42 | QUEUE_NAME = 'guess-the-number-winners' 43 | 44 | TTL = 24 * 60 * 60 # 1 day 45 | 46 | MIN_NUMBER = 1 47 | MAX_NUMBER = 100 48 | 49 | dynamodb = boto3.resource('dynamodb') 50 | sqs = boto3.resource('sqs') 51 | 52 | guess_the_number_table = dynamodb.Table(TABLE_NAME) 53 | guess_the_number_winners_queue = sqs.get_queue_by_name(QueueName=QUEUE_NAME) 54 | 55 | 56 | app = Flask(__name__) 57 | 58 | 59 | @app.route('/') 60 | def index(): 61 | return render_template("index.html") 62 | 63 | 64 | @app.route('/game') 65 | def new_game(): 66 | 67 | game = create_game() 68 | 69 | location = flask.url_for('describe_game', game_id=game['id']) 70 | print("new_game " + location) 71 | return redirect(location) 72 | 73 | 74 | @app.route('/game/') 75 | def describe_game(game_id): 76 | 77 | game = get_game(game_id) 78 | 79 | if game == None or game['won']: 80 | location = flask.url_for('new_game') 81 | print("describe_game " + location) 82 | return redirect(location) 83 | 84 | del game['number'] 85 | return jsonify(game) 86 | 87 | 88 | @app.route('/game//') 89 | def play_game(game_id, guess): 90 | 91 | try: 92 | game = get_game(game_id) 93 | except Exception as e: 94 | s = str(e) 95 | if s == 'GameNotFound' or s == 'GameWon': 96 | location = flask.url_for('new_game') 97 | print("play_game " + location) 98 | return redirect(location) 99 | 100 | won = False 101 | if guess > game['number']: 102 | message = "too big" 103 | attempts = incremet_attempts(game['id']) 104 | elif guess < game['number']: 105 | message = "too small" 106 | attempts = incremet_attempts(game['id']) 107 | else: 108 | attempts = win_game(game['id']) 109 | if attempts > 0: 110 | message = "correct" 111 | won = True 112 | else: 113 | message = "already won" 114 | 115 | response = { 116 | 'message': message, 117 | 'attempts': attempts, 118 | 'won': won 119 | } 120 | 121 | return jsonify(response) 122 | 123 | 124 | # ANNOTATION OpenTelemetry Manual Instrumentation 125 | @tracer.start_as_current_span("create_game") 126 | def create_game(): 127 | game_id = str(uuid.uuid4()) 128 | 129 | random_number = random.randint(MIN_NUMBER, MAX_NUMBER) 130 | game_ttl = int(time.time()) + TTL 131 | 132 | game = { 133 | 'id': game_id, 134 | 'min': MIN_NUMBER, 135 | 'max': MAX_NUMBER, 136 | 'number': random_number, 137 | 'attempts': 0, 138 | 'won': False, 139 | 'ttl': game_ttl 140 | } 141 | 142 | guess_the_number_table.put_item(Item=game) 143 | 144 | # START OpenTelemetry Manual Instrumentation 145 | game_counter.add(1) 146 | current_span = trace.get_current_span() 147 | current_span.set_attribute("game.id", game_id) 148 | current_span.set_attribute("game.number", random_number) 149 | # END OpenTelemetry Manual Instrumentation 150 | 151 | return game 152 | 153 | 154 | def get_game(game_id): 155 | # START OpenTelemetry Manual Instrumentation 156 | with tracer.start_as_current_span("get_game") as span: 157 | # END OpenTelemetry Manual Instrumentation 158 | 159 | resp = guess_the_number_table.get_item(Key={'id': game_id}) 160 | 161 | try: 162 | game = resp['Item'] 163 | # START OpenTelemetry Manual Instrumentation 164 | span.set_attribute("game.id", game_id) 165 | span.set_attribute("game.attempts", int(game['attempts'])) 166 | # END OpenTelemetry Manual Instrumentation 167 | except KeyError: 168 | # START OpenTelemetry Manual Instrumentation 169 | game_not_found_counter.add(1) 170 | span.set_attribute("game.notFound", game_id) 171 | # END OpenTelemetry Manual Instrumentation 172 | raise Exception('GameNotFound') 173 | 174 | return game 175 | 176 | 177 | # ANNOTATION OpenTelemetry Manual Instrumentation 178 | @tracer.start_as_current_span("incremet_attempts") 179 | def incremet_attempts(game_id): 180 | 181 | resp=guess_the_number_table.update_item( 182 | Key={ 183 | 'id': game_id 184 | }, 185 | ConditionExpression = Attr('won').eq(False), 186 | UpdateExpression = 'SET attempts = attempts + :val', 187 | ExpressionAttributeValues = { 188 | ':val': 1 189 | }, 190 | ReturnValues = 'UPDATED_NEW' 191 | ) 192 | 193 | # Check that the table update worked 194 | try: 195 | attempts=resp['Attributes']['attempts'] 196 | except KeyError: 197 | # START OpenTelemetry Manual Instrumentation 198 | game_not_found_counter.add(1) 199 | current_span=trace.get_current_span() 200 | current_span.set_attribute("game.notFound", game_id) 201 | # END OpenTelemetry Manual Instrumentation 202 | return 0 203 | 204 | # START OpenTelemetry Manual Instrumentation 205 | attempt_counter.add(1) 206 | current_span=trace.get_current_span() 207 | current_span.set_attribute("game.id", game_id) 208 | current_span.set_attribute("game.attempts", int(attempts)) 209 | # END OpenTelemetry Manual Instrumentation 210 | 211 | return attempts 212 | 213 | 214 | # ANNOTATION OpenTelemetry Manual Instrumentation 215 | @tracer.start_as_current_span("win_game") 216 | def win_game(game_id): 217 | 218 | resp=guess_the_number_table.update_item( 219 | Key = { 220 | 'id': game_id 221 | }, 222 | ConditionExpression = Attr('won').eq(False), 223 | UpdateExpression = 'SET won = :val1, attempts = attempts + :val2', 224 | ExpressionAttributeValues = { 225 | ':val1': True, 226 | ':val2': 1 227 | }, 228 | ReturnValues = 'UPDATED_NEW' 229 | ) 230 | 231 | # Check that the table update worked 232 | try: 233 | attempts=resp['Attributes']['attempts'] 234 | except KeyError: 235 | # START OpenTelemetry Manual Instrumentation 236 | current_span=trace.get_current_span() 237 | current_span.set_attribute("game.id", game_id) 238 | # END OpenTelemetry Manual Instrumentation 239 | return 0 240 | 241 | # Send SQS message to winners queue 242 | resp=guess_the_number_winners_queue.send_message( 243 | MessageBody = 'There is a winner in {} attempts!'.format(attempts) 244 | ) 245 | 246 | # START OpenTelemetry Manual Instrumentation 247 | won_counter.add(1) 248 | current_span=trace.get_current_span() 249 | current_span.set_attribute("game.id", game_id) 250 | current_span.set_attribute("game.attempts", int(attempts)) 251 | # END OpenTelemetry Manual Instrumentation 252 | 253 | return attempts 254 | -------------------------------------------------------------------------------- /GuessTheNumber-Manual-Lambda/src/collector-config.yaml: -------------------------------------------------------------------------------- 1 | extensions: 2 | sigv4auth: 3 | service: "aps" 4 | region: "us-west-2" 5 | 6 | receivers: 7 | otlp: 8 | protocols: 9 | grpc: 10 | http: 11 | 12 | exporters: 13 | logging: 14 | awsxray: 15 | awsemf: 16 | prometheusremotewrite: 17 | endpoint: "https://aps-workspaces.us-west-2.amazonaws.com/workspaces/ws-0bff5472-a617-4585-bd7a-327addb3386e/api/v1/remote_write" 18 | auth: 19 | authenticator: sigv4auth 20 | 21 | service: 22 | pipelines: 23 | traces: 24 | receivers: [otlp] 25 | exporters: [awsxray] 26 | metrics: 27 | receivers: [otlp] 28 | exporters: [awsemf, prometheusremotewrite] 29 | extensions: [sigv4auth] 30 | -------------------------------------------------------------------------------- /GuessTheNumber-Manual-Lambda/src/requirements.txt: -------------------------------------------------------------------------------- 1 | boto3 2 | Flask 3 | opentelemetry-distro[otlp] 4 | opentelemetry-sdk-extension-aws 5 | opentelemetry-propagator-aws-xray -------------------------------------------------------------------------------- /GuessTheNumber-Manual-Lambda/src/static/index.js: -------------------------------------------------------------------------------- 1 | const endpoint = document.getElementById('endpoint') 2 | const gameDiv = document.getElementById('game'); 3 | const startButton = document.getElementById('start'); 4 | 5 | let gameApi = location.href.replace(/\/$/, "") + "/game"; 6 | 7 | endpoint.value = gameApi; 8 | 9 | document.getElementById('endpointForm').addEventListener('submit', async function (e) { 10 | e.preventDefault(); // Stop form from submitting 11 | 12 | const response = await fetch(endpoint.value); 13 | 14 | const game = await response.json(); // Extract JSON from the HTTP response 15 | 16 | if (game.won) { 17 | return; 18 | } 19 | 20 | // Create guess form 21 | const form = document.createElement("form"); 22 | const gameMessage = document.createElement("p"); 23 | gameMessage.innerHTML = "Guess the number between " + game.min + " and " + game.max; 24 | form.appendChild(gameMessage); 25 | const attemptMessage = document.createElement("p"); 26 | attemptMessage.innerHTML = "Attempt 1 "; // First attempt 27 | form.appendChild(attemptMessage); 28 | const guessInput = document.createElement("input"); 29 | guessInput.type = "text"; 30 | form.appendChild(guessInput); 31 | form.appendChild(document.createTextNode(" ")); 32 | const guessSubmit = document.createElement("input"); 33 | guessSubmit.type = "submit"; 34 | guessSubmit.value = "Guess"; 35 | form.appendChild(guessSubmit); 36 | const guessMessage = document.createElement("p"); 37 | form.appendChild(guessMessage); 38 | gameDiv.innerHTML = ""; 39 | gameDiv.appendChild(form); 40 | guessInput.focus() 41 | 42 | // Process guess 43 | form.addEventListener('submit', async function (e) { 44 | e.preventDefault(); // Stop form from submitting 45 | 46 | guessNumber = parseInt(guessInput.value); 47 | if (isNaN(guessNumber)) { 48 | guessMessage.innerHTML = "Please enter a number"; 49 | return; 50 | } 51 | const guessEnpoint = endpoint.value + "/" + game.id + "/" + guessNumber; 52 | const response = await fetch(guessEnpoint); 53 | const guessGame = await response.json(); // Extract JSON from the HTTP response 54 | 55 | if (guessGame.won) { 56 | guessInput.disabled = true; 57 | guessSubmit.disabled = true; 58 | guessMessage.innerHTML = guessNumber + " is " + guessGame.message + " 👏"; 59 | gameMessage.innerHTML = "You won"; 60 | startButton.focus(); 61 | } else { 62 | nextAttempt = parseInt(guessGame.attempts) + 1 63 | attemptMessage.innerHTML = "Attempt " + nextAttempt; 64 | guessMessage.innerHTML = guessNumber + " is " + guessGame.message; 65 | } 66 | guessInput.value = ""; 67 | 68 | }); 69 | }); 70 | 71 | startButton.focus(); -------------------------------------------------------------------------------- /GuessTheNumber-Manual-Lambda/src/static/style.css: -------------------------------------------------------------------------------- 1 | body { 2 | background-color: white; 3 | font-family: Arial, Helvetica, sans-serif; 4 | text-align: center; 5 | } 6 | 7 | h1 { 8 | color: blue; 9 | font-size: 48px; 10 | } 11 | 12 | p { 13 | color: navy; 14 | font-size: 24px; 15 | } 16 | 17 | input { 18 | background-color: lightyellow; 19 | font-size: 24px; 20 | } 21 | 22 | input[type=submit] { 23 | background-color: lightblue; 24 | font-size: 24px; 25 | } 26 | -------------------------------------------------------------------------------- /GuessTheNumber-Manual-Lambda/src/templates/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Guess the Number 5 | 6 | 7 | 8 |

Guess the Number

9 |
10 |

API Endpoint

11 | 12 | 13 |
14 |
15 |
16 | 17 | 18 | -------------------------------------------------------------------------------- /GuessTheNumber-Manual/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/danilop/reInvent2022-BOA310/14440c8d98ee1750a0e853a37d649d89ba8c133a/GuessTheNumber-Manual/.DS_Store -------------------------------------------------------------------------------- /GuessTheNumber-Manual/Dockerfile: -------------------------------------------------------------------------------- 1 | FROM public.ecr.aws/docker/library/python:3.10-slim 2 | 3 | WORKDIR /app 4 | 5 | COPY src/requirements.txt requirements.txt 6 | RUN pip3 install -r requirements.txt 7 | 8 | COPY src . 9 | 10 | RUN opentelemetry-bootstrap -a install 11 | 12 | ENV OTEL_PYTHON_DISABLED_INSTRUMENTATIONS=urllib3 13 | ENV OTEL_RESOURCE_ATTRIBUTES='service.name=guess-the-number' 14 | 15 | CMD OTEL_PROPAGATORS=xray OTEL_PYTHON_ID_GENERATOR=xray opentelemetry-instrument flask run --host=0.0.0.0 --port=8080 16 | 17 | EXPOSE 8080 -------------------------------------------------------------------------------- /GuessTheNumber-Manual/collector-config.yaml: -------------------------------------------------------------------------------- 1 | extensions: 2 | sigv4auth: 3 | service: "aps" 4 | region: "eu-west-1" 5 | 6 | receivers: 7 | otlp: 8 | protocols: 9 | grpc: 10 | http: 11 | awsecscontainermetrics: 12 | 13 | exporters: 14 | logging: 15 | awsxray: 16 | awsemf: 17 | log_group_name: 'AOTLogGroup' 18 | log_stream_name: 'AOTLogStream' 19 | namespace: 'AOTMetricNS' 20 | prometheusremotewrite: 21 | endpoint: "${AWS_PROMETHEUS_ENDPOINT}" 22 | auth: 23 | authenticator: sigv4auth 24 | resource_to_telemetry_conversion: 25 | enabled: true 26 | 27 | service: 28 | pipelines: 29 | traces: 30 | receivers: [otlp] 31 | exporters: [awsxray] 32 | metrics/application: 33 | receivers: [otlp] 34 | exporters: [awsemf, prometheusremotewrite] 35 | metrics: 36 | receivers: [awsecscontainermetrics] 37 | exporters: [awsemf, prometheusremotewrite] 38 | extensions: [sigv4auth] 39 | -------------------------------------------------------------------------------- /GuessTheNumber-Manual/src/app.py: -------------------------------------------------------------------------------- 1 | # START OpenTelemetry Manual Instrumentation 2 | from opentelemetry import trace 3 | from opentelemetry import metrics 4 | # END OpenTelemetry Manual Instrumentation 5 | 6 | import uuid 7 | import time 8 | import random 9 | 10 | import boto3 11 | from boto3.dynamodb.conditions import Attr 12 | import flask 13 | from flask import Flask, render_template, jsonify, redirect 14 | 15 | # START OpenTelemetry Manual Instrumentation 16 | tracer = trace.get_tracer(__name__) 17 | meter = metrics.get_meter(__name__) 18 | 19 | game_counter = meter.create_counter( 20 | "game.counter", unit="1", description="Counts the number of games" 21 | ) 22 | 23 | game_not_found_counter = meter.create_counter( 24 | "game.notFound", unit="1", description="Counts the number of game IDs not found" 25 | ) 26 | 27 | attempt_counter = meter.create_counter( 28 | "attempt.counter", unit="1", description="Counts the number of attempts" 29 | ) 30 | 31 | won_counter = meter.create_counter( 32 | "won.counter", unit="1", description="Counts the amount of won games" 33 | ) 34 | 35 | already_won_counter = meter.create_counter( 36 | "won.already", unit="1", description="Counts the amount of games already won" 37 | ) 38 | # END OpenTelemetry Manual Instrumentation 39 | 40 | 41 | TABLE_NAME = 'guess-the-number' 42 | QUEUE_NAME = 'guess-the-number-winners' 43 | 44 | TTL = 24 * 60 * 60 # 1 day 45 | 46 | MIN_NUMBER = 1 47 | MAX_NUMBER = 100 48 | 49 | dynamodb = boto3.resource('dynamodb') 50 | sqs = boto3.resource('sqs') 51 | 52 | guess_the_number_table = dynamodb.Table(TABLE_NAME) 53 | guess_the_number_winners_queue = sqs.get_queue_by_name(QueueName=QUEUE_NAME) 54 | 55 | 56 | app = Flask(__name__) 57 | 58 | 59 | @app.route('/') 60 | def index(): 61 | return render_template("index.html") 62 | 63 | 64 | @app.route('/game') 65 | def new_game(): 66 | 67 | game = create_game() 68 | 69 | location = flask.url_for('describe_game', game_id=game['id']) 70 | print("new_game " + location) 71 | return redirect(location) 72 | 73 | 74 | @app.route('/game/') 75 | def describe_game(game_id): 76 | 77 | game = get_game(game_id) 78 | 79 | if game == None or game['won']: 80 | location = flask.url_for('new_game') 81 | print("describe_game " + location) 82 | return redirect(location) 83 | 84 | del game['number'] 85 | return jsonify(game) 86 | 87 | 88 | @app.route('/game//') 89 | def play_game(game_id, guess): 90 | 91 | try: 92 | game = get_game(game_id) 93 | except Exception as e: 94 | s = str(e) 95 | if s == 'GameNotFound' or s == 'GameWon': 96 | location = flask.url_for('new_game') 97 | print("play_game " + location) 98 | return redirect(location) 99 | 100 | won = False 101 | if guess > game['number']: 102 | message = "too big" 103 | attempts = incremet_attempts(game['id']) 104 | elif guess < game['number']: 105 | message = "too small" 106 | attempts = incremet_attempts(game['id']) 107 | else: 108 | attempts = win_game(game['id']) 109 | if attempts > 0: 110 | message = "correct" 111 | won = True 112 | else: 113 | message = "already won" 114 | 115 | response = { 116 | 'message': message, 117 | 'attempts': attempts, 118 | 'won': won 119 | } 120 | 121 | return jsonify(response) 122 | 123 | 124 | # ANNOTATION OpenTelemetry Manual Instrumentation 125 | @tracer.start_as_current_span("create_game") 126 | def create_game(): 127 | game_id = str(uuid.uuid4()) 128 | 129 | random_number = random.randint(MIN_NUMBER, MAX_NUMBER) 130 | game_ttl = int(time.time()) + TTL 131 | 132 | game = { 133 | 'id': game_id, 134 | 'min': MIN_NUMBER, 135 | 'max': MAX_NUMBER, 136 | 'number': random_number, 137 | 'attempts': 0, 138 | 'won': False, 139 | 'ttl': game_ttl 140 | } 141 | 142 | guess_the_number_table.put_item(Item=game) 143 | 144 | # START OpenTelemetry Manual Instrumentation 145 | game_counter.add(1) 146 | current_span = trace.get_current_span() 147 | current_span.set_attribute("game.id", game_id) 148 | current_span.set_attribute("game.number", random_number) 149 | # END OpenTelemetry Manual Instrumentation 150 | 151 | return game 152 | 153 | 154 | # ANNOTATION OpenTelemetry Manual Instrumentation 155 | # @tracer.start_as_current_span("get_game") 156 | def get_game(game_id): 157 | # START OpenTelemetry Manual Instrumentation 158 | with tracer.start_as_current_span("get_game") as span: 159 | # END OpenTelemetry Manual Instrumentation 160 | 161 | resp = guess_the_number_table.get_item(Key={'id': game_id}) 162 | 163 | try: 164 | game = resp['Item'] 165 | # START OpenTelemetry Manual Instrumentation 166 | span.set_attribute("game.id", game_id) 167 | span.set_attribute("game.attempts", int(game['attempts'])) 168 | # END OpenTelemetry Manual Instrumentation 169 | except KeyError: 170 | game=None 171 | # START OpenTelemetry Manual Instrumentation 172 | game_not_found_counter.add(1) 173 | span.set_attribute("game.notFound", game_id) 174 | # END OpenTelemetry Manual Instrumentation 175 | raise Exception('GameNotFound') 176 | 177 | return game 178 | 179 | 180 | # ANNOTATION OpenTelemetry Manual Instrumentation 181 | @tracer.start_as_current_span("incremet_attempts") 182 | def incremet_attempts(game_id): 183 | 184 | resp=guess_the_number_table.update_item( 185 | Key={ 186 | 'id': game_id 187 | }, 188 | ConditionExpression = Attr('won').eq(False), 189 | UpdateExpression = 'SET attempts = attempts + :val', 190 | ExpressionAttributeValues = { 191 | ':val': 1 192 | }, 193 | ReturnValues = 'UPDATED_NEW' 194 | ) 195 | 196 | # Check that the table update worked 197 | try: 198 | attempts=resp['Attributes']['attempts'] 199 | except KeyError: 200 | # START OpenTelemetry Manual Instrumentation 201 | game_not_found_counter.add(1) 202 | current_span=trace.get_current_span() 203 | current_span.set_attribute("game.notFound", game_id) 204 | # END OpenTelemetry Manual Instrumentation 205 | return 0 206 | 207 | # START OpenTelemetry Manual Instrumentation 208 | attempt_counter.add(1) 209 | current_span=trace.get_current_span() 210 | current_span.set_attribute("game.id", game_id) 211 | current_span.set_attribute("game.attempts", int(attempts)) 212 | # END OpenTelemetry Manual Instrumentation 213 | 214 | return attempts 215 | 216 | 217 | # ANNOTATION OpenTelemetry Manual Instrumentation 218 | @tracer.start_as_current_span("win_game") 219 | def win_game(game_id): 220 | 221 | resp=guess_the_number_table.update_item( 222 | Key = { 223 | 'id': game_id 224 | }, 225 | ConditionExpression = Attr('won').eq(False), 226 | UpdateExpression = 'SET won = :val1, attempts = attempts + :val2', 227 | ExpressionAttributeValues = { 228 | ':val1': True, 229 | ':val2': 1 230 | }, 231 | ReturnValues = 'UPDATED_NEW' 232 | ) 233 | 234 | # Check that the table update worked 235 | try: 236 | attempts=resp['Attributes']['attempts'] 237 | except KeyError: 238 | # START OpenTelemetry Manual Instrumentation 239 | current_span=trace.get_current_span() 240 | current_span.set_attribute("game.id", game_id) 241 | # END OpenTelemetry Manual Instrumentation 242 | return 0 243 | 244 | # Send SQS message to winners queue 245 | resp=guess_the_number_winners_queue.send_message( 246 | MessageBody = 'There is a winner in {} attempts!'.format(attempts) 247 | ) 248 | 249 | # START OpenTelemetry Manual Instrumentation 250 | won_counter.add(1) 251 | current_span=trace.get_current_span() 252 | current_span.set_attribute("game.id", game_id) 253 | current_span.set_attribute("game.attempts", int(attempts)) 254 | # END OpenTelemetry Manual Instrumentation 255 | 256 | return attempts 257 | -------------------------------------------------------------------------------- /GuessTheNumber-Manual/src/requirements.txt: -------------------------------------------------------------------------------- 1 | boto3 2 | Flask 3 | opentelemetry-distro[otlp] 4 | opentelemetry-sdk-extension-aws 5 | opentelemetry-propagator-aws-xray 6 | -------------------------------------------------------------------------------- /GuessTheNumber-Manual/src/static/index.js: -------------------------------------------------------------------------------- 1 | const endpoint = document.getElementById('endpoint') 2 | const gameDiv = document.getElementById('game'); 3 | const startButton = document.getElementById('start'); 4 | 5 | let gameApi = location.href.replace(/\/$/, "") + "/game"; 6 | 7 | endpoint.value = gameApi; 8 | 9 | document.getElementById('endpointForm').addEventListener('submit', async function (e) { 10 | e.preventDefault(); // Stop form from submitting 11 | 12 | const response = await fetch(endpoint.value); 13 | 14 | const game = await response.json(); // Extract JSON from the HTTP response 15 | 16 | if (game.won) { 17 | return; 18 | } 19 | 20 | // Create guess form 21 | const form = document.createElement("form"); 22 | const gameMessage = document.createElement("p"); 23 | gameMessage.innerHTML = "Guess the number between " + game.min + " and " + game.max; 24 | form.appendChild(gameMessage); 25 | const attemptMessage = document.createElement("p"); 26 | attemptMessage.innerHTML = "Attempt 1 "; // First attempt 27 | form.appendChild(attemptMessage); 28 | const guessInput = document.createElement("input"); 29 | guessInput.type = "text"; 30 | form.appendChild(guessInput); 31 | form.appendChild(document.createTextNode(" ")); 32 | const guessSubmit = document.createElement("input"); 33 | guessSubmit.type = "submit"; 34 | guessSubmit.value = "Guess"; 35 | form.appendChild(guessSubmit); 36 | const guessMessage = document.createElement("p"); 37 | form.appendChild(guessMessage); 38 | gameDiv.innerHTML = ""; 39 | gameDiv.appendChild(form); 40 | guessInput.focus() 41 | 42 | // Process guess 43 | form.addEventListener('submit', async function (e) { 44 | e.preventDefault(); // Stop form from submitting 45 | 46 | guessNumber = parseInt(guessInput.value); 47 | if (isNaN(guessNumber)) { 48 | guessMessage.innerHTML = "Please enter a number"; 49 | return; 50 | } 51 | const guessEnpoint = endpoint.value + "/" + game.id + "/" + guessNumber; 52 | const response = await fetch(guessEnpoint); 53 | const guessGame = await response.json(); // Extract JSON from the HTTP response 54 | 55 | if (guessGame.won) { 56 | guessInput.disabled = true; 57 | guessSubmit.disabled = true; 58 | guessMessage.innerHTML = guessNumber + " is " + guessGame.message + " 👏"; 59 | gameMessage.innerHTML = "You won"; 60 | startButton.focus(); 61 | } else { 62 | nextAttempt = parseInt(guessGame.attempts) + 1 63 | attemptMessage.innerHTML = "Attempt " + nextAttempt; 64 | guessMessage.innerHTML = guessNumber + " is " + guessGame.message; 65 | } 66 | guessInput.value = ""; 67 | 68 | }); 69 | }); 70 | 71 | startButton.focus(); -------------------------------------------------------------------------------- /GuessTheNumber-Manual/src/static/style.css: -------------------------------------------------------------------------------- 1 | body { 2 | background-color: white; 3 | font-family: Arial, Helvetica, sans-serif; 4 | text-align: center; 5 | } 6 | 7 | h1 { 8 | color: blue; 9 | font-size: 48px; 10 | } 11 | 12 | p { 13 | color: navy; 14 | font-size: 24px; 15 | } 16 | 17 | input { 18 | background-color: lightyellow; 19 | font-size: 24px; 20 | } 21 | 22 | input[type=submit] { 23 | background-color: lightblue; 24 | font-size: 24px; 25 | } 26 | -------------------------------------------------------------------------------- /GuessTheNumber-Manual/src/templates/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Guess the Number 5 | 6 | 7 | 8 |

Guess the Number

9 |
10 |

API Endpoint

11 | 12 | 13 |
14 |
15 |
16 | 17 | 18 | -------------------------------------------------------------------------------- /GuessTheNumber-SAM/.gitignore: -------------------------------------------------------------------------------- 1 | 2 | # Created by https://www.gitignore.io/api/osx,linux,python,windows,pycharm,visualstudiocode 3 | 4 | ### Linux ### 5 | *~ 6 | 7 | # temporary files which can be created if a process still has a handle open of a deleted file 8 | .fuse_hidden* 9 | 10 | # KDE directory preferences 11 | .directory 12 | 13 | # Linux trash folder which might appear on any partition or disk 14 | .Trash-* 15 | 16 | # .nfs files are created when an open file is removed but is still being accessed 17 | .nfs* 18 | 19 | ### OSX ### 20 | *.DS_Store 21 | .AppleDouble 22 | .LSOverride 23 | 24 | # Icon must end with two \r 25 | Icon 26 | 27 | # Thumbnails 28 | ._* 29 | 30 | # Files that might appear in the root of a volume 31 | .DocumentRevisions-V100 32 | .fseventsd 33 | .Spotlight-V100 34 | .TemporaryItems 35 | .Trashes 36 | .VolumeIcon.icns 37 | .com.apple.timemachine.donotpresent 38 | 39 | # Directories potentially created on remote AFP share 40 | .AppleDB 41 | .AppleDesktop 42 | Network Trash Folder 43 | Temporary Items 44 | .apdisk 45 | 46 | ### PyCharm ### 47 | # Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio and Webstorm 48 | # Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839 49 | 50 | # User-specific stuff: 51 | .idea/**/workspace.xml 52 | .idea/**/tasks.xml 53 | .idea/dictionaries 54 | 55 | # Sensitive or high-churn files: 56 | .idea/**/dataSources/ 57 | .idea/**/dataSources.ids 58 | .idea/**/dataSources.xml 59 | .idea/**/dataSources.local.xml 60 | .idea/**/sqlDataSources.xml 61 | .idea/**/dynamic.xml 62 | .idea/**/uiDesigner.xml 63 | 64 | # Gradle: 65 | .idea/**/gradle.xml 66 | .idea/**/libraries 67 | 68 | # CMake 69 | cmake-build-debug/ 70 | 71 | # Mongo Explorer plugin: 72 | .idea/**/mongoSettings.xml 73 | 74 | ## File-based project format: 75 | *.iws 76 | 77 | ## Plugin-specific files: 78 | 79 | # IntelliJ 80 | /out/ 81 | 82 | # mpeltonen/sbt-idea plugin 83 | .idea_modules/ 84 | 85 | # JIRA plugin 86 | atlassian-ide-plugin.xml 87 | 88 | # Cursive Clojure plugin 89 | .idea/replstate.xml 90 | 91 | # Ruby plugin and RubyMine 92 | /.rakeTasks 93 | 94 | # Crashlytics plugin (for Android Studio and IntelliJ) 95 | com_crashlytics_export_strings.xml 96 | crashlytics.properties 97 | crashlytics-build.properties 98 | fabric.properties 99 | 100 | ### PyCharm Patch ### 101 | # Comment Reason: https://github.com/joeblau/gitignore.io/issues/186#issuecomment-215987721 102 | 103 | # *.iml 104 | # modules.xml 105 | # .idea/misc.xml 106 | # *.ipr 107 | 108 | # Sonarlint plugin 109 | .idea/sonarlint 110 | 111 | ### Python ### 112 | # Byte-compiled / optimized / DLL files 113 | __pycache__/ 114 | *.py[cod] 115 | *$py.class 116 | 117 | # C extensions 118 | *.so 119 | 120 | # Distribution / packaging 121 | .Python 122 | build/ 123 | develop-eggs/ 124 | dist/ 125 | downloads/ 126 | eggs/ 127 | .eggs/ 128 | lib/ 129 | lib64/ 130 | parts/ 131 | sdist/ 132 | var/ 133 | wheels/ 134 | *.egg-info/ 135 | .installed.cfg 136 | *.egg 137 | 138 | # PyInstaller 139 | # Usually these files are written by a python script from a template 140 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 141 | *.manifest 142 | *.spec 143 | 144 | # Installer logs 145 | pip-log.txt 146 | pip-delete-this-directory.txt 147 | 148 | # Unit test / coverage reports 149 | htmlcov/ 150 | .tox/ 151 | .coverage 152 | .coverage.* 153 | .cache 154 | .pytest_cache/ 155 | nosetests.xml 156 | coverage.xml 157 | *.cover 158 | .hypothesis/ 159 | 160 | # Translations 161 | *.mo 162 | *.pot 163 | 164 | # Flask stuff: 165 | instance/ 166 | .webassets-cache 167 | 168 | # Scrapy stuff: 169 | .scrapy 170 | 171 | # Sphinx documentation 172 | docs/_build/ 173 | 174 | # PyBuilder 175 | target/ 176 | 177 | # Jupyter Notebook 178 | .ipynb_checkpoints 179 | 180 | # pyenv 181 | .python-version 182 | 183 | # celery beat schedule file 184 | celerybeat-schedule.* 185 | 186 | # SageMath parsed files 187 | *.sage.py 188 | 189 | # Environments 190 | .env 191 | .venv 192 | env/ 193 | venv/ 194 | ENV/ 195 | env.bak/ 196 | venv.bak/ 197 | 198 | # Spyder project settings 199 | .spyderproject 200 | .spyproject 201 | 202 | # Rope project settings 203 | .ropeproject 204 | 205 | # mkdocs documentation 206 | /site 207 | 208 | # mypy 209 | .mypy_cache/ 210 | 211 | ### VisualStudioCode ### 212 | .vscode/* 213 | !.vscode/settings.json 214 | !.vscode/tasks.json 215 | !.vscode/launch.json 216 | !.vscode/extensions.json 217 | .history 218 | 219 | ### Windows ### 220 | # Windows thumbnail cache files 221 | Thumbs.db 222 | ehthumbs.db 223 | ehthumbs_vista.db 224 | 225 | # Folder config file 226 | Desktop.ini 227 | 228 | # Recycle Bin used on file shares 229 | $RECYCLE.BIN/ 230 | 231 | # Windows Installer files 232 | *.cab 233 | *.msi 234 | *.msm 235 | *.msp 236 | 237 | # Windows shortcuts 238 | *.lnk 239 | 240 | # Build folder 241 | 242 | */build/* 243 | 244 | # End of https://www.gitignore.io/api/osx,linux,python,windows,pycharm,visualstudiocode -------------------------------------------------------------------------------- /GuessTheNumber-SAM/README.md: -------------------------------------------------------------------------------- 1 | # GuessTheNumber-SAM -------------------------------------------------------------------------------- /GuessTheNumber-SAM/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/danilop/reInvent2022-BOA310/14440c8d98ee1750a0e853a37d649d89ba8c133a/GuessTheNumber-SAM/__init__.py -------------------------------------------------------------------------------- /GuessTheNumber-SAM/guess_the_number/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/danilop/reInvent2022-BOA310/14440c8d98ee1750a0e853a37d649d89ba8c133a/GuessTheNumber-SAM/guess_the_number/__init__.py -------------------------------------------------------------------------------- /GuessTheNumber-SAM/guess_the_number/app.py: -------------------------------------------------------------------------------- 1 | # START Wrap a WSGI application in an AWS Lambda handler function 2 | from apig_wsgi import make_lambda_handler 3 | # END Wrap a WSGI application in an AWS Lambda handler function 4 | 5 | # START OpenTelemetry Manual Instrumentation 6 | from opentelemetry import trace 7 | from opentelemetry import metrics 8 | # END OpenTelemetry Manual Instrumentation 9 | 10 | import uuid 11 | import time 12 | import random 13 | 14 | import boto3 15 | from boto3.dynamodb.conditions import Attr 16 | import flask 17 | from flask import Flask, render_template, jsonify, redirect 18 | 19 | # START OpenTelemetry Manual Instrumentation 20 | tracer = trace.get_tracer(__name__) 21 | meter = metrics.get_meter(__name__) 22 | 23 | game_counter = meter.create_counter( 24 | "game.counter", unit="1", description="Counts the number of games" 25 | ) 26 | 27 | game_not_found_counter = meter.create_counter( 28 | "game.notFound", unit="1", description="Counts the number of game IDs not found" 29 | ) 30 | 31 | attempt_counter = meter.create_counter( 32 | "attempt.counter", unit="1", description="Counts the number of attempts" 33 | ) 34 | 35 | won_counter = meter.create_counter( 36 | "won.counter", unit="1", description="Counts the amount of won games" 37 | ) 38 | 39 | already_won_counter = meter.create_counter( 40 | "won.already", unit="1", description="Counts the amount of games already won" 41 | ) 42 | # END OpenTelemetry Manual Instrumentation 43 | 44 | 45 | TABLE_NAME = 'guess-the-number' 46 | QUEUE_NAME = 'guess-the-number-winners' 47 | 48 | TTL = 24 * 60 * 60 # 1 day 49 | 50 | MIN_NUMBER = 1 51 | MAX_NUMBER = 100 52 | 53 | dynamodb = boto3.resource('dynamodb') 54 | sqs = boto3.resource('sqs') 55 | 56 | guess_the_number_table = dynamodb.Table(TABLE_NAME) 57 | guess_the_number_winners_queue = sqs.get_queue_by_name(QueueName=QUEUE_NAME) 58 | 59 | 60 | app = Flask(__name__) 61 | 62 | # START Wrap a WSGI application in an AWS Lambda handler function 63 | lambda_handler = make_lambda_handler(app) 64 | # END Wrap a WSGI application in an AWS Lambda handler function 65 | 66 | 67 | @app.route('/') 68 | def index(): 69 | return render_template("index.html") 70 | 71 | 72 | @app.route('/game') 73 | def new_game(): 74 | 75 | game = create_game() 76 | 77 | location = flask.url_for('describe_game', game_id=game['id']) 78 | print("new_game " + location) 79 | return redirect(location) 80 | 81 | 82 | @app.route('/game/') 83 | def describe_game(game_id): 84 | 85 | game = get_game(game_id) 86 | 87 | if game == None or game['won']: 88 | location = flask.url_for('new_game') 89 | print("describe_game " + location) 90 | return redirect(location) 91 | 92 | del game['number'] 93 | return jsonify(game) 94 | 95 | 96 | @app.route('/game//') 97 | def play_game(game_id, guess): 98 | 99 | try: 100 | game = get_game(game_id) 101 | except Exception as e: 102 | s = str(e) 103 | if s == 'GameNotFound' or s == 'GameWon': 104 | location = flask.url_for('new_game') 105 | print("play_game " + location) 106 | return redirect(location) 107 | 108 | won = False 109 | if guess > game['number']: 110 | message = "too big" 111 | attempts = incremet_attempts(game['id']) 112 | elif guess < game['number']: 113 | message = "too small" 114 | attempts = incremet_attempts(game['id']) 115 | else: 116 | attempts = win_game(game['id']) 117 | if attempts > 0: 118 | message = "correct" 119 | won = True 120 | else: 121 | message = "already won" 122 | 123 | response = { 124 | 'message': message, 125 | 'attempts': attempts, 126 | 'won': won 127 | } 128 | 129 | return jsonify(response) 130 | 131 | 132 | # ANNOTATION OpenTelemetry Manual Instrumentation 133 | @tracer.start_as_current_span("create_game") 134 | def create_game(): 135 | game_id = str(uuid.uuid4()) 136 | 137 | random_number = random.randint(MIN_NUMBER, MAX_NUMBER) 138 | game_ttl = int(time.time()) + TTL 139 | 140 | game = { 141 | 'id': game_id, 142 | 'min': MIN_NUMBER, 143 | 'max': MAX_NUMBER, 144 | 'number': random_number, 145 | 'attempts': 0, 146 | 'won': False, 147 | 'ttl': game_ttl 148 | } 149 | 150 | guess_the_number_table.put_item(Item=game) 151 | 152 | # START OpenTelemetry Manual Instrumentation 153 | game_counter.add(1) 154 | current_span = trace.get_current_span() 155 | current_span.set_attribute("game.id", game_id) 156 | current_span.set_attribute("game.number", random_number) 157 | # END OpenTelemetry Manual Instrumentation 158 | 159 | return game 160 | 161 | 162 | def get_game(game_id): 163 | # START OpenTelemetry Manual Instrumentation 164 | with tracer.start_as_current_span("get_game") as span: 165 | # END OpenTelemetry Manual Instrumentation 166 | 167 | resp = guess_the_number_table.get_item(Key={'id': game_id}) 168 | 169 | try: 170 | game = resp['Item'] 171 | # START OpenTelemetry Manual Instrumentation 172 | span.set_attribute("game.id", game_id) 173 | span.set_attribute("game.attempts", int(game['attempts'])) 174 | # END OpenTelemetry Manual Instrumentation 175 | except KeyError: 176 | # START OpenTelemetry Manual Instrumentation 177 | game_not_found_counter.add(1) 178 | span.set_attribute("game.notFound", game_id) 179 | # END OpenTelemetry Manual Instrumentation 180 | raise Exception('GameNotFound') 181 | 182 | return game 183 | 184 | 185 | # ANNOTATION OpenTelemetry Manual Instrumentation 186 | @tracer.start_as_current_span("incremet_attempts") 187 | def incremet_attempts(game_id): 188 | 189 | resp=guess_the_number_table.update_item( 190 | Key={ 191 | 'id': game_id 192 | }, 193 | ConditionExpression = Attr('won').eq(False), 194 | UpdateExpression = 'SET attempts = attempts + :val', 195 | ExpressionAttributeValues = { 196 | ':val': 1 197 | }, 198 | ReturnValues = 'UPDATED_NEW' 199 | ) 200 | 201 | # Check that the table update worked 202 | try: 203 | attempts=resp['Attributes']['attempts'] 204 | except KeyError: 205 | # START OpenTelemetry Manual Instrumentation 206 | game_not_found_counter.add(1) 207 | current_span=trace.get_current_span() 208 | current_span.set_attribute("game.notFound", game_id) 209 | # END OpenTelemetry Manual Instrumentation 210 | return 0 211 | 212 | # START OpenTelemetry Manual Instrumentation 213 | attempt_counter.add(1) 214 | current_span=trace.get_current_span() 215 | current_span.set_attribute("game.id", game_id) 216 | current_span.set_attribute("game.attempts", int(attempts)) 217 | # END OpenTelemetry Manual Instrumentation 218 | 219 | return attempts 220 | 221 | 222 | # ANNOTATION OpenTelemetry Manual Instrumentation 223 | @tracer.start_as_current_span("win_game") 224 | def win_game(game_id): 225 | 226 | resp=guess_the_number_table.update_item( 227 | Key = { 228 | 'id': game_id 229 | }, 230 | ConditionExpression = Attr('won').eq(False), 231 | UpdateExpression = 'SET won = :val1, attempts = attempts + :val2', 232 | ExpressionAttributeValues = { 233 | ':val1': True, 234 | ':val2': 1 235 | }, 236 | ReturnValues = 'UPDATED_NEW' 237 | ) 238 | 239 | # Check that the table update worked 240 | try: 241 | attempts=resp['Attributes']['attempts'] 242 | except KeyError: 243 | # START OpenTelemetry Manual Instrumentation 244 | current_span=trace.get_current_span() 245 | current_span.set_attribute("game.id", game_id) 246 | # END OpenTelemetry Manual Instrumentation 247 | return 0 248 | 249 | # Send SQS message to winners queue 250 | resp=guess_the_number_winners_queue.send_message( 251 | MessageBody = 'There is a winner in {} attempts!'.format(attempts) 252 | ) 253 | 254 | # START OpenTelemetry Manual Instrumentation 255 | won_counter.add(1) 256 | current_span=trace.get_current_span() 257 | current_span.set_attribute("game.id", game_id) 258 | current_span.set_attribute("game.attempts", int(attempts)) 259 | # END OpenTelemetry Manual Instrumentation 260 | 261 | return attempts 262 | -------------------------------------------------------------------------------- /GuessTheNumber-SAM/guess_the_number/collector-config.yaml: -------------------------------------------------------------------------------- 1 | extensions: 2 | sigv4auth: 3 | service: "aps" 4 | region: "us-west-2" 5 | 6 | receivers: 7 | otlp: 8 | protocols: 9 | grpc: 10 | http: 11 | 12 | exporters: 13 | logging: 14 | awsxray: 15 | awsemf: 16 | prometheusremotewrite: 17 | endpoint: "https://aps-workspaces.us-west-2.amazonaws.com/workspaces/ws-0bff5472-a617-4585-bd7a-327addb3386e/api/v1/remote_write" 18 | auth: 19 | authenticator: sigv4auth 20 | 21 | service: 22 | pipelines: 23 | traces: 24 | receivers: [otlp] 25 | exporters: [awsxray] 26 | metrics: 27 | receivers: [otlp] 28 | exporters: [awsemf, prometheusremotewrite] 29 | extensions: [sigv4auth] 30 | -------------------------------------------------------------------------------- /GuessTheNumber-SAM/guess_the_number/requirements.txt: -------------------------------------------------------------------------------- 1 | boto3 2 | Flask 3 | apig-wsgi 4 | -------------------------------------------------------------------------------- /GuessTheNumber-SAM/guess_the_number/static/index.js: -------------------------------------------------------------------------------- 1 | const endpoint = document.getElementById('endpoint') 2 | const gameDiv = document.getElementById('game'); 3 | const startButton = document.getElementById('start'); 4 | 5 | let gameApi = location.href.replace(/\/$/, "") + "/game"; 6 | 7 | endpoint.value = gameApi; 8 | 9 | document.getElementById('endpointForm').addEventListener('submit', async function (e) { 10 | e.preventDefault(); // Stop form from submitting 11 | 12 | const response = await fetch(endpoint.value); 13 | 14 | const game = await response.json(); // Extract JSON from the HTTP response 15 | 16 | if (game.won) { 17 | return; 18 | } 19 | 20 | // Create guess form 21 | const form = document.createElement("form"); 22 | const gameMessage = document.createElement("p"); 23 | gameMessage.innerHTML = "Guess the number between " + game.min + " and " + game.max; 24 | form.appendChild(gameMessage); 25 | const attemptMessage = document.createElement("p"); 26 | attemptMessage.innerHTML = "Attempt 1 "; // First attempt 27 | form.appendChild(attemptMessage); 28 | const guessInput = document.createElement("input"); 29 | guessInput.type = "text"; 30 | form.appendChild(guessInput); 31 | form.appendChild(document.createTextNode(" ")); 32 | const guessSubmit = document.createElement("input"); 33 | guessSubmit.type = "submit"; 34 | guessSubmit.value = "Guess"; 35 | form.appendChild(guessSubmit); 36 | const guessMessage = document.createElement("p"); 37 | form.appendChild(guessMessage); 38 | gameDiv.innerHTML = ""; 39 | gameDiv.appendChild(form); 40 | guessInput.focus() 41 | 42 | // Process guess 43 | form.addEventListener('submit', async function (e) { 44 | e.preventDefault(); // Stop form from submitting 45 | 46 | guessNumber = parseInt(guessInput.value); 47 | if (isNaN(guessNumber)) { 48 | guessMessage.innerHTML = "Please enter a number"; 49 | return; 50 | } 51 | const guessEnpoint = endpoint.value + "/" + game.id + "/" + guessNumber; 52 | const response = await fetch(guessEnpoint); 53 | const guessGame = await response.json(); // Extract JSON from the HTTP response 54 | 55 | if (guessGame.won) { 56 | guessInput.disabled = true; 57 | guessSubmit.disabled = true; 58 | guessMessage.innerHTML = guessNumber + " is " + guessGame.message + " 👏"; 59 | gameMessage.innerHTML = "You won"; 60 | startButton.focus(); 61 | } else { 62 | nextAttempt = parseInt(guessGame.attempts) + 1 63 | attemptMessage.innerHTML = "Attempt " + nextAttempt; 64 | guessMessage.innerHTML = guessNumber + " is " + guessGame.message; 65 | } 66 | guessInput.value = ""; 67 | 68 | }); 69 | }); 70 | 71 | startButton.focus(); -------------------------------------------------------------------------------- /GuessTheNumber-SAM/guess_the_number/static/style.css: -------------------------------------------------------------------------------- 1 | body { 2 | background-color: white; 3 | font-family: Arial, Helvetica, sans-serif; 4 | text-align: center; 5 | } 6 | 7 | h1 { 8 | color: blue; 9 | font-size: 48px; 10 | } 11 | 12 | p { 13 | color: navy; 14 | font-size: 24px; 15 | } 16 | 17 | input { 18 | background-color: lightyellow; 19 | font-size: 24px; 20 | } 21 | 22 | input[type=submit] { 23 | background-color: lightblue; 24 | font-size: 24px; 25 | } 26 | -------------------------------------------------------------------------------- /GuessTheNumber-SAM/guess_the_number/templates/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Guess the Number 5 | 6 | 7 | 8 |

Guess the Number

9 |
10 |

API Endpoint

11 | 12 | 13 |
14 |
15 |
16 | 17 | 18 | -------------------------------------------------------------------------------- /GuessTheNumber-SAM/template.yaml: -------------------------------------------------------------------------------- 1 | AWSTemplateFormatVersion: '2010-09-09' 2 | Transform: AWS::Serverless-2016-10-31 3 | Description: > 4 | GuessTheNumber-SAM 5 | 6 | Globals: 7 | Function: 8 | Timeout: 30 9 | Tracing: Active 10 | 11 | Resources: 12 | GuessTheNumberFunction: 13 | Type: AWS::Serverless::Function 14 | Properties: 15 | CodeUri: guess_the_number/ 16 | Handler: app.lambda_handler 17 | Runtime: python3.9 18 | MemorySize: 2048 19 | Role: arn:aws:iam:::role/guess-the-number 20 | Layers: 21 | - !Sub arn:aws:lambda:${AWS::Region}:901920570463:layer:aws-otel-python-arm64-ver-1-14-0:1 22 | Architectures: 23 | - arm64 24 | FunctionUrlConfig: 25 | AuthType: NONE 26 | Environment: 27 | Variables: 28 | AWS_LAMBDA_EXEC_WRAPPER: /opt/otel-instrument 29 | OPENTELEMETRY_COLLECTOR_CONFIG_FILE: /var/task/collector-config.yaml 30 | 31 | Outputs: 32 | GuessTheNumberFunctionUrlEndpoint: 33 | Description: "My Lambda Function URL Endpoint" 34 | Value: 35 | Fn::GetAtt: GuessTheNumberFunctionUrl.FunctionUrl -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # reInvent2022-BOA310 2 | Code used at re:Invent 2022 for session BOA310 "Building observable applications with OpenTelemetry" 3 | 4 | ## Role 5 | 6 | Create a role using: 7 | - Role/trust.json for the trust relationships 8 | - Role/policy.json for permissions 9 | 10 | Add these managed policies the the permissions: 11 | - AWSXRayDaemonWriteAccess 12 | - AmazonPrometheusRemoteWriteAccess 13 | 14 | ## Container images 15 | 16 | The container image for the Lambda function is built for the arm64 architecture. 17 | The other container images are multi-arch and support both amd64 and arm64. 18 | 19 | ## AppRunner 20 | 21 | Create two services, one using the guess-the-number-auto container image, one using the guess-the-number-manual image. For both, enable Observability (Tracing with AWS X-Ray) in the Service settings. 22 | 23 | ## ECS 24 | 25 | Create a service using the guess-the-number-manual image. Add observability using the console as described in this blog post: 26 | https://aws.amazon.com/blogs/opensource/simplifying-amazon-ecs-monitoring-set-up-with-aws-distro-for-opentelemetry/ 27 | 28 | ## Lambda 29 | 30 | Create an arm64 function using the guess-the-number-manual-lambda ontainer image. 31 | Create a function using the AWS SAM CLI and the app in the GuessTheNumber-SAM directory. 32 | -------------------------------------------------------------------------------- /Role/policy.json: -------------------------------------------------------------------------------- 1 | { 2 | "Version": "2012-10-17", 3 | "Statement": [ 4 | { 5 | "Effect": "Allow", 6 | "Action": [ 7 | "dynamodb:DescribeContributorInsights", 8 | "dynamodb:RestoreTableToPointInTime", 9 | "dynamodb:UpdateGlobalTable", 10 | "dynamodb:DeleteTable", 11 | "dynamodb:UpdateTableReplicaAutoScaling", 12 | "dynamodb:DescribeTable", 13 | "dynamodb:PartiQLInsert", 14 | "dynamodb:GetItem", 15 | "dynamodb:DescribeContinuousBackups", 16 | "dynamodb:DescribeExport", 17 | "dynamodb:EnableKinesisStreamingDestination", 18 | "dynamodb:BatchGetItem", 19 | "dynamodb:DisableKinesisStreamingDestination", 20 | "sqs:GetQueueUrl", 21 | "dynamodb:UpdateTimeToLive", 22 | "dynamodb:BatchWriteItem", 23 | "dynamodb:PutItem", 24 | "dynamodb:PartiQLUpdate", 25 | "sqs:SendMessage", 26 | "dynamodb:Scan", 27 | "dynamodb:StartAwsBackupJob", 28 | "dynamodb:UpdateItem", 29 | "logs:CreateLogGroup", 30 | "logs:PutLogEvents", 31 | "logs:PutMetricFilter", 32 | "dynamodb:UpdateGlobalTableSettings", 33 | "dynamodb:CreateTable", 34 | "dynamodb:RestoreTableFromAwsBackup", 35 | "dynamodb:GetShardIterator", 36 | "dynamodb:ExportTableToPointInTime", 37 | "dynamodb:DescribeBackup", 38 | "dynamodb:UpdateTable", 39 | "dynamodb:GetRecords", 40 | "dynamodb:DescribeTableReplicaAutoScaling", 41 | "dynamodb:DescribeImport", 42 | "dynamodb:DeleteItem", 43 | "dynamodb:CreateTableReplica", 44 | "dynamodb:ListTagsOfResource", 45 | "dynamodb:UpdateContributorInsights", 46 | "dynamodb:CreateBackup", 47 | "dynamodb:UpdateContinuousBackups", 48 | "dynamodb:PartiQLSelect", 49 | "dynamodb:CreateGlobalTable", 50 | "dynamodb:DescribeKinesisStreamingDestination", 51 | "dynamodb:ImportTable", 52 | "dynamodb:ConditionCheckItem", 53 | "dynamodb:Query", 54 | "dynamodb:DescribeStream", 55 | "dynamodb:DeleteTableReplica", 56 | "dynamodb:DescribeTimeToLive", 57 | "dynamodb:DescribeGlobalTableSettings", 58 | "dynamodb:DescribeGlobalTable", 59 | "dynamodb:RestoreTableFromBackup", 60 | "dynamodb:DeleteBackup", 61 | "dynamodb:PartiQLDelete" 62 | ], 63 | "Resource": [ 64 | "arn:aws:dynamodb:*:*:table/guess-the-number", 65 | "arn:aws:sqs:*:*:guess-the-number-winners", 66 | "arn:aws:logs:*:*:*" 67 | ] 68 | }, 69 | { 70 | "Sid": "VisualEditor1", 71 | "Effect": "Allow", 72 | "Action": [ 73 | "dynamodb:DescribeReservedCapacityOfferings", 74 | "dynamodb:DescribeReservedCapacity", 75 | "dynamodb:PurchaseReservedCapacityOfferings", 76 | "dynamodb:DescribeLimits", 77 | "dynamodb:ListStreams" 78 | ], 79 | "Resource": "*" 80 | } 81 | ] 82 | } -------------------------------------------------------------------------------- /Role/trust.json: -------------------------------------------------------------------------------- 1 | { 2 | "Version": "2012-10-17", 3 | "Statement": [ 4 | { 5 | "Effect": "Allow", 6 | "Principal": { 7 | "Service": [ 8 | "apigateway.amazonaws.com", 9 | "events.amazonaws.com", 10 | "lambda.amazonaws.com", 11 | "tasks.apprunner.amazonaws.com", 12 | "ecs-tasks.amazonaws.com" 13 | ] 14 | }, 15 | "Action": "sts:AssumeRole" 16 | } 17 | ] 18 | } -------------------------------------------------------------------------------- /build_local.sh: -------------------------------------------------------------------------------- 1 | cd GuessTheNumber-Auto 2 | docker build --tag guess-the-number-auto . 3 | cd .. 4 | 5 | cd GuessTheNumber-Manual 6 | docker build --tag guess-the-number-manual . 7 | cd .. 8 | 9 | cd GuessTheNumber-Manual-Lambda 10 | docker build --tag guess-the-number-manual-lambda . \ 11 | --build-arg AWS_DEFAULT_REGION=eu-west-1 \ 12 | --build-arg AWS_ACCESS_KEY_ID=$(aws configure get aws_access_key_id) \ 13 | --build-arg AWS_SECRET_ACCESS_KEY=$(aws configure get aws_secret_access_key) 14 | cd .. 15 | -------------------------------------------------------------------------------- /build_push.sh: -------------------------------------------------------------------------------- 1 | export REGION=$(aws configure get region) 2 | export ACCOUNT_ID=$(aws sts get-caller-identity --query "Account" --output text) 3 | 4 | aws ecr delete-repository --repository-name guess-the-number-auto --force 5 | aws ecr delete-repository --repository-name guess-the-number-manual --force 6 | aws ecr delete-repository --repository-name guess-the-number-manual-lambda --force 7 | 8 | aws ecr create-repository --repository-name guess-the-number-auto 9 | aws ecr create-repository --repository-name guess-the-number-manual 10 | aws ecr create-repository --repository-name guess-the-number-manual-lambda 11 | 12 | aws ecr get-login-password --region ${REGION} | docker login --username AWS --password-stdin ${ACCOUNT_ID}.dkr.ecr.${REGION}.amazonaws.com 13 | 14 | docker buildx create --use 15 | 16 | cd GuessTheNumber-Auto 17 | docker buildx build --platform linux/amd64,linux/arm64 --push -t ${ACCOUNT_ID}.dkr.ecr.${REGION}.amazonaws.com/guess-the-number-auto . 18 | cd .. 19 | 20 | cd GuessTheNumber-Manual 21 | docker buildx build --platform linux/amd64,linux/arm64 --push -t ${ACCOUNT_ID}.dkr.ecr.${REGION}.amazonaws.com/guess-the-number-manual . 22 | cd .. 23 | 24 | cd GuessTheNumber-Manual-Lambda 25 | docker buildx build --platform linux/arm64 --push -t ${ACCOUNT_ID}.dkr.ecr.${REGION}.amazonaws.com/guess-the-number-manual-lambda . \ 26 | --build-arg AWS_DEFAULT_REGION=${REGION} \ 27 | --build-arg AWS_ACCESS_KEY_ID=$(aws configure get aws_access_key_id) \ 28 | --build-arg AWS_SECRET_ACCESS_KEY=$(aws configure get aws_secret_access_key) 29 | cd .. 30 | --------------------------------------------------------------------------------