-
Notifications
You must be signed in to change notification settings - Fork 1
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat(memfault): fetch reboots and publish
- Loading branch information
1 parent
46615f0
commit 3e5f3fd
Showing
9 changed files
with
1,354 additions
and
1,127 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,102 @@ | ||
import { | ||
Duration, | ||
aws_events as Events, | ||
aws_events_targets as EventsTargets, | ||
aws_s3 as S3, | ||
aws_iam as IAM, | ||
aws_lambda as Lambda, | ||
Stack, | ||
RemovalPolicy, | ||
} from 'aws-cdk-lib' | ||
import type { IPrincipal } from 'aws-cdk-lib/aws-iam/index.js' | ||
import { Construct } from 'constructs' | ||
import type { PackedLambda } from '../backend.js' | ||
import { LambdaLogGroup } from './LambdaLogGroup.js' | ||
|
||
/** | ||
* Pull Memfault data for devices | ||
*/ | ||
export class Memfault extends Construct { | ||
public readonly bucket: S3.Bucket | ||
public constructor( | ||
parent: Construct, | ||
{ | ||
lambdaSources, | ||
baseLayer, | ||
assetTrackerStackName, | ||
}: { | ||
lambdaSources: { | ||
memfault: PackedLambda | ||
} | ||
baseLayer: Lambda.ILayerVersion | ||
assetTrackerStackName: string | ||
}, | ||
) { | ||
super(parent, 'Memfault') | ||
|
||
this.bucket = new S3.Bucket(this, 'bucket', { | ||
autoDeleteObjects: true, | ||
removalPolicy: RemovalPolicy.DESTROY, | ||
publicReadAccess: true, | ||
websiteIndexDocument: 'index.html', | ||
blockPublicAccess: { | ||
blockPublicAcls: false, | ||
ignorePublicAcls: false, | ||
restrictPublicBuckets: false, | ||
blockPublicPolicy: false, | ||
}, | ||
objectOwnership: S3.ObjectOwnership.OBJECT_WRITER, | ||
cors: [ | ||
{ | ||
allowedOrigins: ['https://world.thingy.rocks', 'http://localhost:*'], | ||
allowedMethods: [S3.HttpMethods.GET], | ||
}, | ||
], | ||
}) | ||
|
||
const fn = new Lambda.Function(this, 'fn', { | ||
handler: lambdaSources.memfault.handler, | ||
architecture: Lambda.Architecture.ARM_64, | ||
runtime: Lambda.Runtime.NODEJS_20_X, | ||
timeout: Duration.seconds(60), | ||
memorySize: 1792, | ||
code: Lambda.Code.fromAsset(lambdaSources.memfault.lambdaZipFile), | ||
description: 'Pull Memfault data for devices and put them in the shadow', | ||
layers: [baseLayer], | ||
environment: { | ||
VERSION: this.node.tryGetContext('version'), | ||
STACK_NAME: Stack.of(this).stackName, | ||
ASSET_TRACKER_STACK_NAME: assetTrackerStackName, | ||
NODE_NO_WARNINGS: '1', | ||
BUCKET: this.bucket.bucketName, | ||
}, | ||
initialPolicy: [ | ||
new IAM.PolicyStatement({ | ||
actions: ['ssm:GetParametersByPath'], | ||
resources: [ | ||
`arn:aws:ssm:${Stack.of(this).region}:${Stack.of(this).account}:parameter/${Stack.of(this).stackName}/memfault/*`, | ||
], | ||
}), | ||
new IAM.PolicyStatement({ | ||
actions: ['iot:ListThingsInThingGroup'], | ||
resources: ['*'], | ||
}), | ||
], | ||
...new LambdaLogGroup(this, 'fnLogs'), | ||
}) | ||
|
||
this.bucket.grantWrite(fn) | ||
|
||
const rule = new Events.Rule(this, 'Rule', { | ||
schedule: Events.Schedule.expression('rate(5 minutes)'), | ||
description: `Invoke the Memfault lambda`, | ||
enabled: true, | ||
targets: [new EventsTargets.LambdaFunction(fn)], | ||
}) | ||
|
||
fn.addPermission('InvokeByEvents', { | ||
principal: new IAM.ServicePrincipal('events.amazonaws.com') as IPrincipal, | ||
sourceArn: rule.ruleArn, | ||
}) | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,112 @@ | ||
import { IoTClient, ListThingsInThingGroupCommand } from '@aws-sdk/client-iot' | ||
import { GetParametersByPathCommand, SSMClient } from '@aws-sdk/client-ssm' | ||
import { fromEnv } from '@nordicsemiconductor/from-env' | ||
import { S3Client, PutObjectCommand } from '@aws-sdk/client-s3' | ||
|
||
const ssm = new SSMClient({}) | ||
const iot = new IoTClient({}) | ||
const s3 = new S3Client({}) | ||
|
||
const { stackName, nrfAssetTrackerStackName, bucket } = fromEnv({ | ||
stackName: 'STACK_NAME', | ||
nrfAssetTrackerStackName: 'ASSET_TRACKER_STACK_NAME', | ||
bucket: 'BUCKET', | ||
})(process.env) | ||
|
||
const Prefix = `/${stackName}/memfault/` | ||
const { organizationAuthToken, organizationId, projectId } = ( | ||
( | ||
await ssm.send( | ||
new GetParametersByPathCommand({ | ||
Path: Prefix, | ||
}), | ||
) | ||
)?.Parameters ?? [] | ||
).reduce( | ||
(params, p) => ({ | ||
...params, | ||
[(p.Name ?? '').replace(Prefix, '')]: p.Value ?? '', | ||
}), | ||
{} as Record<string, string>, | ||
) | ||
|
||
if ( | ||
organizationAuthToken === undefined || | ||
organizationId === undefined || | ||
projectId === undefined | ||
) | ||
throw new Error(`Memfault settings not configured!`) | ||
|
||
type Reboot = { | ||
type: 'memfault' | ||
mcu_reason_register: null | ||
time: string // e.g. '2024-03-14T07:26:37.270000+00:00' | ||
reason: number // e.g. 7 | ||
software_version: { | ||
version: string // e.g. '1.11.1+thingy91.low-power.memfault' | ||
id: number // e.g.504765 | ||
software_type: { | ||
id: number //e.g. 32069; | ||
name: string // e.g. 'thingy_world' | ||
} | ||
archived: boolean | ||
} | ||
} | ||
|
||
const api = { | ||
getLastReboots: async (deviceId: string): Promise<null | Array<Reboot>> => { | ||
const res = await fetch( | ||
`https://api.memfault.com/api/v0/organizations/${organizationId}/projects/${projectId}/devices/${deviceId}/reboots?${new URLSearchParams( | ||
{ | ||
since: new Date(Date.now() - 24 * 60 * 60 * 1000).toISOString(), | ||
}, | ||
).toString()}`, | ||
{ | ||
headers: new Headers({ | ||
Authorization: `Basic ${Buffer.from(`:${organizationAuthToken}`).toString('base64')}`, | ||
}), | ||
}, | ||
) | ||
if (!res.ok) return null | ||
return (await res.json()).data | ||
}, | ||
} | ||
|
||
/** | ||
* Pull data from Memfault about all devices | ||
*/ | ||
export const handler = async (): Promise<void> => { | ||
const { things } = await iot.send( | ||
new ListThingsInThingGroupCommand({ | ||
thingGroupName: nrfAssetTrackerStackName, | ||
}), | ||
) | ||
const deviceReboots: Record<string, Array<Reboot>> = {} | ||
for (const thing of things ?? []) { | ||
const reboots = await api.getLastReboots(thing) | ||
if (reboots === null) { | ||
console.debug(thing, `No data found.`) | ||
continue | ||
} | ||
if (reboots.length === 0) { | ||
console.debug(thing, `No reboots in the last 24 hours.`) | ||
continue | ||
} | ||
deviceReboots[thing] = reboots | ||
console.debug(thing, `Updated`) | ||
} | ||
|
||
await s3.send( | ||
new PutObjectCommand({ | ||
Bucket: bucket, | ||
Key: 'device-reboots.json', | ||
ContentType: 'application/json', | ||
CacheControl: 'public, max-age=300', | ||
Body: JSON.stringify({ | ||
'@context': | ||
'https://github.com/NordicPlayground/thingy-rocks-cloud-aws-js/Memfault/reboots', | ||
reboots: deviceReboots, | ||
}), | ||
}), | ||
) | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.