Terraform : Beanstalk connection with RDS instance - amazon-web-services

I have an error when I build my Beanstalk environment thanks to Terraform. I use Beanstalk with Docker. The error come from the build of Docker Image like we could see thanks to terraform apply error :
Error: creating Elastic Beanstalk Environment (app-dev): waiting for completion: 3 errors occurred:
│ * 2023-02-19 18:36:21.159 +0000 UTC (e-jnwgwcdy7q) : Instance deployment failed. For details, see 'eb-engine.log'.
│ * 2023-02-19 18:36:21.159 +0000 UTC (e-jnwgwcdy7q) : Instance deployment failed to build the Docker image. The deployment failed.
│ * 2023-02-19 18:36:24.538 +0000 UTC (e-jnwgwcdy7q) : [Instance: i-0feeb08c4da8ff1b5] Command failed on instance. Return code: 1 Output: Engine execution has encountered an error..
The custom Docker image contains a Django Rest API where I install my requirements and where I also made migrations inside my RDS instance. The DRF API gets the connection endpoints thanks to environment variables.
Inside it, I provide this Beanstalk stack with application, environment, and application version :
resource "aws_elastic_beanstalk_application" "beanstalk_app" {
  name        = var.project_ref
  description = "Beanstalk application for Django App"
}
resource "aws_elastic_beanstalk_environment" "beanstalk_env" {
  name                = var.project_ref
  application         = aws_elastic_beanstalk_application.beanstalk_app.name
  solution_stack_name = "64bit Amazon Linux 2 v3.5.4 running Docker"
  tier                = "WebServer"
  version_label       = aws_elastic_beanstalk_application_version.beanstalk_app_version.id
  setting {
    namespace = "aws:autoscaling:launchconfiguration"
    name = "IamInstanceProfile"
    value = aws_iam_instance_profile.ec2_eb_profile.name
  }
  # Env vars
  setting {
    namespace = "aws:elasticbeanstalk:application:environment"
    name      = "DB_PORT"
    value     = var.project_port
  }
  setting {
    namespace = "aws:elasticbeanstalk:application:environment"
    name      = "DB_NAME"
    value     = var.project_name
  }
  setting {
    namespace = "aws:elasticbeanstalk:application:environment"
    name      = "DB_USER"
    value     = var.project_db_user
  }
  setting {
    namespace = "aws:elasticbeanstalk:application:environment"
    name      = "DB_PASSWORD"
    value     = var.project_db_pwd
  }
  setting {
    namespace = "aws:elasticbeanstalk:application:environment"
    name      = "DJANDO_ADMIN_PWD"
    value     = var.project_admin_pwd
  }
  # Logs
  setting {
    namespace = "aws:elasticbeanstalk:cloudwatch:logs"
    name      = "StreamLogs"
    value     = "true"
  }
  setting {
    namespace = "aws:elasticbeanstalk:cloudwatch:logs"
    name      = "RetentionInDays"
    value     = "1"
  }
  setting {
    namespace = "aws:elasticbeanstalk:cloudwatch:logs"
    name      = "DeleteOnTerminate"
    value     = "false"
  }
  # Logs health
  setting {
    namespace = "aws:elasticbeanstalk:cloudwatch:logs:health"
    name      = "HealthStreamingEnabled"
    value     = "true"
  }
  setting {
    namespace = "aws:elasticbeanstalk:cloudwatch:logs:health"
    name      = "DeleteOnTerminate"
    value     = "true"
  }
  setting {
    namespace = "aws:elasticbeanstalk:cloudwatch:logs:health"
    name      = "RetentionInDays"
    value     = "1"
  }
  # Tags
  tags = {
    Name = var.project_ref
    Environment = var.project_env
  }
}
resource "aws_elastic_beanstalk_application_version" "beanstalk_app_version" {
  name        = var.project_ref
  description = "application version created by terraform"
  application = aws_elastic_beanstalk_application.beanstalk_app.id
  bucket      = aws_s3_bucket.s3_bucket_back.id
  key         = aws_s3_object.s3_bucket_back_zip.id
}
resource "aws_iam_instance_profile" "ec2_eb_profile" {
  name = "beanstalk-service-user"
  role = "${aws_iam_role.ec2_eb_role.name}"
  tags = {
    Name = var.project_ref
    Environment = var.project_env
  }
}
resource "aws_iam_role" "ec2_eb_role" {
  name = "beanstalk-service-role"
  assume_role_policy = data.aws_iam_policy_document.instance_assume_role_policy.json
}
I also provide a RDS instance like :
resource "aws_db_instance" "db_instance_project" {
  allocated_storage      = 10
  db_name                = var.project_name
  engine                 = "postgres"
  engine_version         = "13.7"
  instance_class         = "db.t3.micro"
  username               = var.project_db_user
  password               = var.project_db_pwd
  skip_final_snapshot    = true
  vpc_security_group_ids = [aws_default_security_group.security_group.id]
  publicly_accessible    = true
}
The security group called in db_instance was correctly opened on the corresponding port.
The application version called S3 Bucket to fetch a docker-compose.yaml stack inside a zip archive with the code to launch.
To conclude, I wonder if there is a way ton debug the Docker Image build or the Terraform launch build ? My eb-engine.log is empty, and all CloudWatch logs are empty also. Is there another way to read logs ?
Do you think this is an error to contact RDS instance ? I purposely opened the RDS public for testing, but there was no change after.
Thanks for your answer and ideas.
EDIT 20/02/2023 : I also tried to insert database config inside my Beanstalk environment like :
setting {
namespace = "aws:rds:dbinstance"
name = "HasCoupleDatabase"
value = false
}
setting {
namespace = "aws:rds:dbinstance"
name = "DBEngine"
value = "postgres"
}
setting {
namespace = "aws:rds:dbinstance"
name = "DBEngineVersion"
value = "13.7"
}
setting {
namespace = "aws:rds:dbinstance"
name = "DBInstanceClass"
value = "db.t3.micro"
}
setting {
namespace = "aws:rds:dbinstance"
name = "DBUser"
value = var.project_db_user
}
setting {
namespace = "aws:rds:dbinstance"
name = "DBPassword"
value = var.project_db_pwd
}
However, we couldn't defined a DB_NAME with this method. So I tried to created an RDS Instance resource to create my DB. Then, I couldn't insert an RDS_DB_HOST to my Beanstalk settings so I don't understand how I can proceed to connect them together.

