<commit_before>//go:build linux && cgo && !agent

package db

import (
	"database/sql"
	"fmt"
	"net/http"

	"github.com/lxc/lxd/lxd/db/cluster"
	"github.com/lxc/lxd/lxd/db/query"
	"github.com/lxc/lxd/shared/api"
	"github.com/lxc/lxd/shared/logger"
	"github.com/lxc/lxd/shared/version"
)

// ClusterGroup is a value object holding db-related details about a cluster group.
type ClusterGroup struct {
	ID          int
	Name        string
	Description string
	Nodes       []string
}

// ClusterGroupFilter specifies potential query parameter fields.
type ClusterGroupFilter struct {
	ID   *int
	Name *string
}

var clusterGroupObjects = cluster.RegisterStmt(`
SELECT cluster_groups.id, cluster_groups.name, coalesce(cluster_groups.description, '')
  FROM cluster_groups
  ORDER BY cluster_groups.name
`)

var clusterGroupObjectsByName = cluster.RegisterStmt(`
SELECT cluster_groups.id, cluster_groups.name, coalesce(cluster_groups.description, '')
  FROM cluster_groups
  WHERE cluster_groups.name = ? ORDER BY cluster_groups.name
`)

var clusterGroupCreate = cluster.RegisterStmt(`
INSERT INTO cluster_groups (name, description)
  VALUES (?, ?)
`)

var clusterGroupID = cluster.RegisterStmt(`
SELECT cluster_groups.id FROM cluster_groups
  WHERE cluster_groups.name = ?
`)

var clusterGroupRename = cluster.RegisterStmt(`
UPDATE cluster_groups SET name = ? WHERE name = ?
`)

var clusterGroupDeleteByName = cluster.RegisterStmt(`
DELETE FROM cluster_groups WHERE name = ?
`)

var clusterGroupUpdate = cluster.RegisterStmt(`
UPDATE cluster_groups
  SET name = ?, description = ?
 WHERE id = ?
`)

var clusterGroupDeleteNodesRef = cluster.RegisterStmt(`
DELETE FROM nodes_cluster_groups WHERE group_id = ?
`)

// GetClusterGroups returns all available ClusterGroups.
// generator: ClusterGroup GetMany
func (c *ClusterTx) GetClusterGroups(filter ClusterGroupFilter) ([]ClusterGroup, error) {
	// Result slice.
	objects := make([]ClusterGroup, 0)

	// Pick the prepared statement and arguments to use based on active criteria.
	var stmt *sql.Stmt
	var args []any

	if filter.Name != nil && filter.ID == nil {
		stmt = cluster.Stmt(c.tx, clusterGroupObjectsByName)
		args = []any{
			filter.Name,
		}
	} else if filter.ID == nil && filter.Name == nil {
		stmt = cluster.Stmt(c.tx, clusterGroupObjects)
		args = []any{}
	} else {
		return nil, fmt.Errorf("No statement exists for the given Filter")
	}

	// Dest function for scanning a row.
	dest := func(i int) []any {
		objects = append(objects, ClusterGroup{})
		return []any{
			&objects[i].ID,
			&objects[i].Name,
			&objects[i].Description,
		}
	}

	// Select.
	err := query.SelectObjects(stmt, dest, args...)
	if err != nil {
		return nil, fmt.Errorf("Failed to fetch cluster groups: %w", err)
	}

	// Get nodes in cluster group.
	for i := 0; i < len(objects); i++ {
		objects[i].Nodes, err = c.GetClusterGroupNodes(objects[i].Name)
		if err != nil {
			return nil, err
		}
	}

	return objects, nil
}

// GetClusterGroup returns the ClusterGroup with the given key.
// generator: ClusterGroup GetOne
func (c *ClusterTx) GetClusterGroup(name string) (*ClusterGroup, error) {
	filter := ClusterGroupFilter{}
	filter.Name = &name

	objects, err := c.GetClusterGroups(filter)
	if err != nil {
		return nil, fmt.Errorf("Failed to fetch cluster group: %w", err)
	}

	switch len(objects) {
	case 0:
		return nil, api.StatusErrorf(http.StatusNotFound, "Cluster group not found")
	case 1:
		return &objects[0], nil
	default:
		return nil, fmt.Errorf("More than one cluster group matches")
	}
}

// GetClusterGroupID return the ID of the ClusterGroup with the given key.
// generator: ClusterGroup ID
func (c *ClusterTx) GetClusterGroupID(name string) (int64, error) {
	stmt := cluster.Stmt(c.tx, clusterGroupID)
	rows, err := stmt.Query(name)
	if err != nil {
		return -1, fmt.Errorf("Failed to get cluster group ID: %w", err)
	}

	defer func() { _ = rows.Close() }()

	// Ensure we read one and only one row.
	if !rows.Next() {
		return -1, api.StatusErrorf(http.StatusNotFound, "Cluster group not found")
	}

	var id int64
	err = rows.Scan(&id)
	if err != nil {
		return -1, fmt.Errorf("Failed to scan ID: %w", err)
	}

	if rows.Next() {
		return -1, fmt.Errorf("More than one row returned")
	}

	err = rows.Err()
	if err != nil {
		return -1, fmt.Errorf("Result set failure: %w", err)
	}

	return id, nil
}

// ClusterGroupExists checks if a ClusterGroup with the given key exists.
// generator: ClusterGroup Exists
func (c *ClusterTx) ClusterGroupExists(name string) (bool, error) {
	_, err := c.GetClusterGroupID(name)
	if err != nil {
		if api.StatusErrorCheck(err, http.StatusNotFound) {
			return false, nil
		}

		return false, err
	}

	return true, nil
}

// CreateClusterGroup adds a new ClusterGroup to the database.
// generator: ClusterGroup Create
func (c *ClusterTx) CreateClusterGroup(object ClusterGroup) (int64, error) {
	// Check if a ClusterGroup with the same key exists.
	exists, err := c.ClusterGroupExists(object.Name)
	if err != nil {
		return -1, fmt.Errorf("Failed to check for duplicates: %w", err)
	}

	if exists {
		return -1, fmt.Errorf("This cluster group already exists")
	}

	args := make([]any, 2)

	// Populate the statement arguments.
	args[0] = object.Name
	args[1] = object.Description

	// Prepared statement to use.
	stmt := cluster.Stmt(c.tx, clusterGroupCreate)

	// Execute the statement.
	result, err := stmt.Exec(args...)
	if err != nil {
		return -1, fmt.Errorf("Failed to create cluster group: %w", err)
	}

	id, err := result.LastInsertId()
	if err != nil {
		return -1, fmt.Errorf("Failed to fetch cluster group ID: %w", err)
	}

	// Insert nodes reference.
	err = addNodesToClusterGroup(c.tx, int(id), object.Nodes)
	if err != nil {
		return -1, fmt.Errorf("Insert nodes for cluster group: %w", err)
	}

	return id, nil
}

// RenameClusterGroup renames the ClusterGroup matching the given key parameters.
// generator: ClusterGroup Rename
func (c *ClusterTx) RenameClusterGroup(name string, to string) error {
	stmt := cluster.Stmt(c.tx, clusterGroupRename)
	result, err := stmt.Exec(to, name)
	if err != nil {
		return fmt.Errorf("Failed to rename cluster group: %w", err)
	}

	n, err := result.RowsAffected()
	if err != nil {
		return fmt.Errorf("Fetch affected rows: %w", err)
	}

	if n != 1 {
		return fmt.Errorf("Query affected %d rows instead of 1", n)
	}

	return nil
}

// DeleteClusterGroup deletes the ClusterGroup matching the given key parameters.
// generator: ClusterGroup DeleteOne-by-Name
func (c *ClusterTx) DeleteClusterGroup(name string) error {
	stmt := cluster.Stmt(c.tx, clusterGroupDeleteByName)
	result, err := stmt.Exec(name)
	if err != nil {
		return fmt.Errorf("Failed to delete cluster group: %w", err)
	}

	n, err := result.RowsAffected()
	if err != nil {
		return fmt.Errorf("Fetch affected rows: %w", err)
	}

	if n != 1 {
		return fmt.Errorf("Query deleted %d rows instead of 1", n)
	}

	return nil
}

// UpdateClusterGroup updates the ClusterGroup matching the given key parameters.
// generator: ClusterGroup Update
func (c *ClusterTx) UpdateClusterGroup(name string, object ClusterGroup) error {
	id, err := c.GetClusterGroupID(name)
	if err != nil {
		return fmt.Errorf("Failed to get cluster group: %w", err)
	}

	stmt := cluster.Stmt(c.tx, clusterGroupUpdate)
	result, err := stmt.Exec(object.Name, object.Description, id)
	if err != nil {
		return fmt.Errorf("Failed to update cluster group: %w", err)
	}

	n, err := result.RowsAffected()
	if err != nil {
		return fmt.Errorf("Fetch affected rows: %w", err)
	}

	if n != 1 {
		return fmt.Errorf("Query updated %d rows instead of 1", n)
	}

	// Delete current nodes.
	stmt = cluster.Stmt(c.tx, clusterGroupDeleteNodesRef)
	_, err = stmt.Exec(id)
	if err != nil {
		return fmt.Errorf("Failed to delete current nodes: %w", err)
	}

	// Insert nodes reference.
	err = addNodesToClusterGroup(c.tx, int(id), object.Nodes)
	if err != nil {
		return fmt.Errorf("Failed to insert nodes for cluster group: %w", err)
	}

	return nil
}

// ClusterGroupToAPI is a convenience to convert a ClusterGroup db struct into
// an API cluster group struct.
func ClusterGroupToAPI(clusterGroup *ClusterGroup, nodes []string) *api.ClusterGroup {
	c := &api.ClusterGroup{
		ClusterGroupPut: api.ClusterGroupPut{
			Description: clusterGroup.Description,
			Members:     nodes,
		},
		ClusterGroupPost: api.ClusterGroupPost{
			Name: clusterGroup.Name,
		},
	}

	return c
}

// GetClusterGroupNodes returns a list of nodes of the given cluster group.
func (c *ClusterTx) GetClusterGroupNodes(groupName string) ([]string, error) {
	q := `SELECT nodes.name FROM nodes_cluster_groups
JOIN nodes ON nodes.id = nodes_cluster_groups.node_id
JOIN cluster_groups ON cluster_groups.id = nodes_cluster_groups.group_id
WHERE cluster_groups.name = ?`

	return query.SelectStrings(c.tx, q, groupName)
}

// GetClusterGroupURIs returns all available ClusterGroup URIs.
// generator: ClusterGroup URIs
func (c *ClusterTx) GetClusterGroupURIs(filter ClusterGroupFilter) ([]string, error) {
	var args []any
	var sql string
	if filter.Name != nil && filter.ID == nil {
		sql = `SELECT cluster_groups.name FROM cluster_groups
WHERE cluster_groups.name = ? ORDER BY cluster_groups.name
`
		args = []any{
			filter.Name,
		}
	} else if filter.ID == nil && filter.Name == nil {
		sql = `SELECT cluster_groups.name FROM cluster_groups ORDER BY cluster_groups.name`
		args = []any{}
	} else {
		return nil, fmt.Errorf("No statement exists for the given Filter")
	}

	names, err := query.SelectStrings(c.tx, sql, args...)
	if err != nil {
		return nil, err
	}

	uris := make([]string, len(names))
	for i, name := range names {
		uris[i] = api.NewURL().Path(version.APIVersion, "cluster/groups", name).String()
	}

	return uris, nil
}

//AddNodeToClusterGroup adds a given node to the given cluster group.
func (c *ClusterTx) AddNodeToClusterGroup(groupName string, nodeName string) error {
	groupID, err := c.GetClusterGroupID(groupName)
	if err != nil {
		return fmt.Errorf("Failed to get cluster group ID: %w", err)
	}

	nodeInfo, err := c.GetNodeByName(nodeName)
	if err != nil {
		return fmt.Errorf("Failed to get node info: %w", err)
	}

	q := `INSERT INTO nodes_cluster_groups (node_id, group_id) VALUES(?, ?);`

	stmt, err := c.prepare(q)
	if err != nil {
		return err
	}

	_, err = stmt.Exec(nodeInfo.ID, groupID)
	if err != nil {
		return err
	}

	return nil
}

