// ConvertToNetworkPolicy converts a *networkingv1.NetworkPolicy into a
// *types.NetworkPolicy
761694
func ConvertToNetworkPolicy(obj interface{}) interface{} {
	netPol, ok := obj.(*networkingv1.NetworkPolicy)
	if !ok {
		return nil
	}
	// TODO check which fields we really need
	return &types.NetworkPolicy{
		NetworkPolicy: netPol,
	}
}
1033119
func (r *CiliumNetworkPolicy) GetPolicyStatus(nodeName string) CiliumNetworkPolicyNodeStatus {
	if r.Status.Nodes == nil {
		return CiliumNetworkPolicyNodeStatus{}
	}
	return r.Status.Nodes[nodeName]
}
388669
func Convert_v1beta1_PodDisruptionBudgetStatus_To_policy_PodDisruptionBudgetStatus(in *v1beta1.PodDisruptionBudgetStatus, out *policy.PodDisruptionBudgetStatus, s conversion.Scope) error {
	return autoConvert_v1beta1_PodDisruptionBudgetStatus_To_policy_PodDisruptionBudgetStatus(in, out, s)
}
1363158
func (network *HostComputeNetwork) RemovePolicy(networkPolicy PolicyNetworkRequest) error {
	logrus.Debugf("hcn::HostComputeNetwork::RemovePolicy id=%s", network.Id)

	settingsJson, err := json.Marshal(networkPolicy)
	if err != nil {
		return err
	}
	requestMessage := &ModifyNetworkSettingRequest{
		ResourceType: NetworkResourceTypePolicy,
		RequestType:  RequestTypeRemove,
		Settings:     settingsJson,
	}

	return network.ModifyNetworkSettings(requestMessage)
}
141919
func ConvertWorkItem(request *http.Request, wit workitem.WorkItemType, wi workitem.WorkItem, additional ...WorkItemConvertFunc) (*app.WorkItem, error) {
	// construct default values from input WI
	relatedURL := rest.AbsoluteURL(request, app.WorkitemHref(wi.ID))
	labelsRelated := relatedURL + "/labels"
	workItemLinksRelated := relatedURL + "/links"

	op := &app.WorkItem{
		ID:   &wi.ID,
		Type: APIStringTypeWorkItem,
		Attributes: map[string]interface{}{
			workitem.SystemVersion: wi.Version,
			workitem.SystemNumber:  wi.Number,
		},
		Relationships: &app.WorkItemRelationships{
			BaseType: &app.RelationBaseType{
				Data: &app.BaseTypeData{
					ID:   wi.Type,
					Type: APIStringTypeWorkItemType,
				},
				Links: &app.GenericLinks{
					Self: ptr.String(rest.AbsoluteURL(request, app.WorkitemtypeHref(wi.Type))),
				},
			},
			Space: app.NewSpaceRelation(wi.SpaceID, rest.AbsoluteURL(request, app.SpaceHref(wi.SpaceID.String()))),
			WorkItemLinks: &app.RelationGeneric{
				Links: &app.GenericLinks{
					Related: &workItemLinksRelated,
				},
			},
		},
		Links: &app.GenericLinksForWorkItem{
			Self:    &relatedURL,
			Related: &relatedURL,
		},
	}

	// Move fields into Relationships or Attributes as needed
	// TODO(kwk): Loop based on WorkItemType and match against Field.Type instead of directly to field value
	for name, val := range wi.Fields {
		switch name {
		case workitem.SystemAssignees:
			if val != nil {
				userID := val.([]interface{})
				op.Relationships.Assignees = &app.RelationGenericList{
					Data: ConvertUsersSimple(request, userID),
				}
			}
		case workitem.SystemLabels:
			if val != nil {
				labelIDs := val.([]interface{})
				op.Relationships.Labels = &app.RelationGenericList{
					Data: ConvertLabelsSimple(request, labelIDs),
					Links: &app.GenericLinks{
						Related: &labelsRelated,
					},
				}
			}
		case workitem.SystemBoardcolumns:
			if val != nil {
				columnIDs := val.([]interface{})
				op.Relationships.Boardcolumns = &app.RelationGenericList{
					Data: ConvertBoardColumnsSimple(request, columnIDs),
				}
			}
		case workitem.SystemCreator:
			if val != nil {
				userID := val.(string)
				data, links := ConvertUserSimple(request, userID)
				op.Relationships.Creator = &app.RelationGeneric{
					Data:  data,
					Links: links,
				}
			}
		case workitem.SystemIteration:
			if val != nil {
				valStr := val.(string)
				data, links := ConvertIterationSimple(request, valStr)
				op.Relationships.Iteration = &app.RelationGeneric{
					Data:  data,
					Links: links,
				}
			}
		case workitem.SystemArea:
			if val != nil {
				valStr := val.(string)
				data, links := ConvertAreaSimple(request, valStr)
				op.Relationships.Area = &app.RelationGeneric{
					Data:  data,
					Links: links,
				}
			}

		case workitem.SystemTitle:
			// 'HTML escape' the title to prevent script injection
			op.Attributes[name] = html.EscapeString(val.(string))
		case workitem.SystemDescription:
			description := rendering.NewMarkupContentFromValue(val)
			if description != nil {
				op.Attributes[name] = (*description).Content
				op.Attributes[workitem.SystemDescriptionMarkup] = (*description).Markup
				op.Attributes[workitem.SystemDescriptionRendered] = rendering.RenderMarkupToHTML((*description).Content, (*description).Markup)
			}
		case workitem.SystemCodebase:
			if val != nil {
				op.Attributes[name] = val
				// TODO: Following format is TBD and hence commented out
				cb := val.(codebase.Content)
				editURL := rest.AbsoluteURL(request, app.CodebaseHref(cb.CodebaseID)+"/edit")
				op.Links.EditCodebase = &editURL
			}
		default:
			op.Attributes[name] = val
		}
	}
	if op.Relationships.Assignees == nil {
		op.Relationships.Assignees = &app.RelationGenericList{Data: nil}
	}
	if op.Relationships.Iteration == nil {
		op.Relationships.Iteration = &app.RelationGeneric{Data: nil}
	}
	if op.Relationships.Area == nil {
		op.Relationships.Area = &app.RelationGeneric{Data: nil}
	}
	// Always include Comments Link, but optionally use workItemIncludeCommentsAndTotal
	workItemIncludeComments(request, &wi, op)
	workItemIncludeChildren(request, &wi, op)
	workItemIncludeEvents(request, &wi, op)
	for _, add := range additional {
		if err := add(request, &wi, op); err != nil {
			return nil, errs.Wrap(err, "failed to run additional conversion function")
		}
	}
	return op, nil
}
251566
func Convert_v1beta1_RunAsGroupStrategyOptions_To_policy_RunAsGroupStrategyOptions(in *v1beta1.RunAsGroupStrategyOptions, out *policy.RunAsGroupStrategyOptions, s conversion.Scope) error {
	return autoConvert_v1beta1_RunAsGroupStrategyOptions_To_policy_RunAsGroupStrategyOptions(in, out, s)
}
57231
func Convert_v1_NetworkPolicyEgressRule_To_networking_NetworkPolicyEgressRule(in *v1.NetworkPolicyEgressRule, out *networking.NetworkPolicyEgressRule, s conversion.Scope) error {
	return autoConvert_v1_NetworkPolicyEgressRule_To_networking_NetworkPolicyEgressRule(in, out, s)
}
1126373
func Convert_v1_ClusterNetwork_To_network_ClusterNetwork(in *v1.ClusterNetwork, out *network.ClusterNetwork, s conversion.Scope) error {
	return autoConvert_v1_ClusterNetwork_To_network_ClusterNetwork(in, out, s)
}
293214
func encodePolicy(p *Policy) (b64Policy, jsonPolicy []byte, err error) {
	jsonPolicy, err = encodePolicyJSON(p)
	if err != nil {
		return nil, nil, fmt.Errorf("failed to encode policy, %s", err.Error())
	}
	// Remove leading and trailing white space, JSON encoding will note include
	// whitespace within the encoding.
	jsonPolicy = bytes.TrimSpace(jsonPolicy)

	b64Policy = make([]byte, base64.StdEncoding.EncodedLen(len(jsonPolicy)))
	base64.StdEncoding.Encode(b64Policy, jsonPolicy)
	return b64Policy, jsonPolicy, nil
}
841503
func (d *Daemon) UpdateNetworkPolicy(e *endpoint.Endpoint, policy *policy.L4Policy,
	labelsMap, deniedIngressIdentities, deniedEgressIdentities cache.IdentityCache, proxyWaitGroup *completion.WaitGroup) (error, revert.RevertFunc) {
	if d.l7Proxy == nil {
		return fmt.Errorf("can't update network policy, proxy disabled"), nil
	}
	err, revertFunc := d.l7Proxy.UpdateNetworkPolicy(e, policy, e.GetIngressPolicyEnabledLocked(), e.GetEgressPolicyEnabledLocked(),
		labelsMap, deniedIngressIdentities, deniedEgressIdentities, proxyWaitGroup)
	return err, revert.RevertFunc(revertFunc)
}
996139
func Convert_v1alpha1_ImageReviewStatus_To_imagepolicy_ImageReviewStatus(in *v1alpha1.ImageReviewStatus, out *imagepolicy.ImageReviewStatus, s conversion.Scope) error {
	return autoConvert_v1alpha1_ImageReviewStatus_To_imagepolicy_ImageReviewStatus(in, out, s)
}
907411
func ParseNetworkPolicy(np *networkingv1.NetworkPolicy) (api.Rules, error) {

	if np == nil {
		return nil, fmt.Errorf("cannot parse NetworkPolicy because it is nil")
	}

	ingresses := []api.IngressRule{}
	egresses := []api.EgressRule{}

	namespace := k8sUtils.ExtractNamespace(&np.ObjectMeta)

	for _, iRule := range np.Spec.Ingress {
		ingress := api.IngressRule{}

		if iRule.Ports != nil && len(iRule.Ports) > 0 {
			ingress.ToPorts = parsePorts(iRule.Ports)
		}

		if iRule.From != nil && len(iRule.From) > 0 {
			for _, rule := range iRule.From {
				endpointSelector := parseNetworkPolicyPeer(namespace, &rule)

				if endpointSelector != nil {
					ingress.FromEndpoints = append(ingress.FromEndpoints, *endpointSelector)
				} else {
					// No label-based selectors were in NetworkPolicyPeer.
					log.WithField(logfields.K8sNetworkPolicyName, np.Name).Debug("NetworkPolicyPeer does not have PodSelector or NamespaceSelector")
				}

				// Parse CIDR-based parts of rule.
				if rule.IPBlock != nil {
					ingress.FromCIDRSet = append(ingress.FromCIDRSet, ipBlockToCIDRRule(rule.IPBlock))
				}
			}
		} else {
			// Based on NetworkPolicyIngressRule docs:
			//   From []NetworkPolicyPeer
			//   If this field is empty or missing, this rule matches all
			//   sources (traffic not restricted by source).
			all := api.NewESFromLabels(
				labels.NewLabel(labels.IDNameAll, "", labels.LabelSourceReserved),
			)
			ingress.FromEndpoints = append(ingress.FromEndpoints, all)
		}

		ingresses = append(ingresses, ingress)
	}

	for _, eRule := range np.Spec.Egress {
		egress := api.EgressRule{}

		if eRule.To != nil && len(eRule.To) > 0 {
			for _, rule := range eRule.To {
				if rule.NamespaceSelector != nil || rule.PodSelector != nil {
					endpointSelector := parseNetworkPolicyPeer(namespace, &rule)

					if endpointSelector != nil {
						egress.ToEndpoints = append(egress.ToEndpoints, *endpointSelector)
					} else {
						log.WithField(logfields.K8sNetworkPolicyName, np.Name).Debug("NetworkPolicyPeer does not have PodSelector or NamespaceSelector")
					}
				}
				if rule.IPBlock != nil {
					egress.ToCIDRSet = append(egress.ToCIDRSet, ipBlockToCIDRRule(rule.IPBlock))
				}
			}
		} else {
			// []To is wildcard
			all := api.NewESFromLabels(
				labels.NewLabel(labels.IDNameAll, "", labels.LabelSourceReserved),
			)
			egress.ToEndpoints = append(egress.ToEndpoints, all)
		}

		if eRule.Ports != nil && len(eRule.Ports) > 0 {
			egress.ToPorts = parsePorts(eRule.Ports)
		} else if eRule.To == nil || len(eRule.To) == 0 {
			// Based on NetworkPolicyEgressRule docs:
			//   From []NetworkPolicyPeer
			//   If this field is empty or missing, this rule matches all
			//   sources (traffic not restricted by source).
			all := api.NewESFromLabels(
				labels.NewLabel(labels.IDNameAll, "", labels.LabelSourceReserved),
			)
			egress.ToEndpoints = append(egress.ToEndpoints, all)
		}

		egresses = append(egresses, egress)
	}

	// Convert the k8s default-deny model to the Cilium default-deny model
	//spec:
	//  podSelector: {}
	//  policyTypes:
	//	  - Ingress
	// Since k8s 1.7 doesn't contain any PolicyTypes, we default deny
	// if podSelector is empty and the policyTypes is not egress
	if len(ingresses) == 0 &&
		(hasV1PolicyType(np.Spec.PolicyTypes, networkingv1.PolicyTypeIngress) ||
			!hasV1PolicyType(np.Spec.PolicyTypes, networkingv1.PolicyTypeEgress)) {
		ingresses = []api.IngressRule{{}}
	}

	// Convert the k8s default-deny model to the Cilium default-deny model
	//spec:
	//  podSelector: {}
	//  policyTypes:
	//	  - Egress
	if len(egresses) == 0 && hasV1PolicyType(np.Spec.PolicyTypes, networkingv1.PolicyTypeEgress) {
		egresses = []api.EgressRule{{}}
	}

	if np.Spec.PodSelector.MatchLabels == nil {
		np.Spec.PodSelector.MatchLabels = map[string]string{}
	}
	np.Spec.PodSelector.MatchLabels[k8sConst.PodNamespaceLabel] = namespace

	// The next patch will pass the UID.
	rule := api.NewRule().
		WithEndpointSelector(api.NewESFromK8sLabelSelector(labels.LabelSourceK8sKeyPrefix, &np.Spec.PodSelector)).
		WithLabels(GetPolicyLabelsv1(np)).
		WithIngressRules(ingresses).
		WithEgressRules(egresses)

	if err := rule.Sanitize(); err != nil {
		return nil, err
	}

	return api.Rules{rule}, nil
}
311330
func NewPolicy(config PolicyConfig) *Policy {
	return &Policy{
		l:                    new(sync.RWMutex),
		Name:                 config.Name,
		Type:                 config.Type,
		Derived:              config.Derived,
		KDF:                  config.KDF,
		ConvergentEncryption: config.ConvergentEncryption,
		ConvergentVersion:    -1,
		Exportable:           config.Exportable,
		DeletionAllowed:      config.DeletionAllowed,
		AllowPlaintextBackup: config.AllowPlaintextBackup,
		VersionTemplate:      config.VersionTemplate,
		StoragePrefix:        config.StoragePrefix,
	}
}
1007991
func (j *AuroraJob) PartitionPolicy(policy *aurora.PartitionPolicy) Job {
	j.jobConfig.TaskConfig.PartitionPolicy = policy
	return j
}
324760
func Convert_policy_PodSecurityPolicy_To_v1beta1_PodSecurityPolicy(in *policy.PodSecurityPolicy, out *v1beta1.PodSecurityPolicy, s conversion.Scope) error {
	return autoConvert_policy_PodSecurityPolicy_To_v1beta1_PodSecurityPolicy(in, out, s)
}
1008820
func Convert_v1_ClusterNetworkList_To_network_ClusterNetworkList(in *v1.ClusterNetworkList, out *network.ClusterNetworkList, s conversion.Scope) error {
	return autoConvert_v1_ClusterNetworkList_To_network_ClusterNetworkList(in, out, s)
}
666306
func (v *version) NetworkPolicies() NetworkPolicyInformer {
	return &networkPolicyInformer{factory: v.factory, namespace: v.namespace, tweakListOptions: v.tweakListOptions}
}