Connection error rpc with Golang and DGraph - go

i'm trying make a mutation inside a DGraph database, but when i run the code, it throws me the next error:
rpc error: code = Unavailable desc = connection close exit status 1
I'm using dGraph with docker in the port 8000, my code of golang here:
package main
import (
"fmt"
"context"
"encoding/json"
"log"
dgo "github.com/dgraph-io/dgo"
api "github.com/dgraph-io/dgo/protos/api"
grpc "google.golang.org/grpc"
)
type Person struct {
Name string `json:"name,omitempty"`
Lastname string `json:"lastname,omitempty"`
}
func main() {
conn, err := grpc.Dial("localhost:8000", grpc.WithInsecure())
if err != nil {
log.Fatal(err)
}
defer conn.Close()
dgraphClient := dgo.NewDgraphClient(api.NewDgraphClient(conn))
p := Person {
Name: "Giovanni",
Lastname: "Mosquera Diazgranados",
}
txn := dgraphClient.NewTxn()
ctx := context.Background()
defer txn.Discard(ctx)
pb, err := json.Marshal(p)
if err != nil {
log.Fatal(err)
}
mu := &api.Mutation{
SetJson: pb,
}
res, err := txn.Mutate(ctx, mu)
if err != nil {
fmt.Println("Aqui toy")
log.Fatal(err)
} else {
fmt.Println(res)
}
}
How can i solve this error to connect with my DGraph and make a mutation?

Welcome to Stack Overflow!
To get your code working locally with the docker "standalone" version of DGraph I had to change 2 things:
use port 9080. The container exposes 3 ports: 8000, 8080, 9080. Using 8080 or 8000 I get the same error you mentioned.
use the v2 imports. Not sure which version of DGraph server you are running, so you might not need to do this. But in case you have a new server you need these imports:
import (
dgo "github.com/dgraph-io/dgo/v2"
api "github.com/dgraph-io/dgo/v2/protos/api"
)

Port 8000 is for the ratel-ui which comes with dgraph. To make mutations using the dgraph go client you will want to connect to the exposed grpc-alpha port, this is typically on 9080.

Related

How to connect mongodb in K8s via a go app

I have a mongodb service up and running. I port-forward to access it locally and in the meantime, I try to check connection with a go app. But I get the error below.
panic: error parsing uri: lookup _mongodb._tcp.localhost on 8.8.8.8:53: no such host
Port-forward:
kubectl port-forward service/mongodb-svc 27017:27017
Go app:
package main
import (
"context"
"fmt"
//"log"
"time"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
"go.mongodb.org/mongo-driver/mongo/readpref"
)
func main() {
username := "username"
address := "localhost"
password := "password"
// Replace the uri string with your MongoDB deployment's connection string.
uri := "mongodb+srv://" + username + ":" + password + "#" + address + "/admin?w=majority"
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
client, err := mongo.Connect(ctx, options.Client().ApplyURI(uri))
if err != nil {
panic(err)
}
defer func() {
if err = client.Disconnect(ctx); err != nil {
panic(err)
}
}()
// Ping the primary
if err := client.Ping(ctx, readpref.Primary()); err != nil {
panic(err)
}
fmt.Println("Successfully connected and pinged.")
}
Your client is trying to a DNS service lookup because you specified the +srv connection type in your URI. Stop doing that and use the correct connection string instead. We do support that in-cluster but not via port forward. I suspect you're trying to mix and match tutorials for both in-cluster and out of cluster. You can't do that.

HTTP GET, from specific local IP, using alternate DNS

First, newbie to Go. Next, I am trying to run the following code below and experiencing this error
2021/06/16 18:24:15 Get "https://www.cnn.com": dial tcp: lookup www.cnn.com on 192.168.100.200:53: dial udp: address 192.168.100.65: mismatched local address type
exit status 1
My end goal is to use a predefined DNS server (alternate from the OS) and create a HTTP/S connection using a specific local IP address. I also suspect this could be accomplished with less code, so would love to understand this more from someone more familiar with Go.
package main
import (
"context"
"io/ioutil"
"log"
"net"
"net/http"
"time"
)
func main() {
q := net.ParseIP("192.168.100.65")
addr := &net.IPAddr{q,""}
var (
dnsResolverIP = "8.8.8.8:53"
dnsResolverProto = "udp"
dnsResolverTimeoutMs = 5000
)
dialer := &net.Dialer{
Resolver: &net.Resolver {
PreferGo: true,
Dial: func(ctx context.Context, network, address string) (net.Conn, error) {
d := net.Dialer {
LocalAddr: addr,
Timeout: time.Duration(dnsResolverTimeoutMs) * time.Millisecond,
}
return d.DialContext(ctx, dnsResolverProto, dnsResolverIP)
},
},
}
dialContext := func(ctx context.Context, network, addr string) (net.Conn, error) {
return dialer.DialContext(ctx, network, addr)
}
http.DefaultTransport.(*http.Transport).DialContext = dialContext
httpClient := &http.Client{}
// Testing the new HTTP client with the custom DNS resolver.
resp, err := httpClient.Get("https://www.cnn.com")
if err != nil {
log.Fatalln(err)
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
log.Fatalln(err)
}
log.Println(string(body))
}

Golang SSH Source Port