// RemoveNodeFromClusterGroup removes a given node from the given group name.
func (c *ClusterTx) RemoveNodeFromClusterGroup(groupName string, nodeName string) error {
	groupID, err := c.GetClusterGroupID(groupName)
	if err != nil {
		return fmt.Errorf("Failed to get cluster group ID: %w", err)
	}

	nodeInfo, err := c.GetNodeByName(nodeName)
	if err != nil {
		return fmt.Errorf("Failed to get node info: %w", err)
	}

	q := `DELETE FROM nodes_cluster_groups WHERE node_id = ? AND group_id = ?`

	stmt, err := c.prepare(q)
	if err != nil {
		return err
	}

	_, err = stmt.Exec(nodeInfo.ID, groupID)
	if err != nil {
		return err
	}

	return nil
}

//GetClusterGroupsWithNode returns a list of cluster group names the given node belongs to.
func (c *ClusterTx) GetClusterGroupsWithNode(nodeName string) ([]string, error) {
	q := `SELECT cluster_groups.name FROM nodes_cluster_groups
JOIN cluster_groups ON cluster_groups.id = nodes_cluster_groups.group_id
JOIN nodes ON nodes.id = nodes_cluster_groups.node_id
WHERE nodes.name = ?`

	return query.SelectStrings(c.tx, q, nodeName)
}

// ToAPI returns a LXD API entry.
func (c *ClusterGroup) ToAPI() (*api.ClusterGroup, error) {
	result := api.ClusterGroup{
		ClusterGroupPut: api.ClusterGroupPut{
			Description: c.Description,
			Members:     c.Nodes,
		},
		ClusterGroupPost: api.ClusterGroupPost{
			Name: c.Name,
		},
	}

	return &result, nil
}

// addNodesToClusterGroup adds the given nodes the the cluster group with the given ID.
func addNodesToClusterGroup(tx *sql.Tx, id int, nodes []string) error {
	str := `
INSERT INTO nodes_cluster_groups (group_id, node_id)
  VALUES (
    ?,
    (SELECT nodes.id
     FROM nodes
     WHERE nodes.name = ?)
  )`
	stmt, err := tx.Prepare(str)
	if err != nil {
		return err
	}

	defer func() { _ = stmt.Close() }()

	for _, node := range nodes {
		_, err = stmt.Exec(id, node)
		if err != nil {
			logger.Debugf("Error adding node %q to cluster group: %s", node, err)
			return err
		}
	}

	return nil
}
<commit_msg>lxd/db/cluster: Don't use prepared statements in RemoveNodeFromClusterGroup and AddNodeToClusterGroup<commit_after>//go:build linux && cgo && !agent

package db

import (
	"database/sql"
	"fmt"
	"net/http"

	"github.com/lxc/lxd/lxd/db/cluster"
	"github.com/lxc/lxd/lxd/db/query"
	"github.com/lxc/lxd/shared/api"
	"github.com/lxc/lxd/shared/logger"
	"github.com/lxc/lxd/shared/version"
)

// ClusterGroup is a value object holding db-related details about a cluster group.
type ClusterGroup struct {
	ID          int
	Name        string
	Description string
	Nodes       []string
}

// ClusterGroupFilter specifies potential query parameter fields.
type ClusterGroupFilter struct {
	ID   *int
	Name *string
}

var clusterGroupObjects = cluster.RegisterStmt(`
SELECT cluster_groups.id, cluster_groups.name, coalesce(cluster_groups.description, '')
  FROM cluster_groups
  ORDER BY cluster_groups.name
`)

var clusterGroupObjectsByName = cluster.RegisterStmt(`
SELECT cluster_groups.id, cluster_groups.name, coalesce(cluster_groups.description, '')
  FROM cluster_groups
  WHERE cluster_groups.name = ? ORDER BY cluster_groups.name
`)

var clusterGroupCreate = cluster.RegisterStmt(`
INSERT INTO cluster_groups (name, description)
  VALUES (?, ?)
`)

var clusterGroupID = cluster.RegisterStmt(`
SELECT cluster_groups.id FROM cluster_groups
  WHERE cluster_groups.name = ?
`)

var clusterGroupRename = cluster.RegisterStmt(`
UPDATE cluster_groups SET name = ? WHERE name = ?
`)

var clusterGroupDeleteByName = cluster.RegisterStmt(`
DELETE FROM cluster_groups WHERE name = ?
`)

var clusterGroupUpdate = cluster.RegisterStmt(`
UPDATE cluster_groups
  SET name = ?, description = ?
 WHERE id = ?
`)

var clusterGroupDeleteNodesRef = cluster.RegisterStmt(`
DELETE FROM nodes_cluster_groups WHERE group_id = ?
`)

// GetClusterGroups returns all available ClusterGroups.
// generator: ClusterGroup GetMany
func (c *ClusterTx) GetClusterGroups(filter ClusterGroupFilter) ([]ClusterGroup, error) {
	// Result slice.
	objects := make([]ClusterGroup, 0)

	// Pick the prepared statement and arguments to use based on active criteria.
	var stmt *sql.Stmt
	var args []any

	if filter.Name != nil && filter.ID == nil {
		stmt = cluster.Stmt(c.tx, clusterGroupObjectsByName)
		args = []any{
			filter.Name,
		}
	} else if filter.ID == nil && filter.Name == nil {
		stmt = cluster.Stmt(c.tx, clusterGroupObjects)
		args = []any{}
	} else {
		return nil, fmt.Errorf("No statement exists for the given Filter")
	}

	// Dest function for scanning a row.
	dest := func(i int) []any {
		objects = append(objects, ClusterGroup{})
		return []any{
			&objects[i].ID,
			&objects[i].Name,
			&objects[i].Description,
		}
	}

	// Select.
	err := query.SelectObjects(stmt, dest, args...)
	if err != nil {
		return nil, fmt.Errorf("Failed to fetch cluster groups: %w", err)
	}

	// Get nodes in cluster group.
	for i := 0; i < len(objects); i++ {
		objects[i].Nodes, err = c.GetClusterGroupNodes(objects[i].Name)
		if err != nil {
			return nil, err
		}
	}

	return objects, nil
}

// GetClusterGroup returns the ClusterGroup with the given key.
// generator: ClusterGroup GetOne
func (c *ClusterTx) GetClusterGroup(name string) (*ClusterGroup, error) {
	filter := ClusterGroupFilter{}
	filter.Name = &name

	objects, err := c.GetClusterGroups(filter)
	if err != nil {
		return nil, fmt.Errorf("Failed to fetch cluster group: %w", err)
	}

	switch len(objects) {
	case 0:
		return nil, api.StatusErrorf(http.StatusNotFound, "Cluster group not found")
	case 1:
		return &objects[0], nil
	default:
		return nil, fmt.Errorf("More than one cluster group matches")
	}
}

// GetClusterGroupID return the ID of the ClusterGroup with the given key.
// generator: ClusterGroup ID
func (c *ClusterTx) GetClusterGroupID(name string) (int64, error) {
	stmt := cluster.Stmt(c.tx, clusterGroupID)
	rows, err := stmt.Query(name)
	if err != nil {
		return -1, fmt.Errorf("Failed to get cluster group ID: %w", err)
	}

	defer func() { _ = rows.Close() }()

	// Ensure we read one and only one row.
	if !rows.Next() {
		return -1, api.StatusErrorf(http.StatusNotFound, "Cluster group not found")
	}

	var id int64
	err = rows.Scan(&id)
	if err != nil {
		return -1, fmt.Errorf("Failed to scan ID: %w", err)
	}

	if rows.Next() {
		return -1, fmt.Errorf("More than one row returned")
	}

	err = rows.Err()
	if err != nil {
		return -1, fmt.Errorf("Result set failure: %w", err)
	}

	return id, nil
}

// ClusterGroupExists checks if a ClusterGroup with the given key exists.
// generator: ClusterGroup Exists
func (c *ClusterTx) ClusterGroupExists(name string) (bool, error) {
	_, err := c.GetClusterGroupID(name)
	if err != nil {
		if api.StatusErrorCheck(err, http.StatusNotFound) {
			return false, nil
		}

		return false, err
	}

	return true, nil
}

// CreateClusterGroup adds a new ClusterGroup to the database.
// generator: ClusterGroup Create
func (c *ClusterTx) CreateClusterGroup(object ClusterGroup) (int64, error) {
	// Check if a ClusterGroup with the same key exists.
	exists, err := c.ClusterGroupExists(object.Name)
	if err != nil {
		return -1, fmt.Errorf("Failed to check for duplicates: %w", err)
	}

	if exists {
		return -1, fmt.Errorf("This cluster group already exists")
	}

	args := make([]any, 2)

	// Populate the statement arguments.
	args[0] = object.Name
	args[1] = object.Description

	// Prepared statement to use.
	stmt := cluster.Stmt(c.tx, clusterGroupCreate)

	// Execute the statement.
	result, err := stmt.Exec(args...)
	if err != nil {
		return -1, fmt.Errorf("Failed to create cluster group: %w", err)
	}

	id, err := result.LastInsertId()
	if err != nil {
		return -1, fmt.Errorf("Failed to fetch cluster group ID: %w", err)
	}

	// Insert nodes reference.
	err = addNodesToClusterGroup(c.tx, int(id), object.Nodes)
	if err != nil {
		return -1, fmt.Errorf("Insert nodes for cluster group: %w", err)
	}

	return id, nil
}

// RenameClusterGroup renames the ClusterGroup matching the given key parameters.
// generator: ClusterGroup Rename
func (c *ClusterTx) RenameClusterGroup(name string, to string) error {
	stmt := cluster.Stmt(c.tx, clusterGroupRename)
	result, err := stmt.Exec(to, name)
	if err != nil {
		return fmt.Errorf("Failed to rename cluster group: %w", err)
	}

	n, err := result.RowsAffected()
	if err != nil {
		return fmt.Errorf("Fetch affected rows: %w", err)
	}

	if n != 1 {
		return fmt.Errorf("Query affected %d rows instead of 1", n)
	}

	return nil
}

// DeleteClusterGroup deletes the ClusterGroup matching the given key parameters.
// generator: ClusterGroup DeleteOne-by-Name
func (c *ClusterTx) DeleteClusterGroup(name string) error {
	stmt := cluster.Stmt(c.tx, clusterGroupDeleteByName)
	result, err := stmt.Exec(name)
	if err != nil {
		return fmt.Errorf("Failed to delete cluster group: %w", err)
	}

	n, err := result.RowsAffected()
	if err != nil {
		return fmt.Errorf("Fetch affected rows: %w", err)
	}

	if n != 1 {
		return fmt.Errorf("Query deleted %d rows instead of 1", n)
	}

	return nil
}

// UpdateClusterGroup updates the ClusterGroup matching the given key parameters.
// generator: ClusterGroup Update
func (c *ClusterTx) UpdateClusterGroup(name string, object ClusterGroup) error {
	id, err := c.GetClusterGroupID(name)
	if err != nil {
		return fmt.Errorf("Failed to get cluster group: %w", err)
	}

	stmt := cluster.Stmt(c.tx, clusterGroupUpdate)
	result, err := stmt.Exec(object.Name, object.Description, id)
	if err != nil {
		return fmt.Errorf("Failed to update cluster group: %w", err)
	}

	n, err := result.RowsAffected()
	if err != nil {
		return fmt.Errorf("Fetch affected rows: %w", err)
	}

	if n != 1 {
		return fmt.Errorf("Query updated %d rows instead of 1", n)
	}

	// Delete current nodes.
	stmt = cluster.Stmt(c.tx, clusterGroupDeleteNodesRef)
	_, err = stmt.Exec(id)
	if err != nil {
		return fmt.Errorf("Failed to delete current nodes: %w", err)
	}

	// Insert nodes reference.
	err = addNodesToClusterGroup(c.tx, int(id), object.Nodes)
	if err != nil {
		return fmt.Errorf("Failed to insert nodes for cluster group: %w", err)
	}

	return nil
}

// ClusterGroupToAPI is a convenience to convert a ClusterGroup db struct into
// an API cluster group struct.
func ClusterGroupToAPI(clusterGroup *ClusterGroup, nodes []string) *api.ClusterGroup {
	c := &api.ClusterGroup{
		ClusterGroupPut: api.ClusterGroupPut{
			Description: clusterGroup.Description,
			Members:     nodes,
		},
		ClusterGroupPost: api.ClusterGroupPost{
			Name: clusterGroup.Name,
		},
	}

	return c
}

