Own bin/x file gets killed instantly - macos

I am writing a rust script, which I place into my bin folder in the end, so its useable from everywhere. All I do is compile my two rust files into a releasable executable. My rust files look as follows:
// main.rs
mod where_are;
fn main() {
println!("{}", where_are::birthdays());
}
// where_are.rs
pub fn birthdays() -> &'static str { return "~/.birthdays"; }
That gets compiled with sudo cargo build --release. Then the target/release/birthdays file gets copied to usr/local/bin/birthdays. Now when I try to execute birthdays I get following error:
[1] 44039 killed birthdays
Any help would be appreciated!
Important information: If I execute the compiled file before I move it into the bin folder it works perfectly

Related

File paths for running golang code for debug vs run

I have a golang code on Linux VM which I am remotely debugging using VS Code. Below is my folder structure
MainFolder
|__Config
|__Other folders
Other Files
When I run the code using VS debugger, it runs properly and my code is able to find the path to files. But when I use the terminal to the code (I have workspace configured and need other project to run, and one project to debug) using go run ./folder, it gives some path like /tmp/go-build2342342342/b001/ when absolute path is populated. Any idea why it works this way and how to make the behavior consistent for properly getting the path?
Below is the code converting relative path to absolute
dir, err := filepath.Abs(filepath.Dir(os.Args[0]))
if err != nil {
log.Fatal(err)
}
var path = filepath.Join(dir, relPath)
absPath, err := filepath.Abs(path)
Go binaries are compiled, even when run via go run. When you go run a package, os.Args[0] is set to the path of the compiled binary within the build cache, not the directory containing the source code for that binary.
To determine the path to source files, you must either pass the source location explicitly (as a flag or explicit argument), or invoke go run in a well-known directory and use os.Getwd to located it.
However, for run-time debugging information specifically, see the runtime and runtime/debug packages.

error "fork/exec /var/task/main: no such file or directory" while executing aws-lambda function

