def _create(self, app_spec, selector, labels): LOG.info("Creating/updating service for %s with labels: %s", app_spec.name, labels) ports = [ self._make_service_port(port_spec) for port_spec in app_spec.ports ] try: svc = Service.get(app_spec.name, app_spec.namespace) ports = self._merge_ports(svc.spec.ports, ports) except NotFound: pass service_name = app_spec.name custom_labels = merge_dicts(app_spec.labels.service, labels) custom_annotations = merge_dicts( app_spec.annotations.service, self._make_tcp_port_annotation(app_spec)) metadata = ObjectMeta(name=service_name, namespace=app_spec.namespace, labels=custom_labels, annotations=custom_annotations) spec = ServiceSpec(selector=selector, ports=ports, type=self._service_type) svc = Service.get_or_create(metadata=metadata, spec=spec) self._owner_references.apply(svc, app_spec) svc.save()
def test_get_or_create_service_not_new(self, put, get): service = create_default_service() mock_response = mock.Mock() mock_response.json.return_value = { "kind": "Service", "apiVersion": "v1", "metadata": { "name": SERVICE_NAME, "namespace": SERVICE_NAMESPACE, "selfLink": "/api/v1/namespaces/" + SERVICE_NAMESPACE + "/services/my-name", "uid": "cc562581-cbf5-11e5-b6ef-247703d2e388", "resourceVersion": "817", "creationTimestamp": "2016-02-05T10:47:06Z", "labels": { "app": "test" }, }, "spec": { "ports": [ { "name": "my-port", "protocol": "TCP", "port": 80, "targetPort": "name" } ], "clusterIP": "10.0.0.54", "type": "ClusterIP", "sessionAffinity": "None" }, "status": { "loadBalancer": {} } } get.return_value = mock_response metadata = ObjectMeta(name=SERVICE_NAME, namespace=SERVICE_NAMESPACE, labels={"app": "test"}) port = ServicePort(name="my-port", port=80, targetPort="name") spec = ServiceSpec(ports=[port]) from_api = Service.get_or_create(metadata=metadata, spec=spec) assert not from_api._new assert from_api.metadata.labels assert from_api.metadata.name == service.metadata.name call_params = from_api.as_dict() put.return_value.json.return_value = call_params from_api.save() pytest.helpers.assert_any_call(put, SERVICES_URI + SERVICE_NAME, call_params)