// GetClusterGroupNodes returns a list of nodes of the given cluster group.
func (c *ClusterTx) GetClusterGroupNodes(groupName string) ([]string, error) {
	q := `SELECT nodes.name FROM nodes_cluster_groups
JOIN nodes ON nodes.id = nodes_cluster_groups.node_id
JOIN cluster_groups ON cluster_groups.id = nodes_cluster_groups.group_id
WHERE cluster_groups.name = ?`

	return query.SelectStrings(c.tx, q, groupName)
}

// GetClusterGroupURIs returns all available ClusterGroup URIs.
// generator: ClusterGroup URIs
func (c *ClusterTx) GetClusterGroupURIs(filter ClusterGroupFilter) ([]string, error) {
	var args []any
	var sql string
	if filter.Name != nil && filter.ID == nil {
		sql = `SELECT cluster_groups.name FROM cluster_groups
WHERE cluster_groups.name = ? ORDER BY cluster_groups.name
`
		args = []any{
			filter.Name,
		}
	} else if filter.ID == nil && filter.Name == nil {
		sql = `SELECT cluster_groups.name FROM cluster_groups ORDER BY cluster_groups.name`
		args = []any{}
	} else {
		return nil, fmt.Errorf("No statement exists for the given Filter")
	}

	names, err := query.SelectStrings(c.tx, sql, args...)
	if err != nil {
		return nil, err
	}

	uris := make([]string, len(names))
	for i, name := range names {
		uris[i] = api.NewURL().Path(version.APIVersion, "cluster/groups", name).String()
	}

	return uris, nil
}

//AddNodeToClusterGroup adds a given node to the given cluster group.
func (c *ClusterTx) AddNodeToClusterGroup(groupName string, nodeName string) error {
	groupID, err := c.GetClusterGroupID(groupName)
	if err != nil {
		return fmt.Errorf("Failed to get cluster group ID: %w", err)
	}

	nodeInfo, err := c.GetNodeByName(nodeName)
	if err != nil {
		return fmt.Errorf("Failed to get node info: %w", err)
	}

	_, err = c.tx.Exec(`INSERT INTO nodes_cluster_groups (node_id, group_id) VALUES(?, ?);`, nodeInfo.ID, groupID)
	if err != nil {
		return err
	}

	return nil
}

// RemoveNodeFromClusterGroup removes a given node from the given group name.
func (c *ClusterTx) RemoveNodeFromClusterGroup(groupName string, nodeName string) error {
	groupID, err := c.GetClusterGroupID(groupName)
	if err != nil {
		return fmt.Errorf("Failed to get cluster group ID: %w", err)
	}

	nodeInfo, err := c.GetNodeByName(nodeName)
	if err != nil {
		return fmt.Errorf("Failed to get node info: %w", err)
	}

	_, err = c.tx.Exec(`DELETE FROM nodes_cluster_groups WHERE node_id = ? AND group_id = ?`, nodeInfo.ID, groupID)
	if err != nil {
		return err
	}

	return nil
}

//GetClusterGroupsWithNode returns a list of cluster group names the given node belongs to.
func (c *ClusterTx) GetClusterGroupsWithNode(nodeName string) ([]string, error) {
	q := `SELECT cluster_groups.name FROM nodes_cluster_groups
JOIN cluster_groups ON cluster_groups.id = nodes_cluster_groups.group_id
JOIN nodes ON nodes.id = nodes_cluster_groups.node_id
WHERE nodes.name = ?`

	return query.SelectStrings(c.tx, q, nodeName)
}

// ToAPI returns a LXD API entry.
func (c *ClusterGroup) ToAPI() (*api.ClusterGroup, error) {
	result := api.ClusterGroup{
		ClusterGroupPut: api.ClusterGroupPut{
			Description: c.Description,
			Members:     c.Nodes,
		},
		ClusterGroupPost: api.ClusterGroupPost{
			Name: c.Name,
		},
	}

	return &result, nil
}

// addNodesToClusterGroup adds the given nodes the the cluster group with the given ID.
func addNodesToClusterGroup(tx *sql.Tx, id int, nodes []string) error {
	str := `
INSERT INTO nodes_cluster_groups (group_id, node_id)
  VALUES (
    ?,
    (SELECT nodes.id
     FROM nodes
     WHERE nodes.name = ?)
  )`
	stmt, err := tx.Prepare(str)
	if err != nil {
		return err
	}

	defer func() { _ = stmt.Close() }()

	for _, node := range nodes {
		_, err = stmt.Exec(id, node)
		if err != nil {
			logger.Debugf("Error adding node %q to cluster group: %s", node, err)
			return err
		}
	}

	return nil
}
<|endoftext|>


<commit_before>package oauth2

import (
	"strings"

	"github.com/hellofresh/janus/pkg/jwt"
	log "github.com/sirupsen/logrus"
)

const (
	// JWT provides a way to check the `exp` field on the JWT and make sure the token is still valid. This is
	// probably the most versatile way to check for tokens, since it doesn't require any storage or extra calls in
	// each request.
	JWT ManagerType = iota
	// Introspection strategy makes sure to validate the provided token on every request against the authentication provider.
	Introspection
)

var typesMap = map[string]ManagerType{
	"jwt":           JWT,
	"introspection": Introspection,
}

// ParseType takes a string type and returns the Manager type constant.
func ParseType(lvl string) (ManagerType, error) {
	m, ok := typesMap[strings.ToLower(lvl)]
	if !ok {
		var m ManagerType
		return m, ErrUnknownStrategy
	}
	return m, nil
}

// ManagerType type
type ManagerType uint8

// Manager holds the methods to handle tokens
type Manager interface {
	IsKeyAuthorized(accessToken string) bool
}

// ManagerFactory is used for creating a new manager
type ManagerFactory struct {
	oAuthServer *OAuth
}

// NewManagerFactory creates a new instance of ManagerFactory
func NewManagerFactory(oAuthServer *OAuth) *ManagerFactory {
	return &ManagerFactory{oAuthServer}
}

// Build creates a manager based on the type
func (f *ManagerFactory) Build(t ManagerType) (Manager, error) {
	// FIXME: make it nicer with BiMap - GetByType, GetByName
	typesMapReversed := make(map[ManagerType]string, len(typesMap))
	for k, v := range typesMap {
		typesMapReversed[v] = k
	}

	log.WithField("name", typesMapReversed[t]).
		Debug("Building token strategy")

	switch t {
	case JWT:
		signingMethods, err := f.oAuthServer.TokenStrategy.GetJWTSigningMethods()
		if nil != err {
			return nil, err
		}

		return NewJWTManager(jwt.NewParser(jwt.NewParserConfig(signingMethods...))), nil
	case Introspection:
		settings, err := f.oAuthServer.TokenStrategy.GetIntrospectionSettings()
		if nil != err {
			return nil, err
		}

		manager, err := NewIntrospectionManager(f.oAuthServer.Endpoints.Introspect.UpstreamURL, settings)
		if err != nil {
			return nil, err
		}

		return manager, nil
	}

	return nil, ErrUnknownManager
}
<commit_msg>KeyAuthorized now accepts a context<commit_after>package oauth2

import (
	"context"
	"strings"

	"github.com/hellofresh/janus/pkg/jwt"
	log "github.com/sirupsen/logrus"
)

const (
	// JWT provides a way to check the `exp` field on the JWT and make sure the token is still valid. This is
	// probably the most versatile way to check for tokens, since it doesn't require any storage or extra calls in
	// each request.
	JWT ManagerType = iota
	// Introspection strategy makes sure to validate the provided token on every request against the authentication provider.
	Introspection
)

var typesMap = map[string]ManagerType{
	"jwt":           JWT,
	"introspection": Introspection,
}

// ParseType takes a string type and returns the Manager type constant.
func ParseType(lvl string) (ManagerType, error) {
	m, ok := typesMap[strings.ToLower(lvl)]
	if !ok {
		var m ManagerType
		return m, ErrUnknownStrategy
	}
	return m, nil
}

// ManagerType type
type ManagerType uint8

// Manager holds the methods to handle tokens
type Manager interface {
	IsKeyAuthorized(ctx context.Context, accessToken string) bool
}

// ManagerFactory is used for creating a new manager
type ManagerFactory struct {
	oAuthServer *OAuth
}

// NewManagerFactory creates a new instance of ManagerFactory
func NewManagerFactory(oAuthServer *OAuth) *ManagerFactory {
	return &ManagerFactory{oAuthServer}
}

// Build creates a manager based on the type
func (f *ManagerFactory) Build(t ManagerType) (Manager, error) {
	// FIXME: make it nicer with BiMap - GetByType, GetByName
	typesMapReversed := make(map[ManagerType]string, len(typesMap))
	for k, v := range typesMap {
		typesMapReversed[v] = k
	}

	log.WithField("name", typesMapReversed[t]).
		Debug("Building token strategy")

	switch t {
	case JWT:
		signingMethods, err := f.oAuthServer.TokenStrategy.GetJWTSigningMethods()
		if nil != err {
			return nil, err
		}

		return NewJWTManager(jwt.NewParser(jwt.NewParserConfig(signingMethods...))), nil
	case Introspection:
		settings, err := f.oAuthServer.TokenStrategy.GetIntrospectionSettings()
		if nil != err {
			return nil, err
		}

		manager, err := NewIntrospectionManager(f.oAuthServer.Endpoints.Introspect.UpstreamURL, settings)
		if err != nil {
			return nil, err
		}

		return manager, nil
	}

	return nil, ErrUnknownManager
}
<|endoftext|>


<commit_before><commit_msg>aio: Return EINVAL if the number of events is negative.<commit_after><|endoftext|>


<commit_before>package profilesvc

// The profilesvc is just over HTTP, so we just have a single transport.go.

import (
	"bytes"
	"encoding/json"
	"errors"
	"io/ioutil"
	"net/http"

	"net/url"

	"github.com/gorilla/mux"
	"golang.org/x/net/context"

	"github.com/go-kit/kit/log"
	httptransport "github.com/go-kit/kit/transport/http"
)

var (
	// ErrBadRouting is returned when an expected path variable is missing.
	// It always indicates programmer error.
	ErrBadRouting = errors.New("inconsistent mapping between route and handler (programmer error)")
)

// MakeHTTPHandler mounts all of the service endpoints into an http.Handler.
// Useful in a profilesvc server.
func MakeHTTPHandler(ctx context.Context, s Service, logger log.Logger) http.Handler {
	r := mux.NewRouter()
	e := MakeServerEndpoints(s)
	options := []httptransport.ServerOption{
		httptransport.ServerErrorLogger(logger),
		httptransport.ServerErrorEncoder(encodeError),
	}

	// POST    /profiles                           adds another profile
	// GET     /profiles/:id                       retrieves the given profile by id
	// PUT     /profiles/:id                       post updated profile information about the profile
	// PATCH   /profiles/:id                       partial updated profile information
	// DELETE  /profiles/:id                       remove the given profile
	// GET     /profiles/:id/addresses             retrieve addresses associated with the profile
	// GET     /profiles/:id/addresses/:addressID  retrieve a particular profile address
	// POST    /profiles/:id/addresses             add a new address
	// DELETE  /profiles/:id/addresses/:addressID  remove an address

	r.Methods("POST").Path("/profiles/").Handler(httptransport.NewServer(
		ctx,
		e.PostProfileEndpoint,
		decodePostProfileRequest,
		encodeResponse,
		options...,
	))
	r.Methods("GET").Path("/profiles/{id}").Handler(httptransport.NewServer(
		ctx,
		e.GetProfileEndpoint,
		decodeGetProfileRequest,
		encodeResponse,
		options...,
	))
	r.Methods("PUT").Path("/profiles/{id}").Handler(httptransport.NewServer(
		ctx,
		e.PutProfileEndpoint,
		decodePutProfileRequest,
		encodeResponse,
		options...,
	))
	r.Methods("PATCH").Path("/profiles/{id}").Handler(httptransport.NewServer(
		ctx,
		e.PatchProfileEndpoint,
		decodePatchProfileRequest,
		encodeResponse,
		options...,
	))
	r.Methods("DELETE").Path("/profiles/{id}").Handler(httptransport.NewServer(
		ctx,
		e.DeleteProfileEndpoint,
		decodeDeleteProfileRequest,
		encodeResponse,
		options...,
	))
	r.Methods("GET").Path("/profiles/{id}/addresses/").Handler(httptransport.NewServer(
		ctx,
		e.GetAddressesEndpoint,
		decodeGetAddressesRequest,
		encodeResponse,
		options...,
	))
	r.Methods("GET").Path("/profiles/{id}/addresses/{addressID}").Handler(httptransport.NewServer(
		ctx,
		e.GetAddressEndpoint,
		decodeGetAddressRequest,
		encodeResponse,
		options...,
	))
	r.Methods("POST").Path("/profiles/{id}/addresses/").Handler(httptransport.NewServer(
		ctx,
		e.PostAddressEndpoint,
		decodePostAddressRequest,
		encodeResponse,
		options...,
	))
	r.Methods("DELETE").Path("/profiles/{id}/addresses/{addressID}").Handler(httptransport.NewServer(
		ctx,
		e.DeleteAddressEndpoint,
		decodeDeleteAddressRequest,
		encodeResponse,
		options...,
	))
	return r
}