Getting error fork/exec /var/task/main: no such file or directory while executing lambda function.
I am using windows platform to run and build code in Go.
I have done following steps to deploy go aws-lambda handler:
Written code in go language with VSCode in windows platform
Build project with : go build main.go
Convert main.exe to main.zip
Uploaded main.zip with handler name main aws-lambda fuction using aws console account
Created test event to test lambda function
Got error "fork/exec /var/task/main: no such file or directory while executing lambda function"
package main
import (
"fmt"
"github.com/aws/aws-lambda-go/lambda"
)
// Request represents the requested object
type Request struct {
ID int `json:"ID"`
Value string `json:"Value"`
}
// Response represents the Response object
type Response struct {
Message string `json:"Message"`
Ok bool `json:"Ok"`
}
// Handler represents the Handler of lambda
func Handler(request Request) (Response, error) {
return Response{
Message: fmt.Sprint("Process Request Id %f", request.ID),
Ok: true,
}, nil
}
func main() {
lambda.Start(Handler)
}
build command
go build main.go
Detail Error in AWS console
{
"errorMessage": "fork/exec /var/task/main: no such file or directory",
"errorType": "PathError"
}
Log Output in AWS console
START RequestId: 9ef206ed-5538-407a-acf0-06673bacf2d7 Version: $LATEST
fork/exec /var/task/main: no such file or directory: PathError
null
END RequestId: 9ef206ed-5538-407a-acf0-06673bacf2d7
REPORT RequestId: 9ef206ed-5538-407a-acf0-06673bacf2d7 Duration: 0.64 ms Billed Duration: 100 ms Memory Size: 512 MB Max Memory Used: 31 MB Init Duration: 1.49 ms
In my case the problem was default setted handler to 'hello' function.
Needed to change it to 'main' via AWS Lambda view panel -> Basic Settings -> Edit.
Run following commands in command prompt
set GOOS=linux
set GOARCH=amd64
set CGO_ENABLED=0
After this , build your project and upload zip file to aws console lambda
like this
GOOS=linux GOARCH=amd64 CGO_ENABLED=0 go build -o main main.go
Reference Link : https://github.com/aws/aws-lambda-go
There are two reasons can happen:
You did't use GOOS=linux GOARCH=amd64 with go build, so try:
GOOS=linux GOARCH=amd64 go build -o main main.go
You used to build this programm some CI function with golang-alpine base image, so try to use full golang image instead.
Recently I was facing similar issue, and I solved it. As the error says it s finding executable with handle name, so you should name your executable same as handler.
Follow these steps and your will not get this error, I am using PowerShell
> go.exe get -u github.com/aws/aws-lambda-go/cmd/build-lambda-zip # If you do not this have utility earlier
> $env:GOOS = "linux"
> $env:GOARCH = "amd64"
> $env:CGO_ENABLED = "0"
> go build -o .\Handler .\main.go # considering your are in the same directory where your main.go or handler code is present
> ~\Go\Bin\build-lambda-zip.exe -o .\Handler.zip .\Handler
Upload this code, and change handler name to Handler(name of the executable that you created above)
Let me know if this helps.
In my embarrasing case I was zipping the folder from outside so the path in the zip I was uploading was 'folder/main'
You can find the description when you click AWS Lambda > Functions > <Your function name> > Handler info
You can tell the Lambda runtime which handler method to invoke by
setting the handler parameter on your function's configuration.
When you configure a function in Go, the value of the handler setting
is the executable file name. For example, using Handler would call the
function in the package main of the Handler executable file.
It means that your file which has a handler function is not necessarily named main.go. My Handler on AWS is hello and I use this command to create executable file GOOS=linux GOARCH=amd64 CGO_ENABLED=0 go build -o hello hello.go
Here is my case. I am learning Terraform to deploy AWS Lambda function.
I am following an terraform official document to deploy a hello function.
The page guides me to create a function using Node.js and I rewrite it using Go.
Here is my modified part of main.tf.
resource "aws_lambda_function" "hello_world" {
function_name = "HelloWorld"
s3_bucket = aws_s3_bucket.lambda_bucket.id
s3_key = aws_s3_object.lambda_hello_world.key
runtime = "go1.x"
handler = "hello"
source_code_hash = data.archive_file.lambda_hello_world.output_base64sha256
role = aws_iam_role.lambda_exec.arn
}
I deleted the hello.js file and created the hello.go file.
My hello.go is the same as AWS example
package main
import (
"fmt"
"context"
"github.com/aws/aws-lambda-go/lambda"
)
type MyEvent struct {
Name string `json:"name"`
}
func HandleRequest(ctx context.Context, name MyEvent) (string, error)
{
return fmt.Sprintf("Hello %s!", name.Name ), nil
}
func main() {
lambda.Start(HandleRequest)
}
After deploying the lambda function using terraform, we can verify it.
% aws lambda invoke --region=us-east-1 --function-name=HelloWorld response.json
{
"StatusCode": 200,
"ExecutedVersion": "$LATEST"
}
I hope this is helpful.
My issue (I think) was the zipping tool / GOOS=windows was set wrong.
Zip Go file using AWS Lambda Tool
My setup is windows + following a golang tutorial. Published to lambda, all appeared fine, got the error and was correctly named and built etc.
I think it's the zipping tool, using build-lambda-zip and now it works for me. Note: I tried using another command to get the tool
go.exe get -u github.com/aws/aws-lambda-go/cmd/build-lambda-zip however this didn't actually get the tool for me.
Hopefully this saves someone else half an hour of googling
In my case it was related to my Go setting.
As I use Go Version Manager, I had to run the following to specify the right Go path before compiling my project.
gvm use go1.x.x
Proceed to compile then deploy.
My case was a strange one, but I'll leave it here in case someone needs it.
I built my executable in a Docker container and then used Docker cp to put the file in a local directory. Then I zipped the executable and deployed it.
Apparently, Docker cp creates a symlink-like file rather than an actual file, so it just wouldn't work.
My solution was just to use sudo cp and copy the executable as another file, which created a physical file, and deployed that instead.
This error has nothing to do with the program; it's a configuration issue.
Please try to give the complied go file name in the lambda console under Go Runtime settings -
In my case my go lambda compiled file is test so configured Handler as test and it worked for me.
Example Configuration
In my case, the solution is very simple.
I was wrong with the command build.
what I did was go build . instead of go build main.go
the zip file should be main.zip.
and the handler info section in console AWS should be named main.
not handler because lambda calls the main function first
If deploying with SAM cli, make sure to run "sam build" before the "sam deploy"
In my case this had to do with the image I was using to build the go binaries. I switched from using alpine to using amazon linux 2 and the problem was solved.
setting environment variable CGO_ENABLED to 0 solved my problem, this is when using sam local start-api to locally test endpoint