Related

splitting text file into array correctly with -split operator

I have a text file that looks like this:
      ;MPV_F4(isHold, taps, state)
      MPV_F5(isHold, taps, state)
         {
            if (taps == 1)
            {
                  if (isHold == 0)
                  {
                   ;[HV] T1 | cycle  mute | This is long LONG
                     Sendinput, {U+0398}  ;Θ ;   ;[rr] [cycle mute         ]
                  }
                  else
                  {
                    if (state)
                                          {
                                             while GetKeyState("f5", "p"){
                                                   Sendinput, {U+0399}  ;Ι ;   ;[rr] [add volume 10    ]  
                                                     sleep, 55
                                                 }  
                                          }
                          ; else
                          ;           {
                          ;           }
                  }
            }
         }      
      MPV_F6(isHold, taps, state)
      ;MPV_F7(isHold, taps, state)
      ;MPV_F8(isHold, taps, state)
      ;MPV_F9(isHold, taps, state)
      ;MPV_F11(isHold, taps, state)
      MPV_N2(isHold, taps, state)
         {
            if (taps == 1)
            {
                  if (isHold == 0)
                  {
                   ;[HV] T1 | cycle  mute | This is long LONG
                     Sendinput, {U+0398}  ;Θ ;   ;[rr] [cycle mute         ]
                  }
                  else
                  {
                    if (state)
                                          {
                                             while GetKeyState("f5", "p"){
                                                   Sendinput, {U+0399}  ;Ι ;   ;[rr] [add volume 10    ]  
                                                     sleep, 55
                                                 }  
                                          }
                          ; else
                          ;           {
                          ;           }
                  }
            }
         }
      ;MPV_N3(isHold, taps, state)
      ;MPV_N4(isHold, taps, state)
      ;MPV_N5(isHold, taps, state)
