Beispiel #1
0
func (s *Say) Hello(ctx context.Context, req *api.Request, rsp *api.Response) error {
	log.Info("Received Say.Hello API request")

	name, ok := req.Get["name"]
	if !ok || len(name.Values) == 0 {
		return errors.BadRequest("go.micro.api.greeter", "Name cannot be blank")
	}

	request := client.NewRequest("go.micro.srv.greeter", "Say.Hello", &hello.Request{
		Name: strings.Join(name.Values, " "),
	})

	response := &hello.Response{}

	if err := client.Call(ctx, request, response); err != nil {
		return err
	}

	rsp.StatusCode = 200
	b, _ := json.Marshal(map[string]string{
		"message": response.Msg,
	})
	rsp.Body = string(b)

	return nil
}
Beispiel #2
0
func (l *Location) Read(ctx context.Context, req *api.Request, rsp *api.Response) error {
	id := extractValue(req.Post["id"])

	if len(id) == 0 {
		return errors.BadRequest(server.Config().Name()+".read", "Require Id")
	}

	request := client.NewRequest("go.micro.srv.geo", "Location.Read", &read.Request{
		Id: id,
	})

	response := &read.Response{}

	err := client.Call(ctx, request, response)
	if err != nil {
		return errors.InternalServerError(server.Config().Name()+".read", "failed to read location")
	}

	b, _ := json.Marshal(response.Entity)

	rsp.StatusCode = 200
	rsp.Body = string(b)

	return nil
}
Beispiel #3
0
func (l *Location) Search(ctx context.Context, req *api.Request, rsp *api.Response) error {
	radius, _ := strconv.ParseFloat(extractValue(req.Post["radius"]), 64)
	typ := extractValue(req.Post["type"])
	entities, _ := strconv.ParseInt(extractValue(req.Post["num_entities"]), 10, 64)

	var latlon map[string]float64
	err := json.Unmarshal([]byte(extractValue(req.Post["center"])), &latlon)
	if err != nil {
		return errors.BadRequest(server.Config().Name()+".search", "invalid center point")
	}

	if len(typ) == 0 {
		return errors.BadRequest(server.Config().Name()+".search", "type cannot be blank")
	}

	if entities == 0 {
		return errors.BadRequest(server.Config().Name()+".search", "num_entities must be greater than 0")
	}

	request := client.NewRequest("go.micro.srv.geo", "Location.Search", &search.Request{
		Center: &common.Location{
			Latitude:  latlon["latitude"],
			Longitude: latlon["longitude"],
		},
		Radius:      radius,
		NumEntities: entities,
		Type:        typ,
	})

	response := &search.Response{}

	err = client.Call(ctx, request, response)
	if err != nil {
		return errors.InternalServerError(server.Config().Name()+".search", "could not retrieve results")
	}

	b, _ := json.Marshal(response.Entities)
	rsp.StatusCode = 200
	rsp.Body = string(b)
	return nil
}
Beispiel #4
0
func call(i int) {
	// Create new request to service go.micro.srv.example, method Example.Call
	req := client.NewRequest("go.micro.srv.example", "Example.Call", &example.Request{
		Name: "John",
	})

	// create context with metadata
	ctx := c.WithMetadata(context.Background(), map[string]string{
		"X-User-Id": "john",
		"X-From-Id": "script",
	})

	rsp := &example.Response{}

	// Call service
	if err := client.Call(ctx, req, rsp); err != nil {
		fmt.Println("call err: ", err, rsp)
		return
	}

	fmt.Println("Call:", i, "rsp:", rsp.Msg)
}
Beispiel #5
0
func main() {
	cmd.Init()

	folders := []string{
		`/mnt/user/films`,
	}

	// Create new request to service go.micro.srv.example, method Example.Call
	req := client.NewRequest("io.jbrodriguez.mediagui.scanner", "Scanner.Scan", &scan.Request{
		// Folders: s.settings.MediaFolders,
		Folders: folders,
	})

	log.Infof("req=%+v", req)

	rsp := &scan.Response{}

	t0 := time.Now()

	// Call service
	if err := client.Call(context.Background(), req, rsp); err != nil {
		log.Warning("Unable to connect to scanning service: %s", err)
		return
	}

	𝛥t := float64(time.Since(t0)) / 1e9

	for _, file := range rsp.Filenames {
		log.Infof("file=%s", file)
	}

	log.Infof("walked %d files in %.3f seconds\n", len(rsp.Filenames), 𝛥t)

	ch := make(chan os.Signal, 1)
	signal.Notify(ch, syscall.SIGTERM, syscall.SIGINT, syscall.SIGKILL)
	log.Infof("Received signal %s", <-ch)
}
Beispiel #6
0
func main() {
	cmd.Init()

	// Create new request to service go.micro.srv.greeter, method Say.Hello
	req := client.NewRequest("go.micro.srv.greeter", "Say.Hello", &hello.Request{
		Name: "John",
	})

	// Set arbitrary headers in context
	ctx := c.WithMetadata(context.Background(), map[string]string{
		"X-User-Id": "john",
		"X-From-Id": "script",
	})

	rsp := &hello.Response{}

	// Call service
	if err := client.Call(ctx, req, rsp); err != nil {
		fmt.Println(err)
		return
	}

	fmt.Println(rsp.Msg)
}
Beispiel #7
0
func rpcHandler(w http.ResponseWriter, r *http.Request) {
	if r.Method != "POST" {
		http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
		return
	}
	defer r.Body.Close()

	var service, method string
	var request interface{}

	// response content type
	w.Header().Set("Content-Type", "application/json")

	switch r.Header.Get("Content-Type") {
	case "application/json":
		b, err := ioutil.ReadAll(r.Body)
		if err != nil {
			e := errors.BadRequest("go.micro.api", err.Error())
			w.WriteHeader(400)
			w.Write([]byte(e.Error()))
			return
		}

		var body map[string]interface{}
		err = json.Unmarshal(b, &body)
		if err != nil {
			e := errors.BadRequest("go.micro.api", err.Error())
			w.WriteHeader(400)
			w.Write([]byte(e.Error()))
			return
		}

		service = body["service"].(string)
		method = body["method"].(string)
		request = body["request"]
	default:
		r.ParseForm()
		service = r.Form.Get("service")
		method = r.Form.Get("method")
		json.Unmarshal([]byte(r.Form.Get("request")), &request)
	}

	var response map[string]interface{}
	req := client.NewJsonRequest(service, method, request)
	err := client.Call(context.Background(), req, &response)
	if err != nil {
		log.Errorf("Error calling %s.%s: %v", service, method, err)
		ce := errors.Parse(err.Error())
		switch ce.Code {
		case 0:
			w.WriteHeader(500)
		default:
			w.WriteHeader(int(ce.Code))
		}
		w.Write([]byte(ce.Error()))
		return
	}

	b, _ := json.Marshal(response)
	w.Header().Set("Content-Length", strconv.Itoa(len(b)))
	w.Write(b)
}
Beispiel #8
0
func Commands() []cli.Command {
	commands := []cli.Command{
		{
			Name:        "registry",
			Usage:       "Query registry",
			Subcommands: registryCommands(),
		},
		{
			Name:  "query",
			Usage: "Query a service method using rpc",
			Action: func(c *cli.Context) {
				if len(c.Args()) < 2 {
					fmt.Println("require service and method")
					return
				}
				service := c.Args()[0]
				method := c.Args()[1]
				var request map[string]interface{}
				var response map[string]interface{}
				json.Unmarshal([]byte(strings.Join(c.Args()[2:], " ")), &request)
				req := client.NewJsonRequest(service, method, request)
				err := client.Call(context.Background(), req, &response)
				if err != nil {
					fmt.Printf("error calling %s.%s: %v\n", service, method, err)
					return
				}
				b, _ := json.MarshalIndent(response, "", "\t")
				fmt.Println(string(b))
			},
		},
		{
			Name:  "health",
			Usage: "Query the health of a service",
			Action: func(c *cli.Context) {
				if !c.Args().Present() {
					fmt.Println("require service name")
					return
				}
				service, err := registry.GetService(c.Args().First())
				if err != nil {
					fmt.Printf("error querying registry: %v", err)
					return
				}
				fmt.Println("node\t\taddress:port\t\tstatus")
				req := client.NewRequest(service.Name, "Debug.Health", &health.Request{})
				for _, node := range service.Nodes {
					address := node.Address
					if node.Port > 0 {
						address = fmt.Sprintf("%s:%d", address, node.Port)
					}
					rsp := &health.Response{}
					err := client.CallRemote(context.Background(), address, req, rsp)
					var status string
					if err != nil {
						status = err.Error()
					} else {
						status = rsp.Status
					}
					fmt.Printf("%s\t\t%s:%d\t\t%s\n", node.Id, node.Address, node.Port, status)
				}
			},
		},
	}

	return append(commands, registryCommands()...)
}
Beispiel #9
0
func (s *Scanner) scanMovies(msg *pubsub.Message) {
	defer s.bus.Pub(nil, "/event/workunit/done")

	// folders := []string{
	// 	"/Volumes/hal-films",
	// 	"/Volumes/wopr-films",
	// }

	// ping := "ping -c1 %s > /dev/null && echo \"YES\" || echo \"NO\""
	// lib.Notify(s.bus, "import:begin", "Import process started")

	if s.settings.UnraidMode {
		// folders := []string{
		// 	`/mnt/user/films`,
		// }
		// filenames := []string{
		// 	"wopr:/mnt/user/films/bluray/ There Be Dragons (2011)/BDMV/BACKUP/MovieObject.bdmv",
		// 	"wopr:/mnt/user/films/bluray/ There Be Dragons (2011)/BDMV/BACKUP/index.bdmv",
		// 	"wopr:/mnt/user/films/bluray/ There Be Dragons (2011)/BDMV/MovieObject.bdmv",
		// 	"wopr:/mnt/user/films/bluray/ There Be Dragons (2011)/BDMV/index.bdmv",
		// 	"wopr:/mnt/user/films/bluray/ There Be Dragons (2011)/CERTIFICATE/BACKUP/id.bdmv",
		// 	"wopr:/mnt/user/films/bluray/ There Be Dragons (2011)/CERTIFICATE/id.bdmv",
		// 	"wopr:/mnt/user/films/bluray/'71 (2014)/BDMV/BACKUP/MovieObject.bdmv",
		// 	"wopr:/mnt/user/films/bluray/'71 (2014)/BDMV/BACKUP/index.bdmv",
		// 	"wopr:/mnt/user/films/bluray/'71 (2014)/BDMV/MovieObject.bdmv",
		// 	"wopr:/mnt/user/films/bluray/'71 (2014)/BDMV/index.bdmv",
		// 	"wopr:/mnt/user/films/bluray/10 Things I Hate About You (1999)/BDMV/BACKUP/MovieObject.bdmv",
		// 	"wopr:/mnt/user/films/bluray/10 Things I Hate About You (1999)/BDMV/BACKUP/index.bdmv",
		// 	"wopr:/mnt/user/films/bluray/10 Things I Hate About You (1999)/BDMV/MovieObject.bdmv",
		// 	"wopr:/mnt/user/films/bluray/10 Things I Hate About You (1999)/BDMV/index.bdmv",
		// 	"wopr:/mnt/user/films/bluray/12 Years A Slave (2013)/BDMV/BACKUP/MovieObject.bdmv",
		// 	"wopr:/mnt/user/films/bluray/12 Years A Slave (2013)/BDMV/BACKUP/index.bdmv",
		// 	"wopr:/mnt/user/films/bluray/12 Years A Slave (2013)/BDMV/MovieObject.bdmv",
		// 	"wopr:/mnt/user/films/bluray/12 Years A Slave (2013)/BDMV/index.bdmv",
		// 	"wopr:/mnt/user/films/bluray/12 Years A Slave (2013)/CERTIFICATE/BACKUP/id.bdmv",
		// 	"wopr:/mnt/user/films/bluray/12 Years A Slave (2013)/CERTIFICATE/id.bdmv",
		// 	"wopr:/mnt/user/films/bluray/13 (2010)/BDMV/BACKUP/MovieObject.bdmv",
		// 	"wopr:/mnt/user/films/bluray/13 (2010)/BDMV/BACKUP/index.bdmv",
		// 	"wopr:/mnt/user/films/bluray/13 (2010)/BDMV/MovieObject.bdmv",
		// 	"wopr:/mnt/user/films/bluray/13 (2010)/BDMV/index.bdmv",
		// 	"wopr:/mnt/user/films/bluray/13 (2010)/CERTIFICATE/BACKUP/id.bdmv",
		// 	"wopr:/mnt/user/films/bluray/13 (2010)/CERTIFICATE/id.bdmv",
		// 	"wopr:/mnt/user/films/blurip/10 Things I Hate About You (1999)/movie.mkv",
		// }

		// mlog.Info("started analysis")
		// s.analyze(filenames)
		// mlog.Info("finished analysis")

		for _, host := range s.settings.UnraidHosts {
			// Create new request to service go.micro.srv.example, method Example.Call
			req := client.NewRequest("io.jbrodriguez.mediagui.agent."+host, "Agent.Scan", &agent.ScanReq{
				// Folders: s.settings.MediaFolders,
				Folders: s.settings.MediaFolders,
				Mask:    s.includedMask,
			})

			rsp := &agent.ScanRsp{}

			// Call service
			if err := client.Call(context.Background(), req, rsp); err != nil {
				mlog.Warning("Unable to connect to service (%s): %s", "io.jbrodriguez.mediagui.agent."+host, err)
				lib.Notify(s.bus, "import:progress", "Unable to connect to host "+host)
				// lib.Notify(s.bus, "import:end", "Import process finished")
				// return
				continue
			}

			s.analyze(rsp.Filenames)
		}
	} else {
		for _, folder := range s.settings.MediaFolders {
			err := s.walk(folder)
			if err != nil {
				mlog.Warning("Unable to scan folder (%s): %s", folder, err)
			}
		}
	}

	// lib.Notify(s.bus, "import:end", "Import process finished")
}
Beispiel #10
0
func (c *Core) pruneMovies(msg *pubsub.Message) {
	t0 := time.Now()

	lib.Notify(c.bus, "prune:begin", "Started Prune Process")

	options := &lib.Options{Offset: 0, Limit: 99999999999999, SortBy: "title", SortOrder: "asc"}
	all := &pubsub.Message{Payload: options, Reply: make(chan interface{}, capacity)}
	c.bus.Pub(all, "/get/movies")

	reply := <-all.Reply
	dto := reply.(*model.MoviesDTO)

	if c.settings.UnraidMode {
		for _, item := range dto.Items {
			// mlog.Info("Item is %s (%s)", item.Title, item.Location)

			index := strings.Index(item.Location, ":")

			host := item.Location[:index]
			location := item.Location[index+1:]

			req := client.NewRequest("io.jbrodriguez.mediagui.agent."+host, "Agent.Exists", &agent.ExistsReq{
				Location: location,
			})

			rsp := &agent.ExistsRsp{}

			if err := client.Call(context.Background(), req, rsp); err != nil {
				mlog.Warning("Unable to connect to service (%s): %s", "io.jbrodriguez.mediagui.agent."+host, err)
				// lib.Notify(s.bus, "import:progress", "Unable to connect to host "+host)
				// lib.Notify(s.bus, "import:end", "Import process finished")
				// return
				continue
			}

			if !rsp.Exists {
				lib.Notify(c.bus, "prune:selected", fmt.Sprintf("UP FOR DELETION: [%d] %s (%s))", item.Id, item.Title, item.Location))

				movie := &pubsub.Message{Payload: item, Reply: make(chan interface{}, capacity)}
				c.bus.Pub(movie, "/command/movie/delete")
			}
		}
	} else {
		for _, item := range dto.Items {
			matches := c.re.FindStringSubmatch(item.Location)
			if len(matches) == 0 {
				continue
			}

			folder := filepath.Join("/Volumes", matches[1])
			if !c.maps[folder] {
				// mlog.Info("Folder not mapped (%s): %s", folder, item.Location)
				continue
			}

			// mlog.Info("Folder mapped (%s): %s", folder, item.Location)

			if _, err := os.Stat(item.Location); err != nil {
				if os.IsNotExist(err) {
					lib.Notify(c.bus, "prune:selected", fmt.Sprintf("UP FOR DELETION: [%d] %s (%s))", item.Id, item.Title, item.Location))

					movie := &pubsub.Message{Payload: item, Reply: make(chan interface{}, capacity)}
					c.bus.Pub(movie, "/command/movie/delete")
				}
			}
		}
	}

	// for _, folder := range c.settings.MediaFolders {
	// 	mlog.Info("folder: %s", folder)
	// 	if _, err := os.Stat(folder); err != nil {
	// 		if os.IsNotExist(err) {
	// 			lib.Notify(c.bus, "prune:error", fmt.Sprintf("Folder %s is not present. Aborting Prune process.", folder))
	// 			return
	// 		}
	// 	}
	// }

	// lib.Notify(c.bus, "prune:end", "Finished Prune Process")
	lib.Notify(c.bus, "prune:end", fmt.Sprintf("Prune process finished (%s elapsed)", time.Since(t0).String()))

}