Cucumber-cpp step defiinition runner exits immediately

Based on the instructions given at cucumber-cpp github repo and cucumber-cpp step definition quick-start guide , I created my cucumber step definition files. The features and their step_definition files are under features/ folder, and the cpp code is built with cucumber-cpp headers and linked against libcucumber-cpp.a as instructed.
Cucumber step definition runners should stay running as a seperate process and cucumber command should execute while the runner is running. Indeed, the examples in the cucumber-cpp repository execute like that, but when I create my own step definitions, with gtest or boost test, they execute immediately, without waiting for calls from cucumber.
Onats-MacBook-Pro:bin onatbas$ ./tests/AdditionTest_TESTTARGET
Running main() from gtest_main.cc
[==========] Running 0 tests from 0 test cases.
[==========] 0 tests from 0 test cases ran. (0 ms total)
[ PASSED ] 0 tests.
Onats-MacBook-Pro:bin onatbas$
Instead of executing immediately, it should say nothing and wait for cucumber calls. I copy-pasted the example code from the cucumber-cpp into my project and they, too, exit immediately. So even though there's no source code difference between cucumber-cpp's examples and mine, they act differently.
I suspected the cmake build scripts might be linking with different libraries, but the linkage process is exactly the same too.
Does anybody have any idea on why this might be happening?
Here's the repository with minimum code that reproduces the error I have. https://github.com/onatbas/CucumberCppTest
The complete trace is at readme.
The cucumber files are under features/, and ther's only one feature that's identical to what's here
The runner executable is defined in tests/CMakeLists.txt
For quick reference: Here's the step-definition file
AdditionTest.cxx
#include <boost/test/unit_test.hpp>
#include <cucumber-cpp/defs.hpp>
#include <CucumberApp.hxx>
using cucumber::ScenarioScope;
struct CalcCtx {
Calculator calc;
double result;
};
GIVEN("^I have entered (\\d+) into the calculator$") {
REGEX_PARAM(double, n);
ScenarioScope<CalcCtx> context;
context->calc.push(n);
}
WHEN("^I press add") {
ScenarioScope<CalcCtx> context;
context->result = context->calc.add();
}
WHEN("^I press divide") {
ScenarioScope<CalcCtx> context;
context->result = context->calc.divide();
}
THEN("^the result should be (.*) on the screen$") {
REGEX_PARAM(double, expected);
ScenarioScope<CalcCtx> context;
BOOST_CHECK_EQUAL(expected, context->result);
}
and here's the tests/CMakeLists.txt file where the executable is added.
cmake_minimum_required(VERSION 3.1)
find_package(Threads)
set(CUCUMBERTEST_TEST_DEPENDENCIES cucumberTest
${CMAKE_THREAD_LIBS_INIT}
${GTEST_BOTH_LIBRARIES}
${GMOCK_BOTH_LIBRARIES}
${CMAKE_THREAD_LIBS_INIT}
${Boost_LIBRARIES}
${CUCUMBER_BINARIES}
)
macro(ADD_NEW_CUCUMBER_TEST TEST_SOURCE FOLDER_NAME)
set (TARGET_NAME ${TEST_SOURCE}_TESTTARGET)
add_executable(${TARGET_NAME} ${CMAKE_SOURCE_DIR}/features/step_definitions/${TEST_SOURCE})
target_link_libraries(${TARGET_NAME} ${CUCUMBERTEST_TEST_DEPENDENCIES})
add_test(NAME ${TEST_SOURCE} COMMAND ${TARGET_NAME})
set_property(TARGET ${TARGET_NAME} PROPERTY FOLDER ${FOLDER_NAME})
endmacro()
ADD_NEW_CUCUMBER_TEST(AdditionTest "cucumberTest_tests")
Your example outputs
Running main() from gtest_main.cc
That main method will run the test runner's default behaviour instead of Cucumber-CPP's. The main mathod that you want (src/main.cpp) is included as part of the compiled cucumber-cpp library.
Try moving ${CUCUMBER_BINARIES} in CUCUMBERTEST_TEST_DEPENDENCIES before all others, or linking to testing libraries that do not contain a main method (e.g. GoogleTest ships with two libraries: one with and one without the main method).