which essentially consists of a repeating pattern of:
FunctionName(isHold, taps, state)
{
<Function Body>
}
I am trying to break it down into arrays that consists of the function name and body. I cant use the string MPV in my regex as there are other similar texts files whose function names does not contain MPV.
My exepected output is:
$MyVar [0] :
      MPV_F5(isHold, taps, state)
         {
            if (taps == 1)
            {
                  if (isHold == 0)
                  {
                   ;[HV] T1 | cycle  mute | This is long LONG
                     Sendinput, {U+0398}  ;Θ ;   ;[rr] [cycle mute         ]
                  }
                  else
                  {
                    if (state)
                                          {
                                             while GetKeyState("f5", "p"){
                                                   Sendinput, {U+0399}  ;Ι ;   ;[rr] [add volume 10    ]  
                                                     sleep, 55
                                                 }  
                                          }
                          ; else
                          ;           {
                          ;           }
                  }
            }
         }
$MyVar [1] :
      MPV_N2(isHold, taps, state)
         {
            if (taps == 1)
            {
                  if (isHold == 0)
                  {
                   ;[HV] T1 | cycle  mute | This is long LONG
                     Sendinput, {U+0398}  ;Θ ;   ;[rr] [cycle mute         ]
                  }
                  else
                  {
                    if (state)
                                          {
                                             while GetKeyState("f5", "p"){
                                                   Sendinput, {U+0399}  ;Ι ;   ;[rr] [add volume 10    ]  
                                                     sleep, 55
                                                 }  
                                          }
                          ; else
                          ;           {
                          ;           }
                  }
            }
         }
At first I tried to use Get-Content's -Delimeter parameter:
$mytextfile = "c:\temp\mytextfile.txt"
Get-content $mytextfile -Delimiter '.*[^;]\(isHold, taps, state\)'
It keeps returning the entire content as a single object, After a few more variations I resorted to just using Get-Content -Raw and then -Split operator:
$MyVar = $mytextfile -Split (?m).*[^;]\(isHold, taps, state\)(?s).*\}
I continue to get unexpected results, most commonly the entire content being returned instead of arrays.
I am using RegEx101*, and options are closesly aligned to what powershell expects. I have tried many variations with no desired results.
Here is a link my RegEx101 page.
What could I be doing wrong here?
Any help would be truelly wellcome.
Try the following:
$MyVar =
[regex]::Matches(
(Get-Content -Raw $mytextfile),
'(?sm)\w+\(isHold, taps, state\)\s*\{(?:.(?!\w+\(\w))+\}'
).Value
Note that this approach is computation-intensive and relies on detecting the end of a function not by properly detecting nested { / } pairs, but by assuming that the presence of any subsequent <funcname>(<wordcharacter> substring (e.g. 'MPV_F6(i') implies that the most recent } ended the function body.
See this regex101.com page.

AUv3 extension based on AVAudioUnitSampler not registered