func decodePostProfileRequest(_ context.Context, r *http.Request) (request interface{}, err error) {
	var req postProfileRequest
	if e := json.NewDecoder(r.Body).Decode(&req.Profile); e != nil {
		return nil, e
	}
	return req, nil
}

func decodeGetProfileRequest(_ context.Context, r *http.Request) (request interface{}, err error) {
	vars := mux.Vars(r)
	id, ok := vars["id"]
	if !ok {
		return nil, ErrBadRouting
	}
	return getProfileRequest{ID: id}, nil
}

func decodePutProfileRequest(_ context.Context, r *http.Request) (request interface{}, err error) {
	vars := mux.Vars(r)
	id, ok := vars["id"]
	if !ok {
		return nil, ErrBadRouting
	}
	var profile Profile
	if err := json.NewDecoder(r.Body).Decode(&profile); err != nil {
		return nil, err
	}
	return putProfileRequest{
		ID:      id,
		Profile: profile,
	}, nil
}

func decodePatchProfileRequest(_ context.Context, r *http.Request) (request interface{}, err error) {
	vars := mux.Vars(r)
	id, ok := vars["id"]
	if !ok {
		return nil, ErrBadRouting
	}
	var profile Profile
	if err := json.NewDecoder(r.Body).Decode(&profile); err != nil {
		return nil, err
	}
	return patchProfileRequest{
		ID:      id,
		Profile: profile,
	}, nil
}

func decodeDeleteProfileRequest(_ context.Context, r *http.Request) (request interface{}, err error) {
	vars := mux.Vars(r)
	id, ok := vars["id"]
	if !ok {
		return nil, ErrBadRouting
	}
	return deleteProfileRequest{ID: id}, nil
}

func decodeGetAddressesRequest(_ context.Context, r *http.Request) (request interface{}, err error) {
	vars := mux.Vars(r)
	id, ok := vars["id"]
	if !ok {
		return nil, ErrBadRouting
	}
	return getAddressesRequest{ProfileID: id}, nil
}

func decodeGetAddressRequest(_ context.Context, r *http.Request) (request interface{}, err error) {
	vars := mux.Vars(r)
	id, ok := vars["id"]
	if !ok {
		return nil, ErrBadRouting
	}
	addressID, ok := vars["addressID"]
	if !ok {
		return nil, ErrBadRouting
	}
	return getAddressRequest{
		ProfileID: id,
		AddressID: addressID,
	}, nil
}

func decodePostAddressRequest(_ context.Context, r *http.Request) (request interface{}, err error) {
	vars := mux.Vars(r)
	id, ok := vars["id"]
	if !ok {
		return nil, ErrBadRouting
	}
	var address Address
	if err := json.NewDecoder(r.Body).Decode(&address); err != nil {
		return nil, err
	}
	return postAddressRequest{
		ProfileID: id,
		Address:   address,
	}, nil
}

func decodeDeleteAddressRequest(_ context.Context, r *http.Request) (request interface{}, err error) {
	vars := mux.Vars(r)
	id, ok := vars["id"]
	if !ok {
		return nil, ErrBadRouting
	}
	addressID, ok := vars["addressID"]
	if !ok {
		return nil, ErrBadRouting
	}
	return deleteAddressRequest{
		ProfileID: id,
		AddressID: addressID,
	}, nil
}

func encodePostProfileRequest(ctx context.Context, req *http.Request, request interface{}) error {
	// r.Methods("POST").Path("/profiles/")
	req.Method, req.URL.Path = "POST", "/profiles/"
	return encodeRequest(ctx, req, request)
}

func encodeGetProfileRequest(ctx context.Context, req *http.Request, request interface{}) error {
	// r.Methods("GET").Path("/profiles/{id}")
	r := request.(getProfileRequest)
	profileID := url.QueryEscape(r.ID)
	req.Method, req.URL.Path = "GET", "/profiles/"+profileID
	return encodeRequest(ctx, req, request)
}

func encodePutProfileRequest(ctx context.Context, req *http.Request, request interface{}) error {
	// r.Methods("PUT").Path("/profiles/{id}")
	r := request.(putProfileRequest)
	profileID := url.QueryEscape(r.ID)
	req.Method, req.URL.Path = "PUT", "/profiles/"+profileID
	return encodeRequest(ctx, req, request)
}

func encodePatchProfileRequest(ctx context.Context, req *http.Request, request interface{}) error {
	// r.Methods("PATCH").Path("/profiles/{id}")
	r := request.(patchProfileRequest)
	profileID := url.QueryEscape(r.ID)
	req.Method, req.URL.Path = "PATCH", "/profiles/"+profileID
	return encodeRequest(ctx, req, request)
}

func encodeDeleteProfileRequest(ctx context.Context, req *http.Request, request interface{}) error {
	// r.Methods("DELETE").Path("/profiles/{id}")
	r := request.(deleteProfileRequest)
	profileID := url.QueryEscape(r.ID)
	req.Method, req.URL.Path = "DELETE", "/profiles/"+profileID
	return encodeRequest(ctx, req, request)
}

func encodeGetAddressesRequest(ctx context.Context, req *http.Request, request interface{}) error {
	// r.Methods("GET").Path("/profiles/{id}/addresses/")
	r := request.(getAddressesRequest)
	profileID := url.QueryEscape(r.ProfileID)
	req.Method, req.URL.Path = "GET", "/profiles/"+profileID+"/addresses/"
	return encodeRequest(ctx, req, request)
}

func encodeGetAddressRequest(ctx context.Context, req *http.Request, request interface{}) error {
	// r.Methods("GET").Path("/profiles/{id}/addresses/{addressID}")
	r := request.(getAddressRequest)
	profileID := url.QueryEscape(r.ProfileID)
	addressID := url.QueryEscape(r.AddressID)
	req.Method, req.URL.Path = "GET", "/profiles/"+profileID+"/addresses/"+ addressID
	return encodeRequest(ctx, req, request)
}

func encodePostAddressRequest(ctx context.Context, req *http.Request, request interface{}) error {
	// r.Methods("POST").Path("/profiles/{id}/addresses/")
	r := request.(postAddressRequest)
	profileID := url.QueryEscape(r.ProfileID)
	req.Method, req.URL.Path = "POST", "/profiles/"+profileID+"/addresses/"
	return encodeRequest(ctx, req, request)
}

func encodeDeleteAddressRequest(ctx context.Context, req *http.Request, request interface{}) error {
	// r.Methods("DELETE").Path("/profiles/{id}/addresses/{addressID}")
	r := request.(deleteAddressRequest)
	profileID := url.QueryEscape(r.ProfileID)
	addressID := url.QueryEscape(r.AddressID)
	req.Method, req.URL.Path = "DELETE", "/profiles/"+profileID+"/addresses/"+addressID
	return encodeRequest(ctx, req, request)
}

func decodePostProfileResponse(_ context.Context, resp *http.Response) (interface{}, error) {
	var response postProfileResponse
	err := json.NewDecoder(resp.Body).Decode(&response)
	return response, err
}

func decodeGetProfileResponse(_ context.Context, resp *http.Response) (interface{}, error) {
	var response getProfileResponse
	err := json.NewDecoder(resp.Body).Decode(&response)
	return response, err
}

func decodePutProfileResponse(_ context.Context, resp *http.Response) (interface{}, error) {
	var response putProfileResponse
	err := json.NewDecoder(resp.Body).Decode(&response)
	return response, err
}

func decodePatchProfileResponse(_ context.Context, resp *http.Response) (interface{}, error) {
	var response patchProfileResponse
	err := json.NewDecoder(resp.Body).Decode(&response)
	return response, err
}

func decodeDeleteProfileResponse(_ context.Context, resp *http.Response) (interface{}, error) {
	var response deleteProfileResponse
	err := json.NewDecoder(resp.Body).Decode(&response)
	return response, err
}

func decodeGetAddressesResponse(_ context.Context, resp *http.Response) (interface{}, error) {
	var response getAddressesResponse
	err := json.NewDecoder(resp.Body).Decode(&response)
	return response, err
}

func decodeGetAddressResponse(_ context.Context, resp *http.Response) (interface{}, error) {
	var response getAddressResponse
	err := json.NewDecoder(resp.Body).Decode(&response)
	return response, err
}

func decodePostAddressResponse(_ context.Context, resp *http.Response) (interface{}, error) {
	var response postAddressResponse
	err := json.NewDecoder(resp.Body).Decode(&response)
	return response, err
}

func decodeDeleteAddressResponse(_ context.Context, resp *http.Response) (interface{}, error) {
	var response deleteAddressResponse
	err := json.NewDecoder(resp.Body).Decode(&response)
	return response, err
}

// errorer is implemented by all concrete response types that may contain
// errors. It allows us to change the HTTP response code without needing to
// trigger an endpoint (transport-level) error. For more information, read the
// big comment in endpoints.go.
type errorer interface {
	error() error
}

// encodeResponse is the common method to encode all response types to the
// client. I chose to do it this way because, since we're using JSON, there's no
// reason to provide anything more specific. It's certainly possible to
// specialize on a per-response (per-method) basis.
func encodeResponse(ctx context.Context, w http.ResponseWriter, response interface{}) error {
	if e, ok := response.(errorer); ok && e.error() != nil {
		// Not a Go kit transport error, but a business-logic error.
		// Provide those as HTTP errors.
		encodeError(ctx, e.error(), w)
		return nil
	}
	w.Header().Set("Content-Type", "application/json; charset=utf-8")
	return json.NewEncoder(w).Encode(response)
}

// encodeRequest likewise JSON-encodes the request to the HTTP request body.
// Don't use it directly as a transport/http.Client EncodeRequestFunc:
// profilesvc endpoints require mutating the HTTP method and request path.
func encodeRequest(_ context.Context, req *http.Request, request interface{}) error {
	var buf bytes.Buffer
	err := json.NewEncoder(&buf).Encode(request)
	if err != nil {
		return err
	}
	req.Body = ioutil.NopCloser(&buf)
	return nil
}

func encodeError(_ context.Context, err error, w http.ResponseWriter) {
	if err == nil {
		panic("encodeError with nil error")
	}
	w.Header().Set("Content-Type", "application/json; charset=utf-8")
	w.WriteHeader(codeFrom(err))
	json.NewEncoder(w).Encode(map[string]interface{}{
		"error": err.Error(),
	})
}

func codeFrom(err error) int {
	switch err {
	case ErrNotFound:
		return http.StatusNotFound
	case ErrAlreadyExists, ErrInconsistentIDs:
		return http.StatusBadRequest
	default:
		if e, ok := err.(httptransport.Error); ok {
			switch e.Domain {
			case httptransport.DomainDecode:
				return http.StatusBadRequest
			case httptransport.DomainDo:
				return http.StatusServiceUnavailable
			default:
				return http.StatusInternalServerError
			}
		}
		return http.StatusInternalServerError
	}
}
<commit_msg>Fix profilesvc path description<commit_after>package profilesvc

// The profilesvc is just over HTTP, so we just have a single transport.go.

import (
	"bytes"
	"encoding/json"
	"errors"
	"io/ioutil"
	"net/http"

	"net/url"

	"github.com/gorilla/mux"
	"golang.org/x/net/context"

	"github.com/go-kit/kit/log"
	httptransport "github.com/go-kit/kit/transport/http"
)