I have a requirement to use a static source port. We will do an IPTables redirect rule based on this source port. So, the static source port is used as an identifier as multiple connections are pending to the same destination port on the server. Think poor man's TCP mux a la iptables.
I have followed the Golang examples and cobbled some messy code together. I am not a programmer.
The ssh.dial function handles a lot, that becomes apparent once you use net.dial along with ssh.NewClientConn, ssh.NewClient and ssh.NewSession.
I see there is no ProxyCommand like in OpenSSH config options. I was using:
ssh -o ProxyCommand="ncat --source-port %h %p" ...
to achieve the requirement in a Bash script.
Additionally, I apologise for a loaded question but ncat et al. allow me to reuse the source port immediately.
Whereas Golang SSH leaves a TIME-WAIT 0 0 192.168.99.53:31337 192.168.99.7:22 for 60 seconds on Arch Linux.
Obviously, subsequent binds to said source port result in an error.
WRT the below code:
I have omitted the ExampleHostKeyCheck function
I know the sClient.Listen is a poor attempt at getting this work
The remote port forward does NOT appear on the server
I'm assuming a LOT more code is now required to handle the channels etc.?
The shell command does work, the file appears in /tmp/
package main
import (
"bytes"
"log"
"net"
"os"
"bufio"
"strings"
"path/filepath"
"golang.org/x/crypto/ssh"
)
func main() {
hostKey, err := ExampleHostKeyCheck()
conf := &ssh.ClientConfig{
User: "robert",
Auth: []ssh.AuthMethod{
ssh.Password("password"),
},
HostKeyCallback: ssh.FixedHostKey(hostKey),
}
server, _ := net.ResolveTCPAddr("tcp", "centos7.ephemeric.local:22")
client, _ := net.ResolveTCPAddr("tcp", ":31337")
cc, err := net.DialTCP("tcp", client, server)
//cc, err := net.DialTCP("tcp", nil, server)
if err != nil {
log.Fatalf("%s", err)
}
defer cc.Close()
conn, chans, reqs, err := ssh.NewClientConn(cc, "", conf)
if err != nil {
log.Fatalf("%s", err)
}
defer conn.Close()
// https://stackoverflow.com/questions/35906991/go-x-crypto-ssh-how-to-establish-ssh-connection-to-private-instance-over-a-ba
sClient := ssh.NewClient(conn, chans, reqs)
if err != nil {
log.Fatalf("%s", err)
}
defer sClient.Close()
session, err := sClient.NewSession()
if err != nil {
log.Fatalf("%s", err)
}
defer session.Close()
sListen, err := sClient.Listen("tcp", "127.0.0.1:31337")
if err != nil {
log.Fatal("unable to register tcp forward: ", err)
}
defer sListen.Close()
var b bytes.Buffer // import "bytes"
session.Stdout = &b // get output
// You can also pass what gets input to the stdin, allowing you to pipe content from client to server session.Stdin = bytes.NewBufferString("MyInput").
err = session.Run("echo slobwashere >>/tmp/slobwashere; ls")
}
Thank you.

Handle Jaeger errors

I am planning to use Jaeger tracing in on my Golang server. Everything is ok but I haven't found a way to handle Jaeger errors. I want to catch, for example, connection error to Jaeger backend while sending trace and write it to loggly.
Code example:
package main
import (
"fmt"
"log"
"golang.org/x/net/context"
"contrib.go.opencensus.io/exporter/jaeger"
"go.opencensus.io/trace"
)
func main() {
agentEndpointURI := "localhost:6831"
collectorEndpointURI := "http://localhost:14268/api/traces"
je, err := jaeger.NewExporter(jaeger.Options{
AgentEndpoint: agentEndpointURI,
CollectorEndpoint: collectorEndpointURI,
ServiceName: "example",
})
if err != nil {
log.Fatalf("Failed to create the Jaeger exporter: %v", err)
}
trace.RegisterExporter(je)
trace.ApplyConfig(trace.Config{
DefaultSampler: trace.AlwaysSample(),
})
traceMethod()
}
func traceMethod() {
ctx := context.Background()
ctx, span := trace.StartSpan(ctx, "traceMethod")
// Do something here if the trace doesn't reach jaeger backend, write error to loggly
fmt.Println("send trace")
defer span.End()
}

how to increase golang.org/x/crypto/ssh verbosity

i wanted to use golang.org/x/crypto/ssh to write a little program which is able to read the equivalent to ssh -v output. While i am able to connect via the ssh package to my server i have no idea how to enable verbose output or get to the desired information in it. As i am new to golang i am not even able to decide if it is possible at all.
Here is my code so far
package main
import (
"fmt"
"golang.org/x/crypto/ssh"
)
type SSHClient struct {
Config *ssh.ClientConfig
Host string
Port int
}
func main() {
sshConfig := &ssh.ClientConfig{
User: "your_user_name",
Auth: []ssh.AuthMethod{
ssh.Password("your_password"),
},
}
client := &SSHClient{
Config: sshConfig,
Host: "example.com",
Port: 22,
}
client.test()
_, err := ssh.Dial("tcp", "example.com:22", sshConfig)
if err != nil {
fmt.Printf("Failed to dial: %s", err)
}
}
func (client *SSHClient) test() {
fmt.Println("test")
}
As a quick hack you can open $GOPATH/golang.org/x/crypto/ssh/mux.go file, change const debugMux = false to const debugMux = true and recompile your program.
In order to see the debug logging make your program do something first:
s, err := c.NewSession()
if err != nil {
fmt.Printf("Failed to create session: %s", err)
}
fmt.Println(s.CombinedOutput("hostname"))

Resources