I created a multi-timbral instrument application based on multiple AVAudioUnitSampler instances (one per Midi channel), wrapped in a custom AVSampler class.
I want to expose it also as an AUv3. I followed some articles and samples and put the view controller and other classes in a Framework target, created an AudioUnit extension target (with a dummy/empty class file as I've no implementation to provide).
In the extension's Info.plist (NSExtensionAttributes) I added AudioComponentBundle (points to the AUFramework) and AudioComponents item with factoryFunction (points to $(PRODUCT_MODULE_NAME).MultiSamplerViewController), aumu type. Also added NSExtensionPrincipalClass pointing to AUFramework.MultiSamplerViewController.
In the shared MultiSamplerViewController I implemented
(AUAudioUnit *)createAudioUnitWithComponentDescription:(AudioComponentDescription)desc error:(NSError **)error {
return [[[multiSampler engine] outputNode] AUAudioUnit];
}
It also contains an - (id)initWithCoder:(NSCoder*)decoder method, that instantiates the wrapping MultiSampler and starts an enclosed MidiManager.
The host application target runs fine, however the AU extension plugin isn't listed in GarageBand (even after runnig the host application once). The target platform is iPad.
I added code to load the appex plugin bundle, however it doesn't seem enough to register the plugin. Also I cannot use the AUAudioUnit registerSubclass as I've no concrete AU implementation class (only my wrapper class).
I'm in the same configuration as an application built on AudioKit framework (that originally wrapped AVAudioUnitSampler - and now uses a custom implementation). I looked into AudioKit code and found they implemented AudioUnit protocols methods in their wrapper class (https://github.com/AudioKit/AUv3-Example-App/blob/master/Example%20Plugin%20App%20AU/Audio%20Unit/ExampleApp_AudioUnit.swift). However I don't know what to do in AUAudioUnit methods implementation (setOutputBusArrays, allocateRenderResources, internalRenderBlock, etc.)
EDIT :
I may have to implement AUaudioUnit callbacks.
To pass mainMixerNode buffers to AUaudioUnit render callback I could store (in memory, so would grow over time... not ideal) these through installTapOnBus, and then access these from render callback.
AVSampler : AUAudioUnit
createAudioEngine
  ...
 [mixerNode installTapOnBus:0
                    bufferSize:4096
                        format:[[AVAudioFormat alloc]initWithStreamDescription:&audioFormat]
                         block:^(AVAudioPCMBuffer * _Nonnull buffer, AVAudioTime * _Nonnull when) {
                            
[self.timeToBuffer addObject:buffer forKey:when];
}];
(AUInternalRenderBlock)internalRenderBlock {
  return ^AUAudioUnitStatus(AudioUnitRenderActionFlags    *actionFlags,
                              const AudioTimeStamp     *timestamp,
                              AVAudioFrameCount     frameCount,
                              NSInteger     outputBusNumber,
                              AudioBufferList     *outputBufferListPtr,
                              const AURenderEvent     *realtimeEventListHead,
                              AURenderPullInputBlock     pullInputBlock ) {
        
        int outputNumBuffers = outputBufferListPtr->mNumberBuffers;
float *ptrLeft  = (float*)outputBufferListPtr->mBuffers[0].mData;
        float *ptrRight = NULL;
        if (outputNumBuffers == 2) {
            ptrRight = (float*)outputBufferListPtr->mBuffers[1].mData;
        }
AVAudioPCMBuffer *mixerNodeBuffer = [self.timeToBuffer objectForKey:timestamp];
mixerNodeBuffer.audioBufferList.pointee.mBuffers
int n = frameCount;
if(mixerNodeBuffer.frameLength == frameCount)
for (int i=0;i<n;i++) {
    ptrLeft[i] = mixerNodeBuffer.floatChannelData[0].pointee[n];
    ptrRight[i] = mixerNodeBuffer.floatChannelData[1].pointee[n];
}
  }
}

SwiftUI: Launching three column iPad app with the Sidebar Visible

Using the below code it’s possible to create a basic three-column iPad layout.
#main
struct threepanelApp: App {
var body: some Scene {
WindowGroup {
NavigationView {
List(0..<10, rowContent: { i in
Text(String(describing: i))
})
.listStyle(SidebarListStyle())
.navigationTitle("One")
List(10..<20, rowContent: { i in
Text(String(describing: i))
})
.navigationTitle("Two")
VStack {
Text("Panel Three")
}
.navigationTitle("Three")
}
}
}
}
However, when the app launches, it does so in its two-column layout.
What I'd like to achieve is the app launching in its three-column layout:
Is this possible with SwiftUI 2?
Figured out a hacky way to do this:
Dip into UIKit in .onAppear, find the UISplitViewController, and set its preferredDisplayMode.
var body: some Scene {
        WindowGroup {
            NavigationView {
                List(0..<10, rowContent: { i in
                    Text(String(describing: i))
                })
                .navigationTitle("One")
                ListTwo()
                VStack {
                    Text("Panel Three")
                }
                .navigationTitle("Three")
            }.onAppear {
                let controller = UIApplication.shared.windows.first { $0.isKeyWindow }!.rootViewController
                guard let split = controller?.children[0] as? UISplitViewController else {
                    print("not a split view")
                    return
                }
                split.preferredDisplayMode = .twoBesideSecondary
            }
        }
    }
when adding this extension, then everything is expanded on app start:
extension UISplitViewController {
open override func viewDidLoad() {
super.viewDidLoad()
preferredDisplayMode = .twoBesideSecondary
}
}

Sum up Rows with same ID and Ignore Smaller Category

I have a very large dataset with multiple columns to sum and categories, but here is an example of what i am trying to do:
I want to sum up the "dollars" column to the total Account Number level based on which line with account number has the highest number in the "people" column.  So there is just 1 line for every account number, and the State column will have whichever state has the higher people in it.
Account Number       State        Dollars          People
1                      MA             200             5
1                     NY             100             2
2                      CT            150             3
3                      OH             100             3
4                     VA             300             7
4                      FL             100             3
and it will look like this after the code:
Account Number       State        Dollars          People
1                     MA             300             7
2                      CT             150            3
3                      OH             100             3
4                      VA             400            10
I think this may be a simple fix but please help!
Thanks in advance!!
proc sql;
create table T2 as
select 'Account Number'n, State, sum(Dollars) as Dollars, sum(People) as People, People as People_Order
from T1
group by 'Account Number'n
order by People_Order desc
;quit;
/* keep the first row within previously performed Order By: */
proc sort data=T2 (drop=People_Order) nodupkey; by 'Account Number'n;run;

How to mock a reference parameter value of function argument in GMock EXPECT_CALL

I am novice to google mock just started and tried to write first mock test as follows. AWSS3io is a rest api class to communicate with AWS s3 server to get files. I want to test the -ve scenario i.e 500 response code. Could you please give valuable comments that is this code good or there are other ways to make t more elegant.
================Below is the code.===================
File: AWSS3io.h
---------------------------start-----------------------------------
class AWSS3io  {
        private:
            std::string m_aws_url;
        public:
            IO_STATUS_CODE get(const std::string &key, std::string &output_string, int &resp_code);
            AWSS3io(const std::string & aws_url);
            ~AWSS3io();
    };
#if GTEST
class MockAWSS3io
    {
        private:
            std::string m_aws_url;
        public:
            MockAWSS3io(const std::string & aws_url) { m_aws_url = aws_url; }
            ~MockAWSS3io() {}
            MOCK_METHOD3(get, IO_STATUS_CODE(const std::string &key, std::string &output_string, int &resp_code));
    };
#endif
    class AWSio
    {
        public:
            AWSio(AWSS3io* paws);
            ~AWSio();
            IO_STATUS_CODE get(const std::string &key, std::string &output_string);
#if GTEST
            MockAWSS3io* aws_s3_io = nullptr;
#else
            AWSS3io* aws_s3_io = nullptr;
#endif
    };
---------------------------end-----------------------------------
file: tests/test_aws_mock_test.cpp
---------------------------start-----------------------------------
TEST(FileGetTest, FailureCase) {
    const std::string t_aws_url = "aa.s3.awss3.com";
    MockAWSS3io aws_s3_io(t_aws_url);
    EXPECT_CALL(*aws_s3_io, get(_,_,_))
.Times(AtLeast(2)).WillOnce(testing::SetArgReferee<2>(500)).WillRepeatedly(testing::SetArgReferee<2>(200));
    AWSio awsio(&aws_s3_io);
    std::string key, value;
    EXPECT_TRUE(awsio.get(key, value));
}
int main(int argc, char** argv) {
  ::testing::InitGoogleMock(&argc, argv);
  return RUN_ALL_TESTS();
}
---------------------------end-----------------------------------