var (
	// ErrBadRouting is returned when an expected path variable is missing.
	// It always indicates programmer error.
	ErrBadRouting = errors.New("inconsistent mapping between route and handler (programmer error)")
)

// MakeHTTPHandler mounts all of the service endpoints into an http.Handler.
// Useful in a profilesvc server.
func MakeHTTPHandler(ctx context.Context, s Service, logger log.Logger) http.Handler {
	r := mux.NewRouter()
	e := MakeServerEndpoints(s)
	options := []httptransport.ServerOption{
		httptransport.ServerErrorLogger(logger),
		httptransport.ServerErrorEncoder(encodeError),
	}

	// POST    /profiles/                          adds another profile
	// GET     /profiles/:id                       retrieves the given profile by id
	// PUT     /profiles/:id                       post updated profile information about the profile
	// PATCH   /profiles/:id                       partial updated profile information
	// DELETE  /profiles/:id                       remove the given profile
	// GET     /profiles/:id/addresses/            retrieve addresses associated with the profile
	// GET     /profiles/:id/addresses/:addressID  retrieve a particular profile address
	// POST    /profiles/:id/addresses/            add a new address
	// DELETE  /profiles/:id/addresses/:addressID  remove an address

	r.Methods("POST").Path("/profiles/").Handler(httptransport.NewServer(
		ctx,
		e.PostProfileEndpoint,
		decodePostProfileRequest,
		encodeResponse,
		options...,
	))
	r.Methods("GET").Path("/profiles/{id}").Handler(httptransport.NewServer(
		ctx,
		e.GetProfileEndpoint,
		decodeGetProfileRequest,
		encodeResponse,
		options...,
	))
	r.Methods("PUT").Path("/profiles/{id}").Handler(httptransport.NewServer(
		ctx,
		e.PutProfileEndpoint,
		decodePutProfileRequest,
		encodeResponse,
		options...,
	))
	r.Methods("PATCH").Path("/profiles/{id}").Handler(httptransport.NewServer(
		ctx,
		e.PatchProfileEndpoint,
		decodePatchProfileRequest,
		encodeResponse,
		options...,
	))
	r.Methods("DELETE").Path("/profiles/{id}").Handler(httptransport.NewServer(
		ctx,
		e.DeleteProfileEndpoint,
		decodeDeleteProfileRequest,
		encodeResponse,
		options...,
	))
	r.Methods("GET").Path("/profiles/{id}/addresses/").Handler(httptransport.NewServer(
		ctx,
		e.GetAddressesEndpoint,
		decodeGetAddressesRequest,
		encodeResponse,
		options...,
	))
	r.Methods("GET").Path("/profiles/{id}/addresses/{addressID}").Handler(httptransport.NewServer(
		ctx,
		e.GetAddressEndpoint,
		decodeGetAddressRequest,
		encodeResponse,
		options...,
	))
	r.Methods("POST").Path("/profiles/{id}/addresses/").Handler(httptransport.NewServer(
		ctx,
		e.PostAddressEndpoint,
		decodePostAddressRequest,
		encodeResponse,
		options...,
	))
	r.Methods("DELETE").Path("/profiles/{id}/addresses/{addressID}").Handler(httptransport.NewServer(
		ctx,
		e.DeleteAddressEndpoint,
		decodeDeleteAddressRequest,
		encodeResponse,
		options...,
	))
	return r
}

func decodePostProfileRequest(_ context.Context, r *http.Request) (request interface{}, err error) {
	var req postProfileRequest
	if e := json.NewDecoder(r.Body).Decode(&req.Profile); e != nil {
		return nil, e
	}
	return req, nil
}

func decodeGetProfileRequest(_ context.Context, r *http.Request) (request interface{}, err error) {
	vars := mux.Vars(r)
	id, ok := vars["id"]
	if !ok {
		return nil, ErrBadRouting
	}
	return getProfileRequest{ID: id}, nil
}

func decodePutProfileRequest(_ context.Context, r *http.Request) (request interface{}, err error) {
	vars := mux.Vars(r)
	id, ok := vars["id"]
	if !ok {
		return nil, ErrBadRouting
	}
	var profile Profile
	if err := json.NewDecoder(r.Body).Decode(&profile); err != nil {
		return nil, err
	}
	return putProfileRequest{
		ID:      id,
		Profile: profile,
	}, nil
}

func decodePatchProfileRequest(_ context.Context, r *http.Request) (request interface{}, err error) {
	vars := mux.Vars(r)
	id, ok := vars["id"]
	if !ok {
		return nil, ErrBadRouting
	}
	var profile Profile
	if err := json.NewDecoder(r.Body).Decode(&profile); err != nil {
		return nil, err
	}
	return patchProfileRequest{
		ID:      id,
		Profile: profile,
	}, nil
}

func decodeDeleteProfileRequest(_ context.Context, r *http.Request) (request interface{}, err error) {
	vars := mux.Vars(r)
	id, ok := vars["id"]
	if !ok {
		return nil, ErrBadRouting
	}
	return deleteProfileRequest{ID: id}, nil
}

func decodeGetAddressesRequest(_ context.Context, r *http.Request) (request interface{}, err error) {
	vars := mux.Vars(r)
	id, ok := vars["id"]
	if !ok {
		return nil, ErrBadRouting
	}
	return getAddressesRequest{ProfileID: id}, nil
}

func decodeGetAddressRequest(_ context.Context, r *http.Request) (request interface{}, err error) {
	vars := mux.Vars(r)
	id, ok := vars["id"]
	if !ok {
		return nil, ErrBadRouting
	}
	addressID, ok := vars["addressID"]
	if !ok {
		return nil, ErrBadRouting
	}
	return getAddressRequest{
		ProfileID: id,
		AddressID: addressID,
	}, nil
}

func decodePostAddressRequest(_ context.Context, r *http.Request) (request interface{}, err error) {
	vars := mux.Vars(r)
	id, ok := vars["id"]
	if !ok {
		return nil, ErrBadRouting
	}
	var address Address
	if err := json.NewDecoder(r.Body).Decode(&address); err != nil {
		return nil, err
	}
	return postAddressRequest{
		ProfileID: id,
		Address:   address,
	}, nil
}

func decodeDeleteAddressRequest(_ context.Context, r *http.Request) (request interface{}, err error) {
	vars := mux.Vars(r)
	id, ok := vars["id"]
	if !ok {
		return nil, ErrBadRouting
	}
	addressID, ok := vars["addressID"]
	if !ok {
		return nil, ErrBadRouting
	}
	return deleteAddressRequest{
		ProfileID: id,
		AddressID: addressID,
	}, nil
}

func encodePostProfileRequest(ctx context.Context, req *http.Request, request interface{}) error {
	// r.Methods("POST").Path("/profiles/")
	req.Method, req.URL.Path = "POST", "/profiles/"
	return encodeRequest(ctx, req, request)
}

func encodeGetProfileRequest(ctx context.Context, req *http.Request, request interface{}) error {
	// r.Methods("GET").Path("/profiles/{id}")
	r := request.(getProfileRequest)
	profileID := url.QueryEscape(r.ID)
	req.Method, req.URL.Path = "GET", "/profiles/"+profileID
	return encodeRequest(ctx, req, request)
}

func encodePutProfileRequest(ctx context.Context, req *http.Request, request interface{}) error {
	// r.Methods("PUT").Path("/profiles/{id}")
	r := request.(putProfileRequest)
	profileID := url.QueryEscape(r.ID)
	req.Method, req.URL.Path = "PUT", "/profiles/"+profileID
	return encodeRequest(ctx, req, request)
}

func encodePatchProfileRequest(ctx context.Context, req *http.Request, request interface{}) error {
	// r.Methods("PATCH").Path("/profiles/{id}")
	r := request.(patchProfileRequest)
	profileID := url.QueryEscape(r.ID)
	req.Method, req.URL.Path = "PATCH", "/profiles/"+profileID
	return encodeRequest(ctx, req, request)
}

func encodeDeleteProfileRequest(ctx context.Context, req *http.Request, request interface{}) error {
	// r.Methods("DELETE").Path("/profiles/{id}")
	r := request.(deleteProfileRequest)
	profileID := url.QueryEscape(r.ID)
	req.Method, req.URL.Path = "DELETE", "/profiles/"+profileID
	return encodeRequest(ctx, req, request)
}

func encodeGetAddressesRequest(ctx context.Context, req *http.Request, request interface{}) error {
	// r.Methods("GET").Path("/profiles/{id}/addresses/")
	r := request.(getAddressesRequest)
	profileID := url.QueryEscape(r.ProfileID)
	req.Method, req.URL.Path = "GET", "/profiles/"+profileID+"/addresses/"
	return encodeRequest(ctx, req, request)
}

func encodeGetAddressRequest(ctx context.Context, req *http.Request, request interface{}) error {
	// r.Methods("GET").Path("/profiles/{id}/addresses/{addressID}")
	r := request.(getAddressRequest)
	profileID := url.QueryEscape(r.ProfileID)
	addressID := url.QueryEscape(r.AddressID)
	req.Method, req.URL.Path = "GET", "/profiles/"+profileID+"/addresses/"+ addressID
	return encodeRequest(ctx, req, request)
}

func encodePostAddressRequest(ctx context.Context, req *http.Request, request interface{}) error {
	// r.Methods("POST").Path("/profiles/{id}/addresses/")
	r := request.(postAddressRequest)
	profileID := url.QueryEscape(r.ProfileID)
	req.Method, req.URL.Path = "POST", "/profiles/"+profileID+"/addresses/"
	return encodeRequest(ctx, req, request)
}

func encodeDeleteAddressRequest(ctx context.Context, req *http.Request, request interface{}) error {
	// r.Methods("DELETE").Path("/profiles/{id}/addresses/{addressID}")
	r := request.(deleteAddressRequest)
	profileID := url.QueryEscape(r.ProfileID)
	addressID := url.QueryEscape(r.AddressID)
	req.Method, req.URL.Path = "DELETE", "/profiles/"+profileID+"/addresses/"+addressID
	return encodeRequest(ctx, req, request)
}

func decodePostProfileResponse(_ context.Context, resp *http.Response) (interface{}, error) {
	var response postProfileResponse
	err := json.NewDecoder(resp.Body).Decode(&response)
	return response, err
}

func decodeGetProfileResponse(_ context.Context, resp *http.Response) (interface{}, error) {
	var response getProfileResponse
	err := json.NewDecoder(resp.Body).Decode(&response)
	return response, err
}

func decodePutProfileResponse(_ context.Context, resp *http.Response) (interface{}, error) {
	var response putProfileResponse
	err := json.NewDecoder(resp.Body).Decode(&response)
	return response, err
}

func decodePatchProfileResponse(_ context.Context, resp *http.Response) (interface{}, error) {
	var response patchProfileResponse
	err := json.NewDecoder(resp.Body).Decode(&response)
	return response, err
}

func decodeDeleteProfileResponse(_ context.Context, resp *http.Response) (interface{}, error) {
	var response deleteProfileResponse
	err := json.NewDecoder(resp.Body).Decode(&response)
	return response, err
}

func decodeGetAddressesResponse(_ context.Context, resp *http.Response) (interface{}, error) {
	var response getAddressesResponse
	err := json.NewDecoder(resp.Body).Decode(&response)
	return response, err
}

func decodeGetAddressResponse(_ context.Context, resp *http.Response) (interface{}, error) {
	var response getAddressResponse
	err := json.NewDecoder(resp.Body).Decode(&response)
	return response, err
}

func decodePostAddressResponse(_ context.Context, resp *http.Response) (interface{}, error) {
	var response postAddressResponse
	err := json.NewDecoder(resp.Body).Decode(&response)
	return response, err
}

func decodeDeleteAddressResponse(_ context.Context, resp *http.Response) (interface{}, error) {
	var response deleteAddressResponse
	err := json.NewDecoder(resp.Body).Decode(&response)
	return response, err
}

// errorer is implemented by all concrete response types that may contain
// errors. It allows us to change the HTTP response code without needing to
// trigger an endpoint (transport-level) error. For more information, read the
// big comment in endpoints.go.
type errorer interface {
	error() error
}

