How to run a Kotlin server generated by Swagger Codegen? - kotlin

I am unable to run the kotlin-server generated by Swagger Codegen v. 3.
The .yaml file is:
openapi: 3.0.0
info:
title: Experiement with Swagger
description: Test
version: 1.0.0
servers:
- url: 'http://localhost:8080'
description: production server's url
tags:
- name: Test
description: Test
externalDocs:
description: Find out more
url: 'http://localhost:8080'
paths:
/testURI:
post:
tags:
- Test
summary: Test
description: Test
requestBody:
required: true
content:
application/json:
schema:
$ref: '#/components/schemas/Test'
responses:
'200':
description: Test success
content:
application/json:
schema:
$ref: '#/components/schemas/TestSuccessResponse'
'404':
description: >-
Only a signed in user can add a question. This response means that
the user isn't signed in.
content:
application/json:
schema:
$ref: '#/components/schemas/UnauthorisedErrorResponse'
'500':
description: >-
means some internal error occur on the server while doing the
operation. The state of the operation if un-determined and the
operation could be succesful, failed or partially successful
(because some database operations are not rolled back if error
occurs!
content:
application/json:
schema:
$ref: '#/components/schemas/InternalServerErrorResponse'
components:
schemas:
Test:
type: object
properties:
some-input:
type: string
TestSuccessResponse:
type: object
properties:
result:
type: string
enum:
- success
additional-info:
type: string
enum:
- Test successful
required:
- result
- additional-info
UnauthorisedErrorResponse:
type: object
properties:
result:
type: string
enum:
- error
additional-info:
type: string
enum:
- Not authorised
required:
- result
- additional-info
InternalServerErrorResponse:
type: object
properties:
result:
type: string
enum:
- error
additional-info:
type: string
enum:
- Internal Server Error
required:
- result
- additional-info
I pasted it into Swagger Editor, downloaded the kotlin-server kotlin-server-server-generated.zip, unzipped it at C:\Users\manu\Documents\manu\kotlin-server-server-generated, opened Readme.MD file and followed the instructions in it.
Using Windows cmd, in C:\Users\manu\Documents\manu\kotlin-server-server-generated,
first I ran gradle wrapper.
I got this output:
Starting a Gradle Daemon, 1 incompatible and 2 stopped Daemons could not be reused, use --status for details
Build cache is an incubating feature.
BUILD SUCCESSFUL in 17s
1 actionable task: 1 executed
Then I ran gradlew check assemble:
C:\Users\manu\Documents\manu\kotlin-server-server-generated>gradlew check assemble
Starting a Gradle Daemon, 1 incompatible and 2 stopped Daemons could not be reused, use --status for details
Build cache is an incubating feature.
w: C:\Users\manu\Documents\manu\kotlin-server-server-generated\src\main\kotlin\io\swagger\server\apis\TestApi.kt: (51, 9): Variable 'gson' is never used
w: C:\Users\manu\Documents\manu\kotlin-server-server-generated\src\main\kotlin\io\swagger\server\apis\TestApi.kt: (52, 9): Variable 'empty' is never used
Task :startShadowScripts
Using TaskInputs.file() with something that doesn't resolve to a File object has been deprecated and is scheduled to be removed in Gradle 5.0. Use TaskInputs.files() instead.
BUILD SUCCESSFUL in 36s
10 actionable tasks: 10 executed
Then I ran java -jar ./build/libs/kotlin-server.jar.
But when I pointed the browser to localhost:8080, I see Page Not Found.
What am I doing wrong?

Related

Serverless: TypeError: Cannot read property 'stage' of undefined

frameworkVersion: '2'
plugins:
- serverless-step-functions
- serverless-python-requirements
- serverless-parameters
- serverless-pseudo-parameters
provider:
name: aws
region: us-east-2
stage: ${opt:stage, 'dev'}
runtime: python3.7
versionFunctions: false
iam:
role: arn:aws:iam::#{AWS::AccountId}:role/AWSLambdaVPCAccessExecutionRole
apiGateway:
shouldStartNameWithService: true
lambdaHashingVersion: 20201221
package:
exclude:
- node_modules/**
- venv/**
# Lambda functions
functions:
generateAlert:
handler: handler.generateAlert
generateData:
handler: handler.generateDataHandler
timeout: 600
approveDenied:
handler: handler.approveDenied
timeout: 600
stepFunctions:
stateMachines:
"claims-etl-and-insight-generation-${self:provider.stage}":
loggingConfig:
level: ALL
includeExecutionData: true
destinations:
- Fn::GetAtt: ["ETLStepFunctionLogGroup", Arn]
name: "claims-etl-and-insight-generation-${self:provider.stage}"
definition:
Comment: "${self:provider.stage} ETL Workflow"
StartAt: RawQualityJob
States:
# Raw Data Quality Check Job Start
RawQualityJob:
Type: Task
Resource: arn:aws:states:::glue:startJobRun.sync
Parameters:
JobName: "data_quality_v2_${self:provider.stage}"
Arguments:
"--workflow-name": "${self:provider.stage}-Workflow"
"--dataset_id.$": "$.datasetId"
"--client_id.$": "$.clientId"
Next: DataQualityChoice
Retry:
- ErrorEquals: [States.ALL]
MaxAttempts: 2
IntervalSeconds: 10
BackoffRate: 5
Catch:
- ErrorEquals: [States.ALL]
Next: GenerateErrorAlertDataQuality
# End Raw Data Quality Check Job
DataQualityChoice:
Type: Task
Resource:
Fn::GetAtt: [approveDenied, Arn]
Next: Is Approved ?
Is Approved ?:
Type: Choice
Choices:
- Variable: "$.quality_status"
StringEquals: "Denied"
Next: FailState
Default: HeaderLineJob
FailState:
Type: Fail
Cause: "Denied status"
# Header Line Job Start
HeaderLineJob:
Type: Parallel
Branches:
- StartAt: HeaderLineIngestion
States:
HeaderLineIngestion:
Type: Task
Resource: arn:aws:states:::glue:startJobRun.sync
Parameters:
JobName: headers_lines_etl_rs_v2
Arguments:
"--workflow-name.$": "$.Arguments.--workflow-name"
"--dataset_id.$": "$.Arguments.--dataset_id"
"--client_id.$": "$.Arguments.--client_id"
End: True
Retry:
- ErrorEquals: [States.ALL]
MaxAttempts: 2
IntervalSeconds: 10
BackoffRate: 5
Catch:
- ErrorEquals: [States.ALL]
Next: GenerateErrorAlertHeaderLine
End: True
# Header Line Job End
GenerateErrorAlertDataQuality:
Type: Task
Resource:
Fn::GetAtt: [generateAlert, Arn]
End: true
resources:
Resources:
# Cloudwatch Log
"ETLStepFunctionLogGroup":
Type: AWS::Logs::LogGroup
Properties:
LogGroupName: "ETLStepFunctionLogGroup_${self:provider.stage}"
This is what my serverless.yml file looks like.
When I run the command:
sls deploy --stage staging
It show
Type Error ----------------------------------------------
TypeError: Cannot read property 'stage' of undefined
at Variables.getValueFromOptions (/snapshot/serverless/lib/classes/Variables.js:648:37)
at Variables.getValueFromSource (/snapshot/serverless/lib/classes/Variables.js:579:17)
at /snapshot/serverless/lib/classes/Variables.js:539:12
Your Environment Information ---------------------------
Operating System: linux
Node Version: 14.4.0
Framework Version: 2.30.3 (standalone)
Plugin Version: 4.5.1
SDK Version: 4.2.0
Components Version: 3.7.4
How I can fix this? I tried with different version of serverless.
There is error in yamlParser file, which is provided by serverless-step-functions.
Above is my serverless config file.
It looks like a $ sign is missing from your provider -> stage?
provider:
name: aws
region: us-east-2
stage: ${opt:stage, 'dev'} # $ sign is missing?
runtime: python3.7
versionFunctions: false
iam:
role: arn:aws:iam::#{AWS::AccountId}:role/AWSLambdaVPCAccessExecutionRole
apiGateway:
shouldStartNameWithService: true
lambdaHashingVersion: 20201221

How to eliminate serverless framework error Template format error

Testing, learning serverless framework. I'm trying to deploy simple/basic state machine with two simple lambda functions.
Serverless definition as follows:
frameworkVersion: '2'
app: state-machine
org: macdrorepo
service: state-machine
plugins:
- serverless-python-requirements
- serverless-iam-roles-per-function
- serverless-step-functions
- serverless-pseudo-parameters
custom:
pythonRequirements:
dockerizePip: non-linux
slim: true
zip: true
provider:
name: aws
runtime: python3.8
region: eu-central-1
stage: ${opt:stage, 'testing'}
timeout: 30
package:
individually: true
exclude:
- node_modules/**
- .git/**
- .venv/**
functions:
processpurchase:
module: state-machine
memorySize: 128
stages:
- testing
- dev
handler: ProcessPurchase.process_purchase
processrefund:
module: state-machine
memorySize: 128
stages:
- testing
- dev
handler: ProcessRefund.process_refund
stepFunctions:
validate: true
stateMachines:
TransactionChoiceMachine:
name: ChoiceMachineTest-${self:provider.stage}
dependsOn: CustomIamRole
definition:
Comment: "Purchase refund choice"
StartAt: ProcessTransaction
States:
ProcessTransaction:
Type: Choice
Choices:
- Variable: "$.TransactionType"
StringEquals: PURCHASE
Next: PurchaseState
- Variable: "$.TransactionType"
StringEquals: REFUND
Next: RefundState
PurchaseState:
Type: Task
Resource:
Fn::GetAtt: [processpurchase, Arn]
End: true
RefundState:
Type: Task
Resource:
Fn::GetAtt: [processrefund, Arn]
End: true
During deploy, sls is saying my state machine definition is ok: State machine "TransactionChoiceMachine" definition is valid
My environment information:
Your Environment Information ---------------------------
Operating System: linux
Node Version: 12.20.0
Framework Version: 2.14.0
Plugin Version: 4.1.2
SDK Version: 2.3.2
Components Version: 3.4.3
Setup SLS_DEBUG=* is not helping me much as I do not know js unfortunately.
After serverless deploy command, I'm getting error:
Error: The CloudFormation template is invalid: Template format error: Unresolved resource dependencies [CustomIamRole] in the Resources block of the template
Looks like you are referencing something called CustomIamRole in your state machine creation but I cannot see it being created anywhere in the yaml file. Either create the role and use it in creation or remove the depends on part.

Cloudwatch Event Rule doesn't invoke when source state machine fails

I have a step function that runs 2 separate lambdas. If the step function fails or times out, I want to get an email via SNS telling me the step function failed. I created the event rule using cloudformation and specified the statemachine ARN in the event pattern. When the step function fails, no email is sent out. If I remove the stateMachineArn parameter and run my step function, I get the failure email. I've double checked numerous times that I'm entering the correct ARN for the state machine. CF for the Event Rule is below (in YAML format). Thanks.
FailureEvent:
Type: AWS::Events::Rule
DependsOn:
- StateMachine
Properties:
Name: !Ref FailureRuleName
Description: "EventRule"
EventPattern:
detail-type:
- "Step Functions Execution Status Change"
detail:
status:
- "FAILED"
- "TIMED_OUT"
stateMachineArn: ["arn:aws:states:region:account#:stateMachine:statemachine"]
Targets:
-
Arn:
Ref: SNSARN
Id: !Ref SNSTopic
I did get this fixed and expanded on it to invoke a lambda that publishes a custom SNS email using a lambda. My alignment was off in my EventPattern section. See below. Thanks to #Marcin.
FailureEvent:
Type: AWS::Events::Rule
DependsOn:
- FMIStateMachine
Properties:
Description: !Ref FailureRuleDescription
Name: !Ref FailureRuleName
State: "ENABLED"
RoleArn:
'Fn::Join': ["", ['arn:aws:iam::', !Ref 'AWS::AccountId', ':role/', !Ref LambdaExecutionRole]]
EventPattern:
detail-type:
- "Step Functions Execution Status Change"
detail:
status:
- "FAILED"
- "TIMED_OUT"
stateMachineArn: [!Ref StateMachine]
Targets:
- Arn:
'Fn::Join': ["", ['arn:aws:lambda:', !Ref 'AWS::Region', ':', !Ref 'AWS::AccountId', ':function:', !Ref FailureLambda]]
Id: !Ref FailureLambda
Input: !Sub '{"failed_service": "${StateMachineName}","sns_arn": "arn:aws:sns:${AWS::Region}:${AWS::AccountId}:${SNSTopic}"}'

Serverless Enterprise deployment

I recently updated to v1.44.0 and used the #serverless/enterprise-plugin and am now unable to deploy. I’m simply trying to create a User Pool, but keep getting an error.
An error occurred: EnterpriseLogAccessIamRole - Policy statement must contain resources. (Service: AmazonIdentityManagement; Status Code: 400; Error Code: MalformedPolicyDocument; Request ID: dc158686-378c-4d01-97fb-1414d55a735d)
serverless.yml
tenant: [omitted]
app: [omitted]
service: auth
frameworkVersion: ">=1.44.0"
plugins:
- '#serverless/enterprise-plugin'
provider:
name: aws
runtime: nodejs8.10
region: us-east-1
custom:
stage: ${opt:stage, self:provider.stage}
cognito:
app:
userPool: ${self:service}-app-user-pool-${self:custom.stage}
identityPool: AppIdentityPoolDev
resources:
Resources:
AppUserPool:
Type: AWS::Cognito::UserPool
Properties:
UserPoolName: ${self:custom.cognito.app.userPool}
UsernameAttributes:
- email
AutoVerifiedAttributes:
- email
MobileAppClient:
Type: AWS::Cognito::UserPoolClient
Properties:
ClientName: ${self:service}-mobile-app-client-${self:custom.stage}
UserPoolId:
Ref: AppUserPool
GenerateSecret: true
Outputs:
AppUserPool:
Value:
Ref: AppUserPool
MobileAppClient:
Value:
Ref: MobileAppClient

unable to add notificationconfiguration to s3 bucket

Created cloud formation template to create bucket with notification.
Following is code:
AWSTemplateFormatVersion: '2010-09-09'
Parameters:
CBRS3ToS3IADelay:
Description: Number of days before an S3 object is transitioned from S3 to S3-IA
Type: Number
Default: 365
CBRS3ToGlacierDelay:
Description: Number of days before an S3-IA object is transitioned from S3-IA to Glacier.
Type: Number
Default: 1460
CBRBucketName:
Description: S3 bucket name
Type: String
Default: "my-bucket-test0011"
Resources:
CBRS3Bucket:
Type: AWS::S3::Bucket
Properties:
BucketName:
Ref: CBRBucketName
AccessControl: Private
LifecycleConfiguration:
Rules:
- Id: CbrCertReportGlacierArchiveRule
Status: Enabled
Transitions:
- StorageClass: STANDARD_IA
TransitionInDays: !Ref CBRS3ToS3IADelay
- StorageClass: GLACIER
TransitionInDays: !Ref CBRS3ToGlacierDelay
NotificationConfiguration:
LambdaConfigurations:
-
Function: "arn:aws:lambda:xxxx:xxxx:function:xxxx"
Event: "s3:ObjectCreated:Put"
Filter:
S3Key:
Rules:
-
Name: suffix
Value: ".gz"
Tags:
- Key: PRODUCT
Value: CRAWS
VersioningConfiguration:
Status: Enabled
Code working with notification block.
But above template is not working with notification.
Getting following error:
Unable to validate the following destination configurations (Service: Amazon S3; Status Code: 400; Error Code: InvalidArgument
I able to do from console.
Anyone help me to fix this issue?
this is late, so more of answering myself for this question (just managed to fix the same problem): it fails due to a preliminary check on s3 to invoke that lambda function, we will need this:
CBRS3BucketCanInvokeFunctionX:
Type: 'AWS::Lambda::Permission'
Properties:
FunctionName: ARN_OF_FUNCTION_X
Action: 'lambda:InvokeFunction'
Principal: s3.amazonaws.com
SourceAccount: !Ref 'AWS::AccountId'
SourceArn: !Sub 'arn:aws:s3:::${CBRBucketName}'
your CBRS3Bucket will also need to let above resource run first:
CBRS3Bucket:
Type: AWS::S3::Bucket
DependsOn: CBRS3BucketCanInvokeFunctionX
Try taking the .gz and put in just gz.