def delete(self, service_id): args = self.parser.parse_args() common_users_not_authorized(args['Authorization']) s = Service().query.get_or_404(service_id) if s is not None: s.remove() return '', 204
def test_iter_match_fail(self): s = Service(Context(http = MockHttp(HTTP_SRC_DIR), service = "http://example.org/service.atomsvc")) try: s.iter_match('image/png').next() self.fail("StopIteration should have been raised.") except StopIteration: pass
def test_get(self): c = Context() c.service = "http://example.org/service.atomsvc" c.http = MockHttp(HTTP_SRC_DIR) s = Service(c) headers, body = s.get() self.assertEqual(headers["status"], "200") self.assertEqual(s.uri(), "http://example.org/service.atomsvc")
def create_service(name,desc) : try : session = Session() new_service = Service(name,desc) service_id = new_service.save_return_id(session) return {"status":0 , "val":service_id} except Exception , msginfo : return {"status":-1 , "val":msginfo}
def calculate_usage_cost(self, usages): from model import Service, Category, ServicePrice from task.notifications import notify_managers_about_new_service_in_tariff total_cost = Decimal() tariff = self.tariff if not tariff: raise Exception("Tariff is not set for customer %s" % self) services = tariff.services_as_dict(lower=True) for usage in usages: db.session.add(usage) service_id = usage.service_id.lower() if isinstance(usage.service_id, str) else str(usage.service_id) service_price = services.get(service_id) service = Service.get_by_id(service_id) usage.tariff_id = tariff.tariff_id usage.customer_mode = self.customer_mode if service is None: logbook.error("Not found declaration service {} during calculate usage for {}", usage.service_id, self) continue usage_volume = service.calculate_volume_usage(usage) usage.usage_volume = usage_volume if service_price is None: if service.category_id == Category.VM: if service.deleted: logbook.error("Service {} not found in {} for {}. But this service is archived", service_id, tariff, self) else: service_price = ServicePrice(service_id=service_id, price=Decimal(0), need_changing=True) self.tariff.services.append(service_price) services = tariff.services_as_dict(lower=True) flavor_name = Service.get_by_id(service_id).flavor.flavor_id notify_managers_about_new_service_in_tariff.delay(self.customer_id, flavor_name) else: logbook.warning("Service {} not found in {} for {}. Allowed services: {}", service_id, tariff, self, services.keys()) if service_price: usage_cost = usage_volume * service_price.price / service.hours else: usage_cost = Decimal(0) total_cost += usage_cost usage.cost = usage_cost logbook.info("Found {} usages for customer {}. Total cost of used resources is: {}", len(usages), self, total_cost) return total_cost
def test_for_nonexistent_flavor(self): """ Tests that transformer doesn't stop when flavor.name isn't in database and creates fake entry in DB for that flavor. """ state = [ {'timestamp': testdata.t0, 'counter_volume': states['active'], 'metadata': {'flavor.name': testdata.flavor}}, {'timestamp': testdata.t0_30, 'counter_volume': states['active'], 'metadata': {'flavor.name': testdata.fake_flavor}}, {'timestamp': testdata.t1, 'counter_volume': states['active'], 'metadata': {'flavor.name': testdata.fake_flavor}} ] with mock.patch('os_interfaces.openstack_wrapper.openstack.get_nova_flavor', mock.MagicMock(side_effect=self.create_flavor_mock)): result = self._run_transform(state) result.sort(key=attrgetter("service_id")) flavor = Service.get_by_id(result[1].service_id).flavor self.assertEqual(flavor.flavor_id, testdata.fake_flavor) self.assertEqual(openstack.get_nova_flavor.call_count, 1) self.assertEqual(openstack.create_flavor.call_count, 10) self.assertEqual(result[1].end - result[1].start, datetime.timedelta(minutes=30, seconds=-1))
def get_service(self, service_id): service = self.services.get(service_id) if not service: service = Service.get_by_id(service_id) if not service: raise ValueError("Service %s not found" % service_id) return service
def load_clinics(file_rows): """Load clinics into database""" print("Clinics") # Delete all rows in table, so if we need to run this a second time, # we won't be trying to add duplicate users # Clinic.query.delete() # Read file_rows and insert data for row in file_rows[1:]: # unpack part of each row clinic_id, clinic_name, city, state, director = row[:5] fresh_mul_1, fresh_mul_2, fresh_mul_3, fresh_mul_4, fresh_mul_5= map(convert_to_float, row[5:10]) fresh_sin_1, fresh_sin_2, fresh_sin_3, fresh_sin_4, fresh_sin_5 = map(convert_to_float, row[10:15]) fro_mul_1, fro_mul_2, fro_mul_3, fro_mul_4, fro_mul_5 = map(convert_to_float, row[15:20]) fro_sin_1, fro_sin_2, fro_sin_3, fro_sin_4, fro_sin_5 = map(convert_to_float, row[20:25]) is_sart, is_surrogates, is_single, is_eggcryo, is_embryocryo, is_donor_emb, is_donor_egg = row[-3:-10:-1] clinic = Clinic(clinic_name=clinic_name, city=city, state=state, director=director) rate = Rate(fresh_mul_1=fresh_mul_1, fresh_mul_2=fresh_mul_2, fresh_mul_3=fresh_mul_3, fresh_mul_4=fresh_mul_4, fresh_mul_5=fresh_mul_5, fresh_sin_1=fresh_sin_1, fresh_sin_2=fresh_sin_2, fresh_sin_3=fresh_sin_3, fresh_sin_4=fresh_sin_4, fresh_sin_5=fresh_sin_5, fro_mul_1=fro_mul_1, fro_mul_2=fro_mul_2, fro_mul_3=fro_mul_3, fro_mul_4=fro_mul_4, fro_mul_5=fro_mul_5, fro_sin_1=fro_sin_1, fro_sin_2=fro_sin_2, fro_sin_3=fro_sin_3, fro_sin_4=fro_sin_4, fro_sin_5=fro_sin_5) service = Service(is_sart=is_sart, is_surrogates=is_surrogates, is_single=is_single, is_eggcryo=is_eggcryo, is_embryocryo=is_embryocryo, is_donor_emb=is_donor_emb, is_donor_egg=is_donor_egg) rate.clinic = clinic db.session.add(clinic) service.clinic = clinic # add to the session or it won't ever be stored db.session.add(service) # Once done, commit db.session.commit()
def list(self, name=None, category=None, page=1, limit=conf.api.pagination.limit, sort=None, visibility=Visibility.DEFAULT, all_parameters=True): """ Return filtered list of services. :param str name: Filter for service name :param str category: Filter :param int page: page number :param int limit: number of items per page :param str visibility: Visibility options *visible* - Only active services, [by default] *deleted* - Only removed services. *all* - All services. :return List service_list: List of services **Example**:: { "service_list": { "total": 20, "per_page": 1, "page": 1, "items": [ { "service_id":"net.associated_ip", "localized_name":{ "ru":"net.associated_ip", "en":"net.associated_ip" }, "measure":{ "measure_id":"hour", "localized_name":{ "ru":"\u0447\u0430\u0441", "en":"hour" }, "measure_type":"time" }, "category":{ "localized_name":{ "ru":"\u0421\u0435\u0442\u044c", "en":"Network" }, "category_id":"net" } } ] } } """ if category: category = frozenset(category) services = Service.list(only_categories=category, visibility=visibility) return {"service_list": self.paginate_services(services, limit, page)}
def handle_unknown_flavor(flavor_name): flavor = openstack.get_nova_flavor(name=flavor_name) service = Service.create_vm( {'en': 'Public Flavor %s' % flavor_name, 'ru': 'Публичный Флавор %s' % flavor_name}, flavor_info={'flavor_id': flavor_name, 'vcpus': flavor.vcpus, 'ram': flavor.ram, 'disk': flavor.disk, 'network': 0}, mutable=False ) flavor_id = service.service_id return flavor_id
def test_create_flavor(self): service_id = self.admin_client.service.create_vm(**self.new_flavor_info)['service_id'] with self.expect_error(errors.ServiceAlreadyExisted): self.admin_client.service.create_vm(**self.new_flavor_info) self.new_flavor_info['localized_name'] = '{"ru": "Флавор Test Flavor", "en": "Flavor Test Flavor"}' with self.expect_error(errors.FlavorAlreadyExists): self.admin_client.service.create_vm(**self.new_flavor_info) self.assertEqual(openstack.create_flavor.call_count, 10) service = Service.get_by_id(service_id) service.mark_immutable() self.assertEqual(openstack.create_flavor.call_count, 11) self.new_flavor_info['localized_name'] = '{"ru": "Флавор TestFlavor1", "en": "Flavor TestFlavor1"}' self.new_flavor_info['flavor_id'] = "TestFlavor1" self.new_flavor_info.pop('network') service_id = self.admin_client.service.create_vm(**self.new_flavor_info)['service_id'] service = Service.get_by_id(service_id) self.assertIsNone(service.flavor.network) with mock.patch('os_interfaces.openstack_wrapper.openstack.get_nova_flavor', mock.MagicMock(side_effect=self.create_flavor_mock)): self.new_flavor_info['localized_name'] = '{"ru": "Флавор TestFlavor2", "en": "Flavor TestFlavor2"}' self.new_flavor_info['flavor_id'] = "TestFlavor2" with self.expect_error(errors.Conflict): service_id = self.admin_client.service.create_vm(**self.new_flavor_info)['service_id'] self.new_flavor_info['disk'] = 30 service_id = self.admin_client.service.create_vm(**self.new_flavor_info)['service_id'] service = Service.get_by_id(service_id) self.assertFalse(service.mutable)
def new_vm(self, flavor_id, vcpus, ram, disk, localized_name, network=None, description=None): """ Add new flavor service. Parameters must be sent as json object. :param LocalizedName localized_name: Dict with name localization. en is mandatory key ``{"en": "Name", "ru": "\u0418\u043c\u044f"}`` :param LocalizedName description: Dict with localized description. (Not mandatory) :param flavor_id: Flavor name :param vcpus: Number of flavor's vcpus :param ram: flavor's RAM amount :param disk: flavor's disk size :param network: flavor's network **Example**:: {"service_info": { "mutable": true, "localized_name": { "ru": "\u0424\u043b\u0430\u0432\u043e\u0440 TestFlavor", "en": "Flavor TestFlavor" }, "deleted": null, "measure": { "localized_name": { "ru": "\u0447\u0430\u0441", "en": "hour" }, "measure_type": "time", "measure_id": "hour" }, "category": { "localized_name": { "ru": "\u0412\u0438\u0440\u0442\u0443\u0430\u043b\u044c\u043d\u044b\u0435 \u043c\u0430\u0448\u0438\u043d\u044b", "en": "Virtual server" }, "category_id": "vm" }, "service_id": 1, "description": {} } } """ flavor_info = dict(flavor_id=flavor_id, vcpus=vcpus, ram=ram, disk=disk, network=network) mutable = True if self.check_flavor_existence(flavor_info): mutable = False flavor = Service.create_vm(localized_name, description, flavor_info, mutable) return {"service_info": display(flavor)}
def __call__(self, value): service_price_list = super().__call__(value) for service_price in service_price_list: service_id = service_price.get("service_id") service = Service.get_by_id(service_id) if not service: raise errors.ServiceNotFound() if service.deleted: raise errors.RemovedServiceInTariff() if service.mutable: raise errors.OnlyImmutableService() return service_price_list
def clearbase(bot, update): uid = update.message.from_user.id if uid not in ADMINS: return try: Company.drop_table() Company.create_table() Service.drop_table() Service.create_table() Good.drop_table() Good.create_table() Aliases.drop_table() Aliases.create_table() except: bot.send_message( uid, 'Что-то пошло не так. Не все таблицы очищены', ) return bot.send_message(uid, 'Таблицу очистил')
def load_services(): """Loads services from services.txt""" print "Services" #prevents adding duplicate entries when the file is rerun Service.query.delete() #read file and insert data for row in open('seed_data/services.txt'): name, yelp_code, picture = row.rstrip().split("|") service = Service(name=name, yelp_code=yelp_code, picture=picture) db.session.add(service) db.session.commit()
def __init__(self, service_id, customer, tariff): self.currency = tariff.currency self.service = Service.get_by_id(service_id) if self.service: self.name = self.service.get_localized_name(customer.locale_language()) self.category = self.service.category.get_localized_name(customer.locale_language()) self.measure = self.service.measure.get_localized_name(customer.locale_language()) self.hours = self.service.hours else: self.name = str(service_id) self.category = "" self.measure = "" self.hours = 1 self.price = tariff.service_price(service_id) self.service_id = service_id self.resources = {}
def handle_unknown_flavor(flavor_name): flavor = openstack.get_nova_flavor(name=flavor_name) service = Service.create_vm( { 'en': 'Public Flavor %s' % flavor_name, 'ru': 'Публичный Флавор %s' % flavor_name }, flavor_info={ 'flavor_id': flavor_name, 'vcpus': flavor.vcpus, 'ram': flavor.ram, 'disk': flavor.disk, 'network': 0 }, mutable=False) flavor_id = service.service_id return flavor_id
def __init__(self, service_usage, customer, tariff): self.currency = tariff.currency service_id, tariff_id, total_cost, total_usage_volume = service_usage service = Service.get_by_id(service_id) if service: self.name = service.get_localized_name(customer.locale_language()) self.category = service.category.get_localized_name(customer.locale_language()) self.measure = service.measure.get_localized_name(customer.locale_language()) self.hours = service.hours else: self.name = str(service_id) self.category = "" self.measure = "" self.hours = 1 self.total_cost = total_cost or Decimal(0) self.total_usage_volume = total_usage_volume or 0 self.price = tariff.service_price(service_id) or Decimal(0) self.service_id = service_id
def put(self, service_id): args = self.parser.parse_args() only_admins_authorized(args['Authorization']) s = Service().query.get_or_404(service_id) if args['owner_id'] is not None: u = User.query.get(args['owner_id']) s.owner = u elif args['owner_login'] is not None: u = User.query.filter_by(login=args['owner_login']).first() s.owner = u else: return 'You are not updating anything', 400 s.insert() return {'service': marshal(s, service_fields)}, 201
def new_custom_service(self, localized_name, measure, description=None): """ Add new custom service. Parameters must be sent as json object. :param LocalizedName localized_name: Dict with name localization. en is mandatory key ``{"en": "Name", "ru": "\u0418\u043c\u044f"}`` :param LocalizedName description: Dict with localized description. (Not mandatory) :param Measure measure: Measure id. Only time measure is possible. **Example**:: {"service_info": { "mutable": true, "localized_name": { "ru": "", "en": "Test Custom Service" }, "deleted": null, "measure": { "localized_name": { "ru": "\u0447\u0430\u0441", "en": "hour" }, "measure_type": "time", "measure_id": "hour" }, "category": { 'localized_name': {'ru': 'Дополнительные', 'en': 'Custom'}, 'category_id': 'custom' }, "service_id": 1, "description": {} } } """ service = Service.create_custom(localized_name, measure, description) return {"service_info": display(service)}
def get_service(self, service_id): """ Return service description :param Id service_id: Service Id :return dict service_info: Dict with service parameters **Example**:: { "service_info": { "service_id": "storage.volume", "measure": { "measure_type": "time_quant", "measure_id": "gigabyte*month", "localized_name": { "ru": "Гб*месяц", "en": "Gb*month" } }, "category": { "localized_name": { "ru": "Хранение данных", "en": "Storage" }, "category_id": "storage" }, "localized_name": { "ru": "Диск", "en": "Volume" } } } """ service = Service.get_by_id(service_id) if not service: raise errors.ServiceNotFound() return {"service_info": display(service)}
def __init__(self, service_id, customer, tariff): self.currency = tariff.currency self.service = Service.get_by_id(service_id) if self.service: self.name = self.service.get_localized_name( customer.locale_language()) self.category = self.service.category.get_localized_name( customer.locale_language()) self.measure = self.service.measure.get_localized_name( customer.locale_language()) self.hours = self.service.hours else: self.name = str(service_id) self.category = "" self.measure = "" self.hours = 1 self.price = tariff.service_price(service_id) self.service_id = service_id self.resources = {}
def populate_services(): """Create minimum sample data for the services table.""" Service.query.delete() b = Business.query.all() services = [{ 'business_id': b[0].id, 'description': 'Walk', 'cost': 30 }, { 'business_id': b[0].id, 'description': 'Board', 'cost': 40 }, { 'business_id': b[0].id, 'description': 'Daycare', 'cost': 60 }, { 'business_id': b[1].id, 'description': 'Walk', 'cost': 25 }, { 'business_id': b[1].id, 'description': 'Board', 'cost': 35 }, { 'business_id': b[1].id, 'description': 'Daycare', 'cost': 55 }] for service in services: s = Service(business_id=service['business_id'], description=service['description'], cost=service['cost']) db.session.add(s) db.session.commit() return None
def __init__(self, service_usage, customer, tariff): self.currency = tariff.currency service_id, tariff_id, total_cost, total_usage_volume = service_usage service = Service.get_by_id(service_id) if service: self.name = service.get_localized_name(customer.locale_language()) self.category = service.category.get_localized_name( customer.locale_language()) self.measure = service.measure.get_localized_name( customer.locale_language()) self.hours = service.hours else: self.name = str(service_id) self.category = "" self.measure = "" self.hours = 1 self.total_cost = total_cost or Decimal(0) self.total_usage_volume = total_usage_volume or 0 self.price = tariff.service_price(service_id) or Decimal(0) self.service_id = service_id
def create(cls, mechanic_id, truck_id, delivery_prevision_date, delivery_prevision_hour, effective_delivered_date, effective_delivered_hour, service_description, total_charge, payment_type): mechanic = MechanicDataHandler.get_by_id(mechanic_id) truck = TruckDataHandler.get_by_id(truck_id) if not truck: IndexUnrelatedToAnyObject if not mechanic: raise IndexUnrelatedToAnyObject if not isinstance(delivery_prevision_date, date) or not isinstance( effective_delivered_date, date): raise TypeError elif not isinstance(delivery_prevision_hour, time) or not isinstance( effective_delivered_hour, time): raise TypeError elif not isinstance(payment_type, PaymentType): raise TypeError service = Service(mechanic_id=mechanic_id, truck_id=truck_id, entry_date=date.today(), entry_time=datetime.now().time(), delivery_prevision_date=delivery_prevision_date, delivery_prevision_hour=delivery_prevision_hour, effective_delivered_date=effective_delivered_date, effective_delivered_hour=effective_delivered_hour, service_description=service_description, total_charge=total_charge, payment_type=payment_type) if cls.exists(service): raise UniqueObjectViolated cls.__db_session.add(service) cls.__db_session.commit()
def test_for_nonexistent_flavor(self): """ Tests that transformer doesn't stop when flavor.name isn't in database and creates fake entry in DB for that flavor. """ state = [{ 'timestamp': testdata.t0, 'counter_volume': states['active'], 'metadata': { 'flavor.name': testdata.flavor } }, { 'timestamp': testdata.t0_30, 'counter_volume': states['active'], 'metadata': { 'flavor.name': testdata.fake_flavor } }, { 'timestamp': testdata.t1, 'counter_volume': states['active'], 'metadata': { 'flavor.name': testdata.fake_flavor } }] with mock.patch( 'os_interfaces.openstack_wrapper.openstack.get_nova_flavor', mock.MagicMock(side_effect=self.create_flavor_mock)): result = self._run_transform(state) result.sort(key=attrgetter("service_id")) flavor = Service.get_by_id(result[1].service_id).flavor self.assertEqual(flavor.flavor_id, testdata.fake_flavor) self.assertEqual(openstack.get_nova_flavor.call_count, 1) self.assertEqual(openstack.create_flavor.call_count, 10) self.assertEqual(result[1].end - result[1].start, datetime.timedelta(minutes=30, seconds=-1))
def load_services(services_filename): """Load services.""" print("Service") for i, row in enumerate(open(services_filename)): row = row.rstrip() service_name, miles = row.split("|") for j in range(1, 11): suggested_mileage = j * int(miles) for k in range(1, 19): new_service = Service(model_id=k, service_name=service_name, suggested_mileage=suggested_mileage) db.session.add(new_service) print(k) db.session.commit()
def post(self): args = self.parser.parse_args() bots_are_not_authorized(args['Authorization']) s = Service().query.filter_by(name=args['name']).first() if s is not None: abort(400, message="Service already exists") else: if is_user(args['Authorization']): u = User.query.filter_by(token=args['Authorization']).first() else: u = User.query.filter_by(login=args['owner_login']).first() s = Service(name=args['name'], region=args['region'], size=args['size'], image=args['image'], ssh_keys=args['ssh_keys'], backups=args['backups'], ipv6=args['ipv6'], user_data=args['user_data'], private_networking=args['private_networking'], volumes=args['volumes'], owner=u) s.insert() return {'service': marshal(s, service_fields)}, 201
def test_iter(self): s = Service(Context(http = MockHttp(HTTP_SRC_DIR), service = "http://example.org/service.atomsvc")) self.assertEqual("http://example.org/entry/index.atom", s.iter().next().collection)
def service(self): # we can't do it by relationship, because some services # can be fixed services which are configured from config file return Service.get_by_id(self.service_id)
def display(self, short=True): service = Service.get_by_id(self.service_id) return {"service": service.display(short), "price": decimal_to_string(self.price), "need_changing": self.need_changing}
def services(serz): sz = [] for variety, examples in list(serz.items()): for example in examples: sz.append(Service(name=example, variety=variety)) db.put_multi(sz)
def create_flavor(self, params=None): service = Service.create_vm(**params) service.mark_immutable() return service
def test_iter_info(self): s = Service(Context(http = MockHttp(HTTP_SRC_DIR), service = "http://example.org/service.atomsvc")) ws_title, coll_title, coll_uri = s.iter_info().next() self.assertEqual("http://example.org/entry/index.atom", coll_uri) self.assertEqual("entry", coll_title) self.assertEqual("Main Site", ws_title)
def test_iter_match(self): s = Service(Context(http = MockHttp(HTTP_SRC_DIR), service = "http://example.org/service_entry_image.atomsvc")) self.assertEqual("http://example.org/images/index.atom", s.iter_match('image/png').next().collection)