Unable to use the same relative path in my program AND my unit tests

In my Go Project I use a function that opens a specific file and returns its content. The file is stored in another directory but still inside my project directory.
package infrastructure
func openKey() ([]byte, error) {
if path, err := filepath.Abs("../security/key.rsa"); err != nil {
return nil, err
}
return ioutil.ReadFile(path)
}
This function works if I call it from a unit test. But if I call the same function in my program, I've this error:
2015/08/13 15:47:54 open
/me/go/src/github.com/myaccount/security/key.rsa: no such file
or directory
The correct absolute path of the file is:
/me/go/src/github.com/myaccount/myrepo/security/key.rsa
Both code that use the openKey function (from my program and unit test) are in the same package: infrastructure
Here is how I execute my program:
go install && ../../../../bin/myproject
And how I execute my unit tests:
go test ./...
And finally the directory structure of my project:
go/src/github.com/myaccount/myrepo/:
- main.go
- security:
- key.rsa // The file that I want to open
- ...
- infrastructure
- openFile.go // The file with the func `openKey``
- server.go // The file with the func that call the func `openKey`
- openFile_test.go // The unit test that calls the func `openKey`
Edit:
Here are the absolute paths of where the binary of my program is located:
/Users/me/Documents/DeĢveloppement/Jean/go/bin
And where my unit tests are located:
/var/folders/tj/8ywtc7pj3rs_j0y6zzldwh5h0000gn/T/go-build221890578/github.com/myaccount/myrepo/infrastructure/_test
Any suggestion?
Thanks!
First, you shouldn't use the same files when running your tests than when running your application in production. Because the test files are accessible to everyone that has access to the repository, which is a security fail.
As said in the comments, the problem is that when running your tests, the working directory is these of the source code (in fact, go copy the whole bunch into a temp directory prior to running the tests), while when you run the program for real, the working directory is the one you are running the command from, hence the wrong relative path.
What I would advise is to use a configuration option to get a the file from which load your file (or a base directory to use with your paths). Either using an environment variable (I strongly encourage you to do that, see the 12factors manofesto for details), a configuration file, a command-line flag, etc.
The go test ./... command changes the current directory to go/src/github.com/myaccount/myrepo/infrastructure before running the tests in that directory. So all relative paths in the tests are relative to the infrastructure directory.
A simple, robust way to allow testing would be to change the signature of your function.
func openKey(relPath string) ([]byte, error) {
if path, err := filepath.Abs(relPath); err != nil {
return nil, err
}
return ioutil.ReadFile(path)
}
This gives you freedom to place key.rsa anywhere during testing, you can for example make a copy of it and store it in infrastructure
An even more elegant and robust way would be to use io.Reader
func openKey(keyFile io.Reader) ([]byte, error) {
return ioutil.ReadAll(keyFile)
}
since you can pass it a strings.Reader for testing. This means that you can test your code without having to rely on the filesystem at all. But that's probably overkill in this case.

Compiling a Vala source On Windows

I compiled a vala program by using following command:
valac test.vala
Of course am I able to run the program on my computer, but when I am trying to run the .exe file on a different one I get following error:
libglib-***.dll is missing on this computer
This is how my source code looks like:
using GLib;
int main(string[] args)
{
bool running = true;
while(running)
{
print("Hello World\n");
}
return 0;
}
The error is pretty clear, but what can I do against it? Thanks in advance.
Along your exe file you will need to install all the libraries you use (glib, gio, etc ...) and their own dependencies (Gtk will require gdk,cairo,pango, and some more).
Edit: take a look at this question on SO, the minimal dependencies are listed.

Resources