Example #1
0
func (a *Api) saveFirewall(w http.ResponseWriter, r *http.Request) {
	firewall := model.Firewall{}
	if err := json.NewDecoder(r.Body).Decode(&firewall); err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	name := firewall.Name
	container := firewall.Container
	gatewayIP := firewall.GatewayIP

	if name == "" || container == "" {
		http.Error(w, "name or container cannot be empty.", http.StatusInternalServerError)
		return
	}

	nameurl := path.Join(pathNameFirewall, name)
	exists, err := a.store.Exists(nameurl)
	if exists {
		http.Error(w, ErrFirewallNameExists.Error(), http.StatusInternalServerError)
		return
	}

	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}

	client := newClientAndScheme(a.client.TLSConfig)
	resp, err := client.Get(a.dUrl + "/containers/" + container + "/json")
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}

	//cleanup
	defer resp.Body.Close()
	defer closeIdleConnections(client)

	data, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}

	if resp.StatusCode >= 400 {
		http.Error(w, string(data), http.StatusInternalServerError)
		return
	}

	var info ContainerInfo
	if err := json.Unmarshal(data, &info); err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}

	if gatewayIP == "" {
		gatewayIP = info.Node.IP
	}
	gateway, err := a.choiceGateway(gatewayIP)
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}

	firewall.Container = info.Id
	firewall.DatapathID = gateway.DatapathID
	firewall.GatewayIP = gateway.ExtIP

	value, err := json.Marshal(firewall)
	if err != nil {
		log.Fatalf("json marshal error: %v", err)
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}

	nodeurl := path.Join(pathNodeFirewall, gateway.DatapathID, strconv.Itoa(firewall.GatewayPort))
	exists, err = a.store.Exists(nodeurl)
	if exists {
		http.Error(w, ErrFirewallPortExists.Error(), http.StatusInternalServerError)
		return
	}
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}

	if err := a.store.Put(nodeurl, value, nil); err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}

	if err := a.store.Put(nameurl, value, nil); err != nil {
		a.store.Delete(nodeurl)
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}

	w.Header().Set("Content-Type", "application/json")
	if err := json.NewEncoder(w).Encode(firewall); err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
}