示例#1
0
func (t *TopologyApi) topologySearch(w http.ResponseWriter, r *auth.AuthenticatedRequest) {
	w.Header().Set("Content-Type", "application/json; charset=UTF-8")

	resource := Topology{}

	data, _ := ioutil.ReadAll(r.Body)
	if len(data) != 0 {
		if err := json.Unmarshal(data, &resource); err != nil {
			w.WriteHeader(http.StatusBadRequest)
			w.Write([]byte(err.Error()))
			return
		}
		if err := validator.Validate(resource); err != nil {
			w.WriteHeader(http.StatusBadRequest)
			w.Write([]byte(err.Error()))
			return
		}
	}

	if resource.GremlinQuery == "" {
		w.WriteHeader(http.StatusNoContent)
		return
	}

	tr := traversal.NewGremlinTraversalParser(strings.NewReader(resource.GremlinQuery), t.Graph)
	tr.AddTraversalExtension(topology.NewTopologyTraversalExtension())
	if t.TableClient != nil {
		tr.AddTraversalExtension(ftraversal.NewFlowTraversalExtension(t.TableClient, t.Storage))
	}

	ts, err := tr.Parse()
	if err != nil {
		w.WriteHeader(http.StatusBadRequest)
		w.Write([]byte(err.Error()))
		return
	}

	res, err := ts.Exec()
	if err != nil {
		w.WriteHeader(http.StatusBadRequest)
		w.Write([]byte(err.Error()))
		return
	}

	w.WriteHeader(http.StatusOK)
	if err := json.NewEncoder(w).Encode(res); err != nil {
		panic(err)
	}
}
示例#2
0
var CaptureCreate = &cobra.Command{
	Use:   "create",
	Short: "Create capture",
	Long:  "Create capture",
	Run: func(cmd *cobra.Command, args []string) {
		client, err := api.NewCrudClientFromConfig(&AuthenticationOpts)
		if err != nil {
			logging.GetLogger().Criticalf(err.Error())
		}

		capture := api.NewCapture(gremlinQuery, bpfFilter)
		capture.Name = captureName
		capture.Description = captureDescription
		capture.Type = captureType
		if err := validator.Validate(capture); err != nil {
			fmt.Println(err.Error())
			cmd.Usage()
			os.Exit(1)
		}
		if err := client.Create("capture", &capture); err != nil {
			logging.GetLogger().Errorf(err.Error())
			os.Exit(1)
		}
		printJSON(&capture)
	},
}

var CaptureList = &cobra.Command{
	Use:   "list",
	Short: "List captures",
示例#3
0
文件: alert.go 项目: nplanel/skydive
	Use:   "create",
	Short: "Create alert",
	Long:  "Create alert",
	Run: func(cmd *cobra.Command, args []string) {
		client, err := api.NewCrudClientFromConfig(&authenticationOpts)
		if err != nil {
			logging.GetLogger().Criticalf(err.Error())
		}

		alert := api.NewAlert()
		alert.Name = alertName
		alert.Description = alertDescription
		alert.Select = alertSelect
		alert.Action = alertAction
		alert.Test = alertTest
		if errs := validator.Validate(alert); errs != nil {
			fmt.Println("Error: ", errs)
			cmd.Usage()
			os.Exit(1)
		}
		if err := client.Create("alert", &alert); err != nil {
			logging.GetLogger().Errorf(err.Error())
			os.Exit(1)
		}
		printJSON(&alert)
	},
}

var AlertList = &cobra.Command{
	Use:   "list",
	Short: "List alerts",
func (pi *PacketInjectorApi) injectPacket(w http.ResponseWriter, r *auth.AuthenticatedRequest) {
	decoder := json.NewDecoder(r.Body)
	var ppr PacketParamsReq
	err := decoder.Decode(&ppr)
	if err != nil {
		w.WriteHeader(http.StatusBadRequest)
		w.Write([]byte(err.Error()))
		return
	}
	defer r.Body.Close()

	if errs := validator.Validate(&ppr); errs != nil {
		w.WriteHeader(http.StatusBadRequest)
		w.Write([]byte(err.Error()))
		return
	}

	srcNode := pi.getNode(ppr.Src)
	dstNode := pi.getNode(ppr.Dst)
	if srcNode == nil || dstNode == nil {
		writeError(w, http.StatusBadRequest, errors.New("Not able to find a Node"))
		return
	}

	srcdata := srcNode.Metadata()
	dstdata := dstNode.Metadata()

	if _, ok := srcdata["IPV4"]; !ok {
		writeError(w, http.StatusBadRequest, errors.New("Source Node doesn't have an IP"))
		return
	}
	if _, ok := dstdata["IPV4"]; !ok {
		writeError(w, http.StatusBadRequest, errors.New("Destination Node doesn't have an IP"))
		return
	}

	if srcdata["IPV4"] == "" || srcdata["MAC"] == "" ||
		dstdata["IPV4"] == "" || dstdata["MAC"] == "" {
		writeError(w, http.StatusBadRequest, errors.New("Selected nodes are not proper"))
		return
	}

	pp := packet_injector.PacketParams{
		SrcNode: srcNode,
		DstNode: dstNode,
		Type:    ppr.Type,
		Payload: ppr.Payload,
		Count:   ppr.Count,
	}

	host := srcNode.Host()
	if err := pi.PIClient.InjectPacket(host, &pp); err != nil {
		writeError(w, http.StatusBadRequest, err)
		return
	}
	w.Header().Set("Content-Type", "application/json; charset=UTF-8")
	w.WriteHeader(http.StatusOK)
	if err := json.NewEncoder(w).Encode(pp); err != nil {
		panic(err)
	}
}
示例#5
0
文件: api.go 项目: nplanel/skydive
func (a *ApiServer) RegisterApiHandler(handler ApiHandler) error {
	name := handler.Name()
	title := strings.Title(name)

	routes := []shttp.Route{
		{
			title + "Index",
			"GET",
			"/api/" + name,
			func(w http.ResponseWriter, r *auth.AuthenticatedRequest) {
				w.Header().Set("Content-Type", "application/json; charset=UTF-8")
				w.WriteHeader(http.StatusOK)

				resources := handler.Index()
				if err := json.NewEncoder(w).Encode(resources); err != nil {
					logging.GetLogger().Criticalf("Failed to display %s: %s", name, err.Error())
				}
			},
		},
		{
			title + "Show",
			"GET",
			shttp.PathPrefix(fmt.Sprintf("/api/%s/", name)),
			func(w http.ResponseWriter, r *auth.AuthenticatedRequest) {
				id := r.URL.Path[len(fmt.Sprintf("/api/%s/", name)):]
				if id == "" {
					w.WriteHeader(http.StatusBadRequest)
					return
				}

				resource, ok := handler.Get(id)
				if !ok {
					w.WriteHeader(http.StatusNotFound)
					return
				}
				w.Header().Set("Content-Type", "application/json; charset=UTF-8")
				w.WriteHeader(http.StatusOK)
				if err := json.NewEncoder(w).Encode(resource); err != nil {
					logging.GetLogger().Criticalf("Failed to display %s: %s", name, err.Error())
				}
			},
		},
		{
			title + "Insert",
			"POST",
			"/api/" + name,
			func(w http.ResponseWriter, r *auth.AuthenticatedRequest) {
				resource := handler.New()

				// keep the original ID
				id := resource.ID()

				if err := json.NewDecoder(r.Body).Decode(&resource); err != nil {
					writeError(w, http.StatusBadRequest, err)
					return
				}

				resource.SetID(id)

				if err := validator.Validate(resource); err != nil {
					writeError(w, http.StatusBadRequest, err)
					return
				}

				if err := handler.Create(resource); err != nil {
					writeError(w, http.StatusBadRequest, err)
					return
				}

				data, err := json.Marshal(&resource)
				if err != nil {
					writeError(w, http.StatusBadRequest, err)
					return
				}

				w.Header().Set("Content-Type", "application/json; charset=UTF-8")
				w.WriteHeader(http.StatusOK)
				if _, err := w.Write(data); err != nil {
					logging.GetLogger().Criticalf("Failed to create %s: %s", name, err.Error())
				}
			},
		},
		{
			title + "Delete",
			"DELETE",
			shttp.PathPrefix(fmt.Sprintf("/api/%s/", name)),
			func(w http.ResponseWriter, r *auth.AuthenticatedRequest) {
				id := r.URL.Path[len(fmt.Sprintf("/api/%s/", name)):]
				if id == "" {
					w.WriteHeader(http.StatusBadRequest)
					return
				}

				if err := handler.Delete(id); err != nil {
					writeError(w, http.StatusBadRequest, err)
					return
				}

				w.Header().Set("Content-Type", "application/json; charset=UTF-8")
				w.WriteHeader(http.StatusOK)
			},
		},
	}

	a.HTTPServer.RegisterRoutes(routes)

	if _, err := a.EtcdKeyAPI.Set(context.Background(), "/"+name, "", &etcd.SetOptions{Dir: true}); err != nil {
		if _, err = a.EtcdKeyAPI.Get(context.Background(), "/"+name, nil); err != nil {
			return err
		}
	}

	a.handlers[handler.Name()] = handler

	return nil
}
	Short:        "inject packets",
	Long:         "inject packets",
	SilenceUsage: false,
	Run: func(cmd *cobra.Command, args []string) {
		client, err := api.NewCrudClientFromConfig(&AuthenticationOpts)
		if err != nil {
			logging.GetLogger().Criticalf(err.Error())
		}

		packet := &api.PacketParamsReq{}
		packet.Src = srcNode
		packet.Dst = dstNode
		packet.Type = packetType
		packet.Payload = payload
		packet.Count = count
		if errs := validator.Validate(packet); errs != nil {
			fmt.Println("Error: ", errs)
			cmd.Usage()
			os.Exit(1)
		}
		if err := client.Create("injectpacket", &packet); err != nil {
			logging.GetLogger().Errorf(err.Error())
			os.Exit(1)
		}
	},
}

func addInjectPacketFlags(cmd *cobra.Command) {
	cmd.Flags().StringVarP(&srcNode, "src", "", "", "source node gremlin expression")
	cmd.Flags().StringVarP(&dstNode, "dst", "", "", "destination node gremlin expression")
	cmd.Flags().StringVarP(&packetType, "type", "", "icmp", "packet type: icmp")