// encodeResponse is the common method to encode all response types to the
// client. I chose to do it this way because, since we're using JSON, there's no
// reason to provide anything more specific. It's certainly possible to
// specialize on a per-response (per-method) basis.
func encodeResponse(ctx context.Context, w http.ResponseWriter, response interface{}) error {
	if e, ok := response.(errorer); ok && e.error() != nil {
		// Not a Go kit transport error, but a business-logic error.
		// Provide those as HTTP errors.
		encodeError(ctx, e.error(), w)
		return nil
	}
	w.Header().Set("Content-Type", "application/json; charset=utf-8")
	return json.NewEncoder(w).Encode(response)
}

// encodeRequest likewise JSON-encodes the request to the HTTP request body.
// Don't use it directly as a transport/http.Client EncodeRequestFunc:
// profilesvc endpoints require mutating the HTTP method and request path.
func encodeRequest(_ context.Context, req *http.Request, request interface{}) error {
	var buf bytes.Buffer
	err := json.NewEncoder(&buf).Encode(request)
	if err != nil {
		return err
	}
	req.Body = ioutil.NopCloser(&buf)
	return nil
}

func encodeError(_ context.Context, err error, w http.ResponseWriter) {
	if err == nil {
		panic("encodeError with nil error")
	}
	w.Header().Set("Content-Type", "application/json; charset=utf-8")
	w.WriteHeader(codeFrom(err))
	json.NewEncoder(w).Encode(map[string]interface{}{
		"error": err.Error(),
	})
}

func codeFrom(err error) int {
	switch err {
	case ErrNotFound:
		return http.StatusNotFound
	case ErrAlreadyExists, ErrInconsistentIDs:
		return http.StatusBadRequest
	default:
		if e, ok := err.(httptransport.Error); ok {
			switch e.Domain {
			case httptransport.DomainDecode:
				return http.StatusBadRequest
			case httptransport.DomainDo:
				return http.StatusServiceUnavailable
			default:
				return http.StatusInternalServerError
			}
		}
		return http.StatusInternalServerError
	}
}
<|endoftext|>


<commit_before>// Copyright 2016 Documize Inc. <legal@documize.com>. All rights reserved.
//
// This software (Documize Community Edition) is licensed under
// GNU AGPL v3 http://www.gnu.org/licenses/agpl-3.0.en.html
//
// You can operate outside the AGPL restrictions by purchasing
// Documize Enterprise Edition and obtaining a commercial license
// by contacting <sales@documize.com>.
//
// https://documize.com

package search

import (
	"database/sql"
	"strings"

	"github.com/documize/community/domain"
	"github.com/documize/community/domain/store"
	"github.com/documize/community/model/attachment"
	"github.com/documize/community/model/doc"
	"github.com/documize/community/model/page"
	"github.com/documize/community/model/search"
	"github.com/pkg/errors"
)

// StoreSQLServer provides data access to space information.
type StoreSQLServer struct {
	store.Context
	store.SearchStorer
}

// IndexDocument adds search index entries for document inserting title, tags and attachments as
// searchable items. Any existing document entries are removed.
func (s StoreSQLServer) IndexDocument(ctx domain.RequestContext, doc doc.Document, a []attachment.Attachment) (err error) {
	return nil
}

// DeleteDocument removes all search entries for document.
func (s StoreSQLServer) DeleteDocument(ctx domain.RequestContext, ID string) (err error) {
	return nil
}

// IndexContent adds search index entry for document context.
// Any existing document entries are removed.
func (s StoreSQLServer) IndexContent(ctx domain.RequestContext, p page.Page) (err error) {
	return nil
}

// DeleteContent removes all search entries for specific document content.
func (s StoreSQLServer) DeleteContent(ctx domain.RequestContext, pageID string) (err error) {
	return nil
}

// Documents searches the documents that the client is allowed to see, using the keywords search string, then audits that search.
// Visible documents include both those in the client's own organization and those that are public, or whose visibility includes the client.
func (s StoreSQLServer) Documents(ctx domain.RequestContext, q search.QueryOptions) (results []search.QueryResult, err error) {
	q.Keywords = strings.TrimSpace(q.Keywords)
	if len(q.Keywords) == 0 {
		return
	}

	results = []search.QueryResult{}

	// Match doc names
	if q.Doc {
		r1, err1 := s.matchDoc(ctx, q.Keywords)
		if err1 != nil {
			err = errors.Wrap(err1, "search document names")
			return
		}

		results = append(results, r1...)
	}

	// Match doc content
	if q.Content {
		r2, err2 := s.matchSection(ctx, q.Keywords)
		if err2 != nil {
			err = errors.Wrap(err2, "search document content")
			return
		}

		results = append(results, r2...)
	}

	if len(results) == 0 {
		results = []search.QueryResult{}
	}

	return
}

// Match published documents.
func (s StoreSQLServer) matchDoc(ctx domain.RequestContext, keywords string) (r []search.QueryResult, err error) {
	keywords = strings.ToLower(keywords)

	sql1 := s.Bind(`SELECT
			d.id, d.c_orgid AS orgid, d.c_refid AS documentid, d.c_refid AS itemid, 'doc' AS itemtype,
			d.c_spaceid as spaceid, COALESCE(d.c_name,'Unknown') AS document, d.c_tags AS tags,
			d.c_desc AS excerpt, d.c_template AS template, d.c_versionid AS versionid,
			COALESCE(l.c_name,'Unknown') AS space, d.c_created AS created, d.c_revised AS revised
		FROM
            dmz_doc d
        LEFT JOIN
            dmz_space l ON l.c_orgid=d.c_orgid AND l.c_refid = d.c_spaceid
        WHERE
			d.c_orgid = ?
			AND d.c_lifecycle = 1
            AND d.c_spaceid IN
            (
                SELECT c_refid FROM dmz_space WHERE c_orgid=? AND c_refid IN
                (
                    SELECT c_refid from dmz_permission WHERE c_orgid=? AND c_who='user' AND (c_whoid=? OR c_whoid='0') AND c_location='space'
                    UNION ALL
                    SELECT p.c_refid from dmz_permission p LEFT JOIN dmz_group_member r ON p.c_whoid=r.c_groupid WHERE p.c_orgid=? AND p.c_who='role'
                    AND p.c_location='space' AND (r.c_userid=? OR r.c_userid='0')
                )
            )
            AND (CONTAINS(d.c_name, ?) OR CONTAINS(d.c_desc, ?))`)

	err = s.Runtime.Db.Select(&r,
		sql1,
		ctx.OrgID,
		ctx.OrgID,
		ctx.OrgID,
		ctx.UserID,
		ctx.OrgID,
		ctx.UserID,
		keywords, keywords)

	if err == sql.ErrNoRows {
		err = nil
		r = []search.QueryResult{}
	}

	return
}

// Match approved section contents.
func (s StoreSQLServer) matchSection(ctx domain.RequestContext, keywords string) (r []search.QueryResult, err error) {
	keywords = strings.ToLower(keywords)

	sql1 := s.Bind(`SELECT
			d.id, d.c_orgid AS orgid, d.c_refid AS documentid, s.c_refid AS itemid, 'page' AS itemtype,
			d.c_spaceid as spaceid, COALESCE(d.c_name,'Unknown') AS document, d.c_tags AS tags,
			d.c_desc AS excerpt, d.c_template AS template, d.c_versionid AS versionid,
			COALESCE(l.c_name,'Unknown') AS space, d.c_created AS created, d.c_revised AS revised
		FROM
			dmz_doc d
		INNER JOIN
			dmz_section s ON s.c_docid = d.c_refid
        INNER JOIN
            dmz_space l ON l.c_orgid=d.c_orgid AND l.c_refid = d.c_spaceid
		WHERE
			d.c_refid = s.c_docid
			AND d.c_orgid = ?
			AND d.c_lifecycle = 1
			AND s.c_status = 0
            AND d.c_spaceid IN
            (
                SELECT c_refid FROM dmz_space WHERE c_orgid=? AND c_refid IN
                (
                    SELECT c_refid from dmz_permission WHERE c_orgid=? AND c_who='user' AND (c_whoid=? OR c_whoid='0') AND c_location='space'
                    UNION ALL
                    SELECT p.c_refid from dmz_permission p LEFT JOIN dmz_group_member r ON p.c_whoid=r.c_groupid WHERE p.c_orgid=? AND p.c_who='role'
                    AND p.c_location='space' AND (r.c_userid=? OR r.c_userid='0')
                )
            )
            AND (CONTAINS(s.c_name, ?) OR CONTAINS(s.c_body, ?))`)

	err = s.Runtime.Db.Select(&r,
		sql1,
		ctx.OrgID,
		ctx.OrgID,
		ctx.OrgID,
		ctx.UserID,
		ctx.OrgID,
		ctx.UserID,
		keywords, keywords)

	if err == sql.ErrNoRows {
		err = nil
		r = []search.QueryResult{}
	}

	return
}

/*
https://docs.microsoft.com/en-us/sql/relational-databases/search/get-started-with-full-text-search?view=sql-server-2017#options

SELECT * FROM dmz_doc WHERE CONTAINS(c_name, 'release AND v2.0*');
SELECT * FROM dmz_doc WHERE CONTAINS(c_name, 'release AND NOT v2.0*');
SELECT * FROM dmz_section WHERE CONTAINS(c_name, 'User');
SELECT * FROM dmz_section WHERE CONTAINS(c_body, 'authenticate AND NOT user');
*/
<commit_msg>Enable tag searching for SQL Server database<commit_after>// Copyright 2016 Documize Inc. <legal@documize.com>. All rights reserved.
//
// This software (Documize Community Edition) is licensed under
// GNU AGPL v3 http://www.gnu.org/licenses/agpl-3.0.en.html
//
// You can operate outside the AGPL restrictions by purchasing
// Documize Enterprise Edition and obtaining a commercial license
// by contacting <sales@documize.com>.
//
// https://documize.com

package search

import (
	"database/sql"
	"fmt"
	"strings"

	"github.com/documize/community/domain"
	"github.com/documize/community/domain/store"
	"github.com/documize/community/model/attachment"
	"github.com/documize/community/model/doc"
	"github.com/documize/community/model/page"
	"github.com/documize/community/model/search"
	"github.com/pkg/errors"
)

// StoreSQLServer provides data access to space information.
type StoreSQLServer struct {
	store.Context
	store.SearchStorer
}

// IndexDocument adds search index entries for document inserting title, tags and attachments as
// searchable items. Any existing document entries are removed.
func (s StoreSQLServer) IndexDocument(ctx domain.RequestContext, doc doc.Document, a []attachment.Attachment) (err error) {
	return nil
}

// DeleteDocument removes all search entries for document.
func (s StoreSQLServer) DeleteDocument(ctx domain.RequestContext, ID string) (err error) {
	return nil
}

// IndexContent adds search index entry for document context.
// Any existing document entries are removed.
func (s StoreSQLServer) IndexContent(ctx domain.RequestContext, p page.Page) (err error) {
	return nil
}

// DeleteContent removes all search entries for specific document content.
func (s StoreSQLServer) DeleteContent(ctx domain.RequestContext, pageID string) (err error) {
	return nil
}

// Documents searches the documents that the client is allowed to see, using the keywords search string, then audits that search.
// Visible documents include both those in the client's own organization and those that are public, or whose visibility includes the client.
func (s StoreSQLServer) Documents(ctx domain.RequestContext, q search.QueryOptions) (results []search.QueryResult, err error) {
	q.Keywords = strings.TrimSpace(q.Keywords)
	if len(q.Keywords) == 0 {
		return
	}

	results = []search.QueryResult{}

	// Match doc names
	if q.Doc {
		r1, err1 := s.matchDoc(ctx, q.Keywords)
		if err1 != nil {
			err = errors.Wrap(err1, "search document names")
			return
		}

		results = append(results, r1...)
	}

	// Match doc content
	if q.Content {
		r2, err2 := s.matchSection(ctx, q.Keywords)
		if err2 != nil {
			err = errors.Wrap(err2, "search document content")
			return
		}

		results = append(results, r2...)
	}

	// Match doc content
	if q.Tag {
		r3, err2 := s.matchTag(ctx, q.Keywords)
		if err2 != nil {
			err = errors.Wrap(err2, "search document tag")
			return
		}

		results = append(results, r3...)
	}

	if len(results) == 0 {
		results = []search.QueryResult{}
	}

	return
}

// Match published documents.
func (s StoreSQLServer) matchDoc(ctx domain.RequestContext, keywords string) (r []search.QueryResult, err error) {
	keywords = strings.ToLower(keywords)

	sql1 := s.Bind(`SELECT
			d.id, d.c_orgid AS orgid, d.c_refid AS documentid, d.c_refid AS itemid, 'doc' AS itemtype,
			d.c_spaceid as spaceid, COALESCE(d.c_name,'Unknown') AS document, d.c_tags AS tags,
			d.c_desc AS excerpt, d.c_template AS template, d.c_versionid AS versionid,
			COALESCE(l.c_name,'Unknown') AS space, d.c_created AS created, d.c_revised AS revised
		FROM
            dmz_doc d
        LEFT JOIN
            dmz_space l ON l.c_orgid=d.c_orgid AND l.c_refid = d.c_spaceid
        WHERE
			d.c_orgid = ?
			AND d.c_lifecycle = 1
            AND d.c_spaceid IN
            (
                SELECT c_refid FROM dmz_space WHERE c_orgid=? AND c_refid IN
                (
                    SELECT c_refid from dmz_permission WHERE c_orgid=? AND c_who='user' AND (c_whoid=? OR c_whoid='0') AND c_location='space'
                    UNION ALL
                    SELECT p.c_refid from dmz_permission p LEFT JOIN dmz_group_member r ON p.c_whoid=r.c_groupid WHERE p.c_orgid=? AND p.c_who='role'
                    AND p.c_location='space' AND (r.c_userid=? OR r.c_userid='0')
                )
            )
            AND (CONTAINS(d.c_name, ?) OR CONTAINS(d.c_desc, ?))`)

	err = s.Runtime.Db.Select(&r,
		sql1,
		ctx.OrgID,
		ctx.OrgID,
		ctx.OrgID,
		ctx.UserID,
		ctx.OrgID,
		ctx.UserID,
		keywords, keywords)

	if err == sql.ErrNoRows {
		err = nil
		r = []search.QueryResult{}
	}

	return
}

// Match approved section contents.
func (s StoreSQLServer) matchSection(ctx domain.RequestContext, keywords string) (r []search.QueryResult, err error) {
	keywords = strings.ToLower(keywords)

	sql1 := s.Bind(`SELECT
			d.id, d.c_orgid AS orgid, d.c_refid AS documentid, s.c_refid AS itemid, 'page' AS itemtype,
			d.c_spaceid as spaceid, COALESCE(d.c_name,'Unknown') AS document, d.c_tags AS tags,
			d.c_desc AS excerpt, d.c_template AS template, d.c_versionid AS versionid,
			COALESCE(l.c_name,'Unknown') AS space, d.c_created AS created, d.c_revised AS revised
		FROM
			dmz_doc d
		INNER JOIN
			dmz_section s ON s.c_docid = d.c_refid
        INNER JOIN
            dmz_space l ON l.c_orgid=d.c_orgid AND l.c_refid = d.c_spaceid
		WHERE
			d.c_refid = s.c_docid
			AND d.c_orgid = ?
			AND d.c_lifecycle = 1
			AND s.c_status = 0
            AND d.c_spaceid IN
            (
                SELECT c_refid FROM dmz_space WHERE c_orgid=? AND c_refid IN
                (
                    SELECT c_refid from dmz_permission WHERE c_orgid=? AND c_who='user' AND (c_whoid=? OR c_whoid='0') AND c_location='space'
                    UNION ALL
                    SELECT p.c_refid from dmz_permission p LEFT JOIN dmz_group_member r ON p.c_whoid=r.c_groupid WHERE p.c_orgid=? AND p.c_who='role'
                    AND p.c_location='space' AND (r.c_userid=? OR r.c_userid='0')
                )
            )
            AND (CONTAINS(s.c_name, ?) OR CONTAINS(s.c_body, ?))`)

	err = s.Runtime.Db.Select(&r,
		sql1,
		ctx.OrgID,
		ctx.OrgID,
		ctx.OrgID,
		ctx.UserID,
		ctx.OrgID,
		ctx.UserID,
		keywords, keywords)

	if err == sql.ErrNoRows {
		err = nil
		r = []search.QueryResult{}
	}

	return
}

func (s StoreSQLServer) matchTag(ctx domain.RequestContext, keywords string) (r []search.QueryResult, err error) {
	// LIKE clause does not like quotes!
	keywords = strings.Replace(keywords, "'", "", -1)
	keywords = strings.Replace(keywords, "\"", "", -1)
	keywords = strings.Replace(keywords, "%", "", -1)
	keywords = fmt.Sprintf("%%%s%%", strings.ToLower(keywords))

	sql1 := s.Bind(`SELECT
			d.id, d.c_orgid AS orgid, d.c_refid AS documentid, d.c_refid AS itemid, 'tag' AS itemtype,
			d.c_spaceid as spaceid, COALESCE(d.c_name,'Unknown') AS document, d.c_tags AS tags,
			d.c_desc AS excerpt, d.c_template AS template, d.c_versionid AS versionid,
			COALESCE(l.c_name,'Unknown') AS space, d.c_created AS created, d.c_revised AS revised
		FROM
            dmz_doc d
        LEFT JOIN
            dmz_space l ON l.c_orgid=d.c_orgid AND l.c_refid = d.c_spaceid
        WHERE
			d.c_orgid = ?
			AND d.c_lifecycle = 1
            AND d.c_spaceid IN
            (
                SELECT c_refid FROM dmz_space WHERE c_orgid=? AND c_refid IN
                (
                    SELECT c_refid from dmz_permission WHERE c_orgid=? AND c_who='user' AND (c_whoid=? OR c_whoid='0') AND c_location='space'
                    UNION ALL
                    SELECT p.c_refid from dmz_permission p LEFT JOIN dmz_group_member r ON p.c_whoid=r.c_groupid WHERE p.c_orgid=? AND p.c_who='role'
                    AND p.c_location='space' AND (r.c_userid=? OR r.c_userid='0')
                )
            )
            AND d.c_tags LIKE ?`)

	err = s.Runtime.Db.Select(&r,
		sql1,
		ctx.OrgID,
		ctx.OrgID,
		ctx.OrgID,
		ctx.UserID,
		ctx.OrgID,
		ctx.UserID,
		keywords)

	if err == sql.ErrNoRows {
		err = nil
		r = []search.QueryResult{}
	}

	return
}

/*
https://docs.microsoft.com/en-us/sql/relational-databases/search/get-started-with-full-text-search?view=sql-server-2017#options

SELECT * FROM dmz_doc WHERE CONTAINS(c_name, 'release AND v2.0*');
SELECT * FROM dmz_doc WHERE CONTAINS(c_name, 'release AND NOT v2.0*');
SELECT * FROM dmz_section WHERE CONTAINS(c_name, 'User');
SELECT * FROM dmz_section WHERE CONTAINS(c_body, 'authenticate AND NOT user');
*/
<|endoftext|>


<commit_before>package ipvlan

import (
	"fmt"

	"github.com/docker/docker/pkg/parsers/kernel"
	"github.com/docker/docker/pkg/stringid"
	"github.com/docker/libnetwork/driverapi"
	"github.com/docker/libnetwork/netlabel"
	"github.com/docker/libnetwork/ns"
	"github.com/docker/libnetwork/options"
	"github.com/docker/libnetwork/osl"
	"github.com/docker/libnetwork/types"
	"github.com/sirupsen/logrus"
)

// CreateNetwork the network for the specified driver type
func (d *driver) CreateNetwork(nid string, option map[string]interface{}, nInfo driverapi.NetworkInfo, ipV4Data, ipV6Data []driverapi.IPAMData) error {
	defer osl.InitOSContext()()
	kv, err := kernel.GetKernelVersion()
	if err != nil {
		return fmt.Errorf("Failed to check kernel version for %s driver support: %v", ipvlanType, err)
	}
	// ensure Kernel version is >= v4.2 for ipvlan support
	if kv.Kernel < ipvlanKernelVer || (kv.Kernel == ipvlanKernelVer && kv.Major < ipvlanMajorVer) {
		return fmt.Errorf("kernel version failed to meet the minimum ipvlan kernel requirement of %d.%d, found %d.%d.%d",
			ipvlanKernelVer, ipvlanMajorVer, kv.Kernel, kv.Major, kv.Minor)
	}
	// reject a null v4 network
	if len(ipV4Data) == 0 || ipV4Data[0].Pool.String() == "0.0.0.0/0" {
		return fmt.Errorf("ipv4 pool is empty")
	}
	// parse and validate the config and bind to networkConfiguration
	config, err := parseNetworkOptions(nid, option)
	if err != nil {
		return err
	}
	config.ID = nid
	err = config.processIPAM(nid, ipV4Data, ipV6Data)
	if err != nil {
		return err
	}
	// verify the ipvlan mode from -o ipvlan_mode option
	switch config.IpvlanMode {
	case "", modeL2:
		// default to ipvlan L2 mode if -o ipvlan_mode is empty
		config.IpvlanMode = modeL2
	case modeL3:
		config.IpvlanMode = modeL3
	default:
		return fmt.Errorf("requested ipvlan mode '%s' is not valid, 'l2' mode is the ipvlan driver default", config.IpvlanMode)
	}
	// loopback is not a valid parent link
	if config.Parent == "lo" {
		return fmt.Errorf("loopback interface is not a valid %s parent link", ipvlanType)
	}
	// if parent interface not specified, create a dummy type link to use named dummy+net_id
	if config.Parent == "" {
		config.Parent = getDummyName(stringid.TruncateID(config.ID))
		// empty parent and --internal are handled the same. Set here to update k/v
		config.Internal = true
	}
	err = d.createNetwork(config)
	if err != nil {
		return err
	}
	// update persistent db, rollback on fail
	err = d.storeUpdate(config)
	if err != nil {
		d.deleteNetwork(config.ID)
		logrus.Debugf("encountered an error rolling back a network create for %s : %v", config.ID, err)
		return err
	}

	return nil
}

// createNetwork is used by new network callbacks and persistent network cache
func (d *driver) createNetwork(config *configuration) error {
	networkList := d.getNetworks()
	for _, nw := range networkList {
		if config.Parent == nw.config.Parent {
			return fmt.Errorf("network %s is already using parent interface %s",
				getDummyName(stringid.TruncateID(nw.config.ID)), config.Parent)
		}
	}
	if !parentExists(config.Parent) {
		// if the --internal flag is set, create a dummy link
		if config.Internal {
			err := createDummyLink(config.Parent, getDummyName(stringid.TruncateID(config.ID)))
			if err != nil {
				return err
			}
			config.CreatedSlaveLink = true
			// notify the user in logs they have limited communications
			if config.Parent == getDummyName(stringid.TruncateID(config.ID)) {
				logrus.Debugf("Empty -o parent= and --internal flags limit communications to other containers inside of network: %s",
					config.Parent)
			}
		} else {
			// if the subinterface parent_iface.vlan_id checks do not pass, return err.
			//  a valid example is 'eth0.10' for a parent iface 'eth0' with a vlan id '10'
			err := createVlanLink(config.Parent)
			if err != nil {
				return err
			}
			// if driver created the networks slave link, record it for future deletion
			config.CreatedSlaveLink = true
		}
	}
	n := &network{
		id:        config.ID,
		driver:    d,
		endpoints: endpointTable{},
		config:    config,
	}
	// add the *network
	d.addNetwork(n)

	return nil
}

// DeleteNetwork the network for the specified driver type
func (d *driver) DeleteNetwork(nid string) error {
	defer osl.InitOSContext()()
	n := d.network(nid)
	if n == nil {
		return fmt.Errorf("network id %s not found", nid)
	}
	// if the driver created the slave interface, delete it, otherwise leave it
	if ok := n.config.CreatedSlaveLink; ok {
		// if the interface exists, only delete if it matches iface.vlan or dummy.net_id naming
		if ok := parentExists(n.config.Parent); ok {
			// only delete the link if it is named the net_id
			if n.config.Parent == getDummyName(stringid.TruncateID(nid)) {
				err := delDummyLink(n.config.Parent)
				if err != nil {
					logrus.Debugf("link %s was not deleted, continuing the delete network operation: %v",
						n.config.Parent, err)
				}
			} else {
				// only delete the link if it matches iface.vlan naming
				err := delVlanLink(n.config.Parent)
				if err != nil {
					logrus.Debugf("link %s was not deleted, continuing the delete network operation: %v",
						n.config.Parent, err)
				}
			}
		}
	}
	for _, ep := range n.endpoints {
		if link, err := ns.NlHandle().LinkByName(ep.srcName); err == nil {
			if err := ns.NlHandle().LinkDel(link); err != nil {
				logrus.WithError(err).Warnf("Failed to delete interface (%s)'s link on endpoint (%s) delete", ep.srcName, ep.id)
			}
		}

		if err := d.storeDelete(ep); err != nil {
			logrus.Warnf("Failed to remove ipvlan endpoint %.7s from store: %v", ep.id, err)
		}
	}
	// delete the *network
	d.deleteNetwork(nid)
	// delete the network record from persistent cache
	err := d.storeDelete(n.config)
	if err != nil {
		return fmt.Errorf("error deleting deleting id %s from datastore: %v", nid, err)
	}
	return nil
}

// parseNetworkOptions parse docker network options
func parseNetworkOptions(id string, option options.Generic) (*configuration, error) {
	var (
		err    error
		config = &configuration{}
	)
	// parse generic labels first
	if genData, ok := option[netlabel.GenericData]; ok && genData != nil {
		if config, err = parseNetworkGenericOptions(genData); err != nil {
			return nil, err
		}
	}
	// setting the parent to "" will trigger an isolated network dummy parent link
	if _, ok := option[netlabel.Internal]; ok {
		config.Internal = true
		// empty --parent= and --internal are handled the same.
		config.Parent = ""
	}
	return config, nil
}

// parseNetworkGenericOptions parse generic driver docker network options
func parseNetworkGenericOptions(data interface{}) (*configuration, error) {
	var (
		err    error
		config *configuration
	)
	switch opt := data.(type) {
	case *configuration:
		config = opt
	case map[string]string:
		config = &configuration{}
		err = config.fromOptions(opt)
	case options.Generic:
		var opaqueConfig interface{}
		if opaqueConfig, err = options.GenerateFromModel(opt, config); err == nil {
			config = opaqueConfig.(*configuration)
		}
	default:
		err = types.BadRequestErrorf("unrecognized network configuration format: %v", opt)
	}
	return config, err
}

// fromOptions binds the generic options to networkConfiguration to cache
func (config *configuration) fromOptions(labels map[string]string) error {
	for label, value := range labels {
		switch label {
		case parentOpt:
			// parse driver option '-o parent'
			config.Parent = value
		case driverModeOpt:
			// parse driver option '-o ipvlan_mode'
			config.IpvlanMode = value
		}
	}
	return nil
}

// processIPAM parses v4 and v6 IP information and binds it to the network configuration
func (config *configuration) processIPAM(id string, ipamV4Data, ipamV6Data []driverapi.IPAMData) error {
	if len(ipamV4Data) > 0 {
		for _, ipd := range ipamV4Data {
			s := &ipv4Subnet{
				SubnetIP: ipd.Pool.String(),
				GwIP:     ipd.Gateway.String(),
			}
			config.Ipv4Subnets = append(config.Ipv4Subnets, s)
		}
	}
	if len(ipamV6Data) > 0 {
		for _, ipd := range ipamV6Data {
			s := &ipv6Subnet{
				SubnetIP: ipd.Pool.String(),
				GwIP:     ipd.Gateway.String(),
			}
			config.Ipv6Subnets = append(config.Ipv6Subnets, s)
		}
	}
	return nil
}
<commit_msg>Ipvlan network handles netlabel.Internal wrong<commit_after>package ipvlan

import (
	"fmt"

	"github.com/docker/docker/pkg/parsers/kernel"
	"github.com/docker/docker/pkg/stringid"
	"github.com/docker/libnetwork/driverapi"
	"github.com/docker/libnetwork/netlabel"
	"github.com/docker/libnetwork/ns"
	"github.com/docker/libnetwork/options"
	"github.com/docker/libnetwork/osl"
	"github.com/docker/libnetwork/types"
	"github.com/sirupsen/logrus"
)

// CreateNetwork the network for the specified driver type
func (d *driver) CreateNetwork(nid string, option map[string]interface{}, nInfo driverapi.NetworkInfo, ipV4Data, ipV6Data []driverapi.IPAMData) error {
	defer osl.InitOSContext()()
	kv, err := kernel.GetKernelVersion()
	if err != nil {
		return fmt.Errorf("Failed to check kernel version for %s driver support: %v", ipvlanType, err)
	}
	// ensure Kernel version is >= v4.2 for ipvlan support
	if kv.Kernel < ipvlanKernelVer || (kv.Kernel == ipvlanKernelVer && kv.Major < ipvlanMajorVer) {
		return fmt.Errorf("kernel version failed to meet the minimum ipvlan kernel requirement of %d.%d, found %d.%d.%d",
			ipvlanKernelVer, ipvlanMajorVer, kv.Kernel, kv.Major, kv.Minor)
	}
	// reject a null v4 network
	if len(ipV4Data) == 0 || ipV4Data[0].Pool.String() == "0.0.0.0/0" {
		return fmt.Errorf("ipv4 pool is empty")
	}
	// parse and validate the config and bind to networkConfiguration
	config, err := parseNetworkOptions(nid, option)
	if err != nil {
		return err
	}
	config.ID = nid
	err = config.processIPAM(nid, ipV4Data, ipV6Data)
	if err != nil {
		return err
	}
	// verify the ipvlan mode from -o ipvlan_mode option
	switch config.IpvlanMode {
	case "", modeL2:
		// default to ipvlan L2 mode if -o ipvlan_mode is empty
		config.IpvlanMode = modeL2
	case modeL3:
		config.IpvlanMode = modeL3
	default:
		return fmt.Errorf("requested ipvlan mode '%s' is not valid, 'l2' mode is the ipvlan driver default", config.IpvlanMode)
	}
	// loopback is not a valid parent link
	if config.Parent == "lo" {
		return fmt.Errorf("loopback interface is not a valid %s parent link", ipvlanType)
	}
	// if parent interface not specified, create a dummy type link to use named dummy+net_id
	if config.Parent == "" {
		config.Parent = getDummyName(stringid.TruncateID(config.ID))
		// empty parent and --internal are handled the same. Set here to update k/v
		config.Internal = true
	}
	err = d.createNetwork(config)
	if err != nil {
		return err
	}
	// update persistent db, rollback on fail
	err = d.storeUpdate(config)
	if err != nil {
		d.deleteNetwork(config.ID)
		logrus.Debugf("encountered an error rolling back a network create for %s : %v", config.ID, err)
		return err
	}

	return nil
}

// createNetwork is used by new network callbacks and persistent network cache
func (d *driver) createNetwork(config *configuration) error {
	networkList := d.getNetworks()
	for _, nw := range networkList {
		if config.Parent == nw.config.Parent {
			return fmt.Errorf("network %s is already using parent interface %s",
				getDummyName(stringid.TruncateID(nw.config.ID)), config.Parent)
		}
	}
	if !parentExists(config.Parent) {
		// if the --internal flag is set, create a dummy link
		if config.Internal {
			err := createDummyLink(config.Parent, getDummyName(stringid.TruncateID(config.ID)))
			if err != nil {
				return err
			}
			config.CreatedSlaveLink = true
			// notify the user in logs they have limited communications
			if config.Parent == getDummyName(stringid.TruncateID(config.ID)) {
				logrus.Debugf("Empty -o parent= and --internal flags limit communications to other containers inside of network: %s",
					config.Parent)
			}
		} else {
			// if the subinterface parent_iface.vlan_id checks do not pass, return err.
			//  a valid example is 'eth0.10' for a parent iface 'eth0' with a vlan id '10'
			err := createVlanLink(config.Parent)
			if err != nil {
				return err
			}
			// if driver created the networks slave link, record it for future deletion
			config.CreatedSlaveLink = true
		}
	}
	n := &network{
		id:        config.ID,
		driver:    d,
		endpoints: endpointTable{},
		config:    config,
	}
	// add the *network
	d.addNetwork(n)

	return nil
}

// DeleteNetwork the network for the specified driver type
func (d *driver) DeleteNetwork(nid string) error {
	defer osl.InitOSContext()()
	n := d.network(nid)
	if n == nil {
		return fmt.Errorf("network id %s not found", nid)
	}
	// if the driver created the slave interface, delete it, otherwise leave it
	if ok := n.config.CreatedSlaveLink; ok {
		// if the interface exists, only delete if it matches iface.vlan or dummy.net_id naming
		if ok := parentExists(n.config.Parent); ok {
			// only delete the link if it is named the net_id
			if n.config.Parent == getDummyName(stringid.TruncateID(nid)) {
				err := delDummyLink(n.config.Parent)
				if err != nil {
					logrus.Debugf("link %s was not deleted, continuing the delete network operation: %v",
						n.config.Parent, err)
				}
			} else {
				// only delete the link if it matches iface.vlan naming
				err := delVlanLink(n.config.Parent)
				if err != nil {
					logrus.Debugf("link %s was not deleted, continuing the delete network operation: %v",
						n.config.Parent, err)
				}
			}
		}
	}
	for _, ep := range n.endpoints {
		if link, err := ns.NlHandle().LinkByName(ep.srcName); err == nil {
			if err := ns.NlHandle().LinkDel(link); err != nil {
				logrus.WithError(err).Warnf("Failed to delete interface (%s)'s link on endpoint (%s) delete", ep.srcName, ep.id)
			}
		}

		if err := d.storeDelete(ep); err != nil {
			logrus.Warnf("Failed to remove ipvlan endpoint %.7s from store: %v", ep.id, err)
		}
	}
	// delete the *network
	d.deleteNetwork(nid)
	// delete the network record from persistent cache
	err := d.storeDelete(n.config)
	if err != nil {
		return fmt.Errorf("error deleting deleting id %s from datastore: %v", nid, err)
	}
	return nil
}

// parseNetworkOptions parse docker network options
func parseNetworkOptions(id string, option options.Generic) (*configuration, error) {
	var (
		err    error
		config = &configuration{}
	)
	// parse generic labels first
	if genData, ok := option[netlabel.GenericData]; ok && genData != nil {
		if config, err = parseNetworkGenericOptions(genData); err != nil {
			return nil, err
		}
	}
	// setting the parent to "" will trigger an isolated network dummy parent link
	if val, ok := option[netlabel.Internal]; ok {
		if internal, ok := val.(bool); ok && internal {
			config.Internal = true
			// empty --parent= and --internal are handled the same.
			config.Parent = ""
		}
	}
	return config, nil
}

// parseNetworkGenericOptions parse generic driver docker network options
func parseNetworkGenericOptions(data interface{}) (*configuration, error) {
	var (
		err    error
		config *configuration
	)
	switch opt := data.(type) {
	case *configuration:
		config = opt
	case map[string]string:
		config = &configuration{}
		err = config.fromOptions(opt)
	case options.Generic:
		var opaqueConfig interface{}
		if opaqueConfig, err = options.GenerateFromModel(opt, config); err == nil {
			config = opaqueConfig.(*configuration)
		}
	default:
		err = types.BadRequestErrorf("unrecognized network configuration format: %v", opt)
	}
	return config, err
}

// fromOptions binds the generic options to networkConfiguration to cache
func (config *configuration) fromOptions(labels map[string]string) error {
	for label, value := range labels {
		switch label {
		case parentOpt:
			// parse driver option '-o parent'
			config.Parent = value
		case driverModeOpt:
			// parse driver option '-o ipvlan_mode'
			config.IpvlanMode = value
		}
	}
	return nil
}

// processIPAM parses v4 and v6 IP information and binds it to the network configuration
func (config *configuration) processIPAM(id string, ipamV4Data, ipamV6Data []driverapi.IPAMData) error {
	if len(ipamV4Data) > 0 {
		for _, ipd := range ipamV4Data {
			s := &ipv4Subnet{
				SubnetIP: ipd.Pool.String(),
				GwIP:     ipd.Gateway.String(),
			}
			config.Ipv4Subnets = append(config.Ipv4Subnets, s)
		}
	}
	if len(ipamV6Data) > 0 {
		for _, ipd := range ipamV6Data {
			s := &ipv6Subnet{
				SubnetIP: ipd.Pool.String(),
				GwIP:     ipd.Gateway.String(),
			}
			config.Ipv6Subnets = append(config.Ipv6Subnets, s)
		}
	}
	return nil
}
<|endoftext|>