You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@trafficcontrol.apache.org by mi...@apache.org on 2018/05/23 16:50:23 UTC

[incubator-trafficcontrol] branch master updated: Add TO Go delete cdns/name

This is an automated email from the ASF dual-hosted git repository.

mitchell852 pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/incubator-trafficcontrol.git


The following commit(s) were added to refs/heads/master by this push:
     new 1372532  Add TO Go delete cdns/name
1372532 is described below

commit 13725325f2020ffe68122f4cbe8856aa75da2bd6
Author: Robert Butts <ro...@apache.org>
AuthorDate: Sat May 19 15:27:28 2018 -0600

    Add TO Go delete cdns/name
---
 .../traffic_ops_golang/api/shared_handlers.go      | 13 +++
 traffic_ops/traffic_ops_golang/cdn/namedelete.go   | 95 ++++++++++++++++++++++
 traffic_ops/traffic_ops_golang/routes.go           |  2 +
 3 files changed, 110 insertions(+)

diff --git a/traffic_ops/traffic_ops_golang/api/shared_handlers.go b/traffic_ops/traffic_ops_golang/api/shared_handlers.go
index b10e958..c4b520f 100644
--- a/traffic_ops/traffic_ops_golang/api/shared_handlers.go
+++ b/traffic_ops/traffic_ops_golang/api/shared_handlers.go
@@ -465,6 +465,19 @@ func RespWriter(w http.ResponseWriter, r *http.Request) func(v interface{}, err
 	}
 }
 
+// WriteRespAlert creates an alert, serializes it as JSON, and writes that to w. Any errors are logged and written to w via tc.GetHandleErrorsFunc.
+// This is a helper for the common case; not using this in unusual cases is perfectly acceptable.
+func WriteRespAlert(w http.ResponseWriter, r *http.Request, level tc.AlertLevel, msg string) {
+	resp := struct{ tc.Alerts }{tc.CreateAlerts(level, msg)}
+	respBts, err := json.Marshal(resp)
+	if err != nil {
+		HandleErr(w, r, http.StatusInternalServerError, nil, errors.New("marshalling JSON: "+err.Error()))
+		return
+	}
+	w.Header().Set(tc.ContentType, tc.ApplicationJson)
+	w.Write(respBts)
+}
+
 // IntParams parses integer parameters, and returns map of the given params, or an error. This guarantees if error is nil, all requested parameters successfully parsed and exist in the returned map, hence if error is nil there's no need to check for existence. The intParams may be nil if no integer parameters are required.
 // This is a helper for the common case; not using this in unusual cases is perfectly acceptable.
 func IntParams(params map[string]string, intParamNames []string) (map[string]int, error) {
diff --git a/traffic_ops/traffic_ops_golang/cdn/namedelete.go b/traffic_ops/traffic_ops_golang/cdn/namedelete.go
new file mode 100644
index 0000000..6fb4389
--- /dev/null
+++ b/traffic_ops/traffic_ops_golang/cdn/namedelete.go
@@ -0,0 +1,95 @@
+package cdn
+
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+import (
+	"database/sql"
+	"errors"
+	"net/http"
+
+	"github.com/apache/incubator-trafficcontrol/lib/go-tc"
+	"github.com/apache/incubator-trafficcontrol/traffic_ops/traffic_ops_golang/api"
+)
+
+func DeleteName(db *sql.DB) http.HandlerFunc {
+	return func(w http.ResponseWriter, r *http.Request) {
+		params, _, userErr, sysErr, errCode := api.AllParams(r, nil)
+		if userErr != nil || sysErr != nil {
+			api.HandleErr(w, r, errCode, userErr, sysErr)
+			return
+		}
+		cdnName := tc.CDNName(params["name"])
+		if ok, err := cdnExists(db, cdnName); err != nil {
+			api.HandleErr(w, r, http.StatusInternalServerError, nil, errors.New("checking CDN existence: "+err.Error()))
+			return
+		} else if !ok {
+			api.HandleErr(w, r, http.StatusNotFound, nil, nil)
+			return
+		}
+		if ok, err := cdnUnused(db, cdnName); err != nil {
+			api.HandleErr(w, r, http.StatusInternalServerError, nil, errors.New("checking CDN usage: "+err.Error()))
+			return
+		} else if !ok {
+			api.HandleErr(w, r, http.StatusBadRequest, errors.New("Failed to delete cdn name = "+string(cdnName)+" has delivery services or servers"), nil)
+			return
+		}
+		if err := deleteCDNByName(db, tc.CDNName(cdnName)); err != nil {
+			api.HandleErr(w, r, http.StatusInternalServerError, nil, errors.New("deleting CDN: "+err.Error()))
+			return
+		}
+		api.WriteRespAlert(w, r, tc.SuccessLevel, "cdn was deleted.")
+	}
+}
+
+func deleteCDNByName(db *sql.DB, name tc.CDNName) error {
+	if _, err := db.Exec(`DELETE FROM cdn WHERE name = $1`, name); err != nil {
+		return errors.New("deleting cdns: " + err.Error())
+	}
+	return nil
+}
+
+func cdnExists(db *sql.DB, name tc.CDNName) (bool, error) {
+	id := 0
+	if err := db.QueryRow(`SELECT id FROM cdn WHERE name = $1`, name).Scan(&id); err != nil {
+		if err == sql.ErrNoRows {
+			return false, nil
+		}
+		return false, errors.New("querying cdn existence: " + err.Error())
+	}
+	return true, nil
+}
+
+func cdnUnused(db *sql.DB, name tc.CDNName) (bool, error) {
+	useCount := 0
+	if err := db.QueryRow(`
+WITH cdn_id as (
+  SELECT id as v FROM cdn WHERE name = $1
+)
+SELECT
+  (SELECT COUNT(*) FROM server WHERE server.cdn_id = (select v from cdn_id)) +
+	(SELECT COUNT(*) FROM deliveryservice WHERE deliveryservice.cdn_id = (select v from cdn_id))
+`, name).Scan(&useCount); err != nil {
+		return false, errors.New("querying cdn use count: " + err.Error())
+	}
+	if useCount > 0 {
+		return false, nil
+	}
+	return true, nil
+}
diff --git a/traffic_ops/traffic_ops_golang/routes.go b/traffic_ops/traffic_ops_golang/routes.go
index 83f1102..d8a76c8 100644
--- a/traffic_ops/traffic_ops_golang/routes.go
+++ b/traffic_ops/traffic_ops_golang/routes.go
@@ -110,6 +110,8 @@ func Routes(d ServerData) ([]Route, []RawRoute, http.Handler, error) {
 		{1.1, http.MethodPost, `cdns/?$`, api.CreateHandler(cdn.GetRefType(), d.DB), auth.PrivLevelOperations, Authenticated, nil},
 		{1.1, http.MethodDelete, `cdns/{id}$`, api.DeleteHandler(cdn.GetRefType(), d.DB), auth.PrivLevelOperations, Authenticated, nil},
 
+		{1.1, http.MethodDelete, `cdns/name/{name}$`, cdn.DeleteName(d.DB.DB), auth.PrivLevelOperations, Authenticated, nil},
+
 		//CDN: Monitoring: Traffic Monitor
 		{1.1, http.MethodGet, `cdns/{name}/configs/monitoring(\.json)?$`, monitoringHandler(d.DB), auth.PrivLevelReadOnly, Authenticated, nil},
 

-- 
To stop receiving notification emails like this one, please contact
mitchell852@apache.org.