Ejemplo n.º 1
0
        protected override async Task InitializeAsync(ILambdaConfigSource envSource, ILambdaContext context)
        {
            await base.InitializeAsync(envSource, context);

            // retrieve the optional parameter name for the slack token
            _slackVerificationTokenName = envSource.Read("SLACKTOKENNAME");
        }
Ejemplo n.º 2
0
        protected virtual async Task InitializeAsync(ILambdaConfigSource envSource, ILambdaContext context)
        {
            // read configuration from environment variables
            DeploymentTier      = envSource.Read("TIER");
            ModuleName          = envSource.Read("MODULE");
            _deadLetterQueueUrl = envSource.Read("DEADLETTERQUEUE");
            _loggingTopicArn    = envSource.Read("LOGGINGTOPIC");
            var framework = envSource.Read("LAMBDARUNTIME");

            LogInfo($"TIER = {DeploymentTier}");
            LogInfo($"MODULE = {ModuleName}");
            LogInfo($"DEADLETTERQUEUE = {_deadLetterQueueUrl ?? "NONE"}");
            LogInfo($"LOGGINGTOPIC = {_loggingTopicArn ?? "NONE"}");

            // read optional git-sha file
            var gitsha = File.Exists("gitsha.txt") ? File.ReadAllText("gitsha.txt") : null;

            LogInfo($"GITSHA = {gitsha ?? "NONE"}");

            // convert environment variables to lambda parameters
            _appConfig = new LambdaConfig(new LambdaDictionarySource(await ReadParametersFromEnvironmentVariables()));

            // initialize rollbar
            var          rollbarAccessToken = _appConfig.ReadText("RollbarToken", defaultValue: null);
            const string proxy    = "";
            const string platform = "lambda";

            _rollbarClient = RollbarClient.Create(new RollbarConfiguration(

                                                      // NOTE (2018-08-06, bjorg): the rollbar access token determines the rollbar project
                                                      //  the error report is associated with; when rollbar intergration is disabled,
                                                      //  use the module name instead so the logging recipient can determine the module
                                                      //  the log entry belongs to.
                                                      rollbarAccessToken ?? ModuleName,
                                                      proxy,
                                                      DeploymentTier,
                                                      platform,
                                                      framework,
                                                      gitsha
                                                      ));
            _rollbarEnabled = (rollbarAccessToken != null);
            LogInfo($"ROLLBAR = {(_rollbarEnabled ? "ENABLED" : "DISABLED")}");
        }
Ejemplo n.º 3
0
        //--- Methods ---
        public T Read <T>(string key, Func <string, T> fallback, Func <string, T> convert, Action <T> validate)
        {
            // attempt to read the requested key
            string textValue;

            try {
                textValue = _source.Read(key);
            } catch (Exception e) when(!(e is ALambdaConfigException))
            {
                throw new LambdaConfigUnexpectedException(CombinePathWithKey(Path, key), "reading config key", e);
            }

            // check if we were unable to find a value
            T value;

            if (textValue == null)
            {
                // check if we have a fallback option for getting the value
                if (fallback == null)
                {
                    throw new LambdaConfigMissingKeyException(CombinePathWithKey(Path, key));
                }

                // attempt to get the key value using the fallback callback
                try {
                    value = fallback(key);
                } catch (Exception e) when(!(e is ALambdaConfigException))
                {
                    throw new LambdaConfigUnexpectedException(CombinePathWithKey(Path, key), "invoking fallback", e);
                }
            }
            else
            {
                // attempt to convert value to desired type
                try {
                    if (convert == null)
                    {
                        value = (T)Convert.ChangeType(textValue, typeof(T));
                    }
                    else
                    {
                        value = convert(textValue);
                    }
                } catch (Exception e) when(!(e is ALambdaConfigException))
                {
                    throw new LambdaConfigUnexpectedException(CombinePathWithKey(Path, key), "validating value", e);
                }
            }

            // optionally validate converted value
            if (validate == null)
            {
                return(value);
            }
            try {
                validate(value);
            } catch (Exception e) when(!(e is ALambdaConfigException))
            {
                throw new LambdaConfigBadValueException(CombinePathWithKey(Path, key), e);
            }
            return(value);
        }
        //--- Methods ---

        /// <summary>
        /// The <see cref="InitializePrologueAsync(ILambdaConfigSource)"/> method is invoked to prepare the Lambda function
        /// for initialization. This is the first of three methods that are invoked to initialize the Lambda function.
        /// </summary>
        /// <param name="envSource">The <see cref="ILambdaConfigSource"/> instance from which to read the configuration settings.</param>
        /// <returns>The task object representing the asynchronous operation.</returns>
        protected override async Task InitializePrologueAsync(ILambdaConfigSource envSource)
        {
            await base.InitializePrologueAsync(envSource);

            _corsOrigin = envSource.Read("CORS_ORIGIN");
        }
Ejemplo n.º 5
0
        protected virtual async Task InitializeAsync(ILambdaConfigSource envSource, ILambdaContext context)
        {
            // read configuration from environment variables
            DeploymentTier      = envSource.Read("TIER");
            ModuleName          = envSource.Read("MODULE");
            _deadLetterQueueUrl = envSource.Read("DEADLETTERQUEUE");
            _loggingTopicArn    = envSource.Read("LOGGINGTOPIC");
            var framework = envSource.Read("LAMBDARUNTIME");

            LogInfo($"TIER = {DeploymentTier}");
            LogInfo($"MODULE = {ModuleName}");
            LogInfo($"DEADLETTERQUEUE = {_deadLetterQueueUrl ?? "NONE"}");
            LogInfo($"LOGGINGTOPIC = {_loggingTopicArn ?? "NONE"}");

            // read optional git-sha file
            var gitsha = File.Exists("gitsha.txt") ? File.ReadAllText("gitsha.txt") : null;

            LogInfo($"GITSHA = {gitsha ?? "NONE"}");

            // read module parameter values from parameters file
            var parameters = await ParseParameters("/", File.ReadAllText("parameters.json"));

            // create config where environment variables take precedence over those found in the parameter file
            _appConfig = new LambdaConfig(new LambdaMultiSource(new[] {
                envSource,
                new LambdaDictionarySource("", parameters)
            }));

            // initialize rollbar
            var          rollbarAccessToken = _appConfig.ReadText("RollbarToken", defaultValue: null);
            const string proxy    = "";
            const string platform = "lambda";

            _rollbarClient = RollbarClient.Create(new RollbarConfiguration(

                                                      // NOTE (2018-08-06, bjorg): the rollbar access token determines the rollbar project
                                                      //  the error report is associated with; when rollbar intergration is disabled,
                                                      //  use the module name instead so the logging recipient can determine the module
                                                      //  the log entry belongs to.
                                                      rollbarAccessToken ?? ModuleName,
                                                      proxy,
                                                      DeploymentTier,
                                                      platform,
                                                      framework,
                                                      gitsha
                                                      ));
            _rollbarEnabled = (rollbarAccessToken != null);
            LogInfo($"ROLLBAR = {(_rollbarEnabled ? "ENABLED" : "DISABLED")}");

            // local functions
            async Task <Dictionary <string, string> > ParseParameters(string parameterPrefix, string json)
            {
                var functionParameters = JsonConvert.DeserializeObject <Dictionary <string, LambdaFunctionParameter> >(json);
                var flatten            = new Dictionary <string, string>();

                await Flatten(functionParameters, parameterPrefix, "STACK_", flatten);

                return(flatten);

                // local functions
                async Task Flatten(Dictionary <string, LambdaFunctionParameter> source, string prefix, string envPrefix, Dictionary <string, string> target)
                {
                    foreach (var kv in source)
                    {
                        var value = kv.Value.Value;
                        switch (kv.Value.Type)
                        {
                        case LambdaFunctionParameterType.Collection:
                            await Flatten((Dictionary <string, LambdaFunctionParameter>) value, prefix + kv.Key + "/", envPrefix + kv.Key.ToUpperInvariant() + "_", target);

                            break;

                        case LambdaFunctionParameterType.Secret: {
                            var secret          = (string)value;
                            var plaintextStream = (await _kmsClient.DecryptAsync(new DecryptRequest {
                                    CiphertextBlob = new MemoryStream(Convert.FromBase64String(secret)),
                                    EncryptionContext = kv.Value.EncryptionContext
                                })).Plaintext;
                            target.Add(prefix + kv.Key, Encoding.UTF8.GetString(plaintextStream.ToArray()));
                            break;
                        }

                        case LambdaFunctionParameterType.Stack:
                            target.Add(prefix + kv.Key, envSource.Read(envPrefix + kv.Key.ToUpperInvariant()));
                            break;

                        case LambdaFunctionParameterType.Text:
                            target.Add(prefix + kv.Key, (string)value);
                            break;

                        default:
                            throw new NotSupportedException($"unsupported parameter type: '{kv.Value.Type.ToString()}'");
                        }
                    }
                }
            }
        }