Пример #1
0
def db_asset_add(**kwargs):
    """
    add asset to db
    添加主机时数据库操作函数
    """
    group_id_list = kwargs.pop('groups')
    asset = Asset(**kwargs)
    asset.save()

    group_select = []
    for group_id in group_id_list:
        group = AssetGroup.objects.filter(id=group_id)
        group_select.extend(group)
    asset.group = group_select
Пример #2
0
def db_asset_add(**kwargs):
    """
    add asset to db
    添加主机时数据库操作函数
    """
    group_id_list = kwargs.pop('groups')
    asset = Asset(**kwargs)
    asset.save()

    group_select = []
    for group_id in group_id_list:
        group = AssetGroup.objects.filter(id=group_id)
        group_select.extend(group)
    asset.group = group_select
Пример #3
0
def exmysql():
    data = xlrd.open_workbook('asset.xls')
    #获取工作表sheet1
    table = data.sheet_by_name('sheet1')
    #获取行数和列数
    nrows, ncols = table.nrows, table.ncols
    #
    colnames = table.row_values(0)
    w = []
    # print(nrows,ncols)
    # lists = []
    # for i in range(1,nrows):
    #     print(i)
    #     row = table.row_values(i)
    #     if row:
    #         app = {}
    #         for ii in range(len(n)):
    #             app[n[ii]] = row[ii]
    #         lists.append(app)
    # print(lists)
    for i in range(1, nrows):
        #获取每行的值
        row = table.row_values(i)
        print()
        for j in range(0, ncols):  #
            if type(row[j]) == float:
                row[j] = int(row[j])
        if row:
            if Asset.objects.filter(hostname=row[0],
                                    inner_ip=row[1],
                                    pub_ip=row[2]).exists():
                pass
            else:
                w.append(
                    Asset(hostname=row[0],
                          inner_ip=row[1],
                          pub_ip=row[2],
                          port=row[3],
                          mem_total=row[4],
                          disk_total=row[5],
                          cpu_model=row[6],
                          num_cpus=row[7],
                          osfinger=row[8],
                          osrelease=row[9],
                          dns=row[10],
                          mac_addr=row[11],
                          kernelrelease=row[12],
                          serialnumber=row[13],
                          virtual=row[14],
                          status=row[15],
                          detail=row[16]))

    Asset.objects.bulk_create(w)


#system_user=row[17],product=row[18],tag=row[19],cloud_platform=row[20],create_user=row[21]
Пример #4
0
 def setUp(self):
     self.user = User.objects.create_basic_user(
         username='******',
         email='*****@*****.**',
         password='******'
     )
     self.asset = Asset(
         user=self.user,
         name='test_asset')
     self.asset.save()
Пример #5
0
def create_asset(**kwargs):
    app.logger.info(f"Attempting to create asset: {kwargs.items()}")
    try:
        with ScopedSession as local_db_session:
            new_asset = Asset(**kwargs)
            local_db_session.add(new_asset)
            local_db_session.flush()
            app.logger.info(f"Asset created: {new_asset.id}")
    except:
        new_asset = None
    return new_asset
Пример #6
0
class ModelTests(TestCase):
    def setUp(self):
        self.user = User.objects.create_basic_user(
            username='******',
            email='*****@*****.**',
            password='******'
        )
        self.asset = Asset(
            user=self.user,
            name='test_asset')
        self.asset.save()

    def tearDown(self):
        self.user.delete()
        self.asset.delete()

    def test_price(self):
        self.assertIsNone(self.asset.price)
        self.asset.price = MoneyAmount('USD', 400)
        self.assertEqual(self.asset.price, MoneyAmount('USD', 400))

    def test_absolute_url(self):
        self.assertEqual(
            self.asset.get_absolute_url(),
            '/assets/user/{0}/asset/{1}'.format(self.user.id, self.asset.id.hex)
        )

    def test_qr_code(self):
        print('QR CODE: {0}'.format(self.asset.qr_code))
        self.assertEqual(
            self.asset.qr_code,
            settings.HOST_URI + self.asset.get_absolute_url()
        )
Пример #7
0
def add_old_asset():
    ''' 增加一个旧资产,以展示资产折旧 '''
    from asset.models import Asset, AssetCategory
    from user.models import User
    from datetime import timedelta
    if not Asset.objects.all().exists():
        asset = Asset(name='旧资产',
                      value=10000,
                      category=AssetCategory.root(),
                      status='IDLE',
                      service_life=10,
                      owner=User.admin())
        asset.save()
        asset.start_time -= timedelta(366)
        asset.save()
Пример #8
0
    def mutate(self, info, input):
        name, urls, media_type, copyright_level, user_ids, stage_ids, tags, w, h = itemgetter(
            'name', 'urls', 'media_type', 'copyright_level', 'user_ids',
            'stage_ids', 'tags', 'w', 'h')(input)
        current_user_id = get_jwt_identity()
        with ScopedSession() as local_db_session:
            asset_type = local_db_session.query(AssetTypeModel).filter(
                AssetTypeModel.name == media_type).first()
            if not asset_type:
                asset_type = AssetTypeModel(name=media_type,
                                            file_location=media_type)
                local_db_session.add(asset_type)
                local_db_session.flush()

            if 'id' in input:
                id = from_global_id(input['id'])[1]
                asset = local_db_session.query(AssetModel).filter(
                    AssetModel.id == id).first()

                if asset:
                    code, error, user, timezone = current_user()
                    if not user.role in (ADMIN, SUPER_ADMIN):
                        if not user.id == asset.owner_id:
                            raise Exception(
                                "You don't have permission to edit this media")

            else:
                asset = AssetModel(owner_id=current_user_id)
                local_db_session.add(asset)

            if asset:
                asset.name = name
                asset.asset_type = asset_type
                file_location = urls[0]
                if file_location:
                    if "?" in file_location:
                        file_location = file_location[:file_location.index("?"
                                                                           )]
                    if asset.id and file_location != asset.file_location and '/' not in file_location:
                        existedAsset = local_db_session.query(
                            AssetModel).filter(
                                AssetModel.file_location == file_location
                            ).filter(AssetModel.id != asset.id).first()
                        if existedAsset:
                            raise Exception(
                                "Stream with the same key already existed, please pick another unique key!"
                            )
                    asset.file_location = file_location
                else:
                    asset.file_location = uuid.uuid4()
                asset.copyright_level = copyright_level
                asset.updated_on = datetime.utcnow()
                local_db_session.flush()

            if urls:
                if not asset.description:
                    asset.description = "{}"
                attributes = json.loads(asset.description)
                if not 'frame' in attributes or attributes['frames']:
                    attributes['frames'] = []

                asset.size = 0
                for url in urls:
                    attributes['frames'].append(url)
                    full_path = os.path.join(absolutePath, storagePath, url)
                    try:
                        size = os.path.getsize(full_path)
                    except:
                        size = 0  # file not exist
                    asset.size += size

                if len(urls) > 1:
                    attributes['multi'] = True
                else:
                    attributes['multi'] = False
                    attributes['frames'] = []
                attributes['w'] = w
                attributes['h'] = h
                if asset_type.name == 'stream' and '/' not in file_location:
                    attributes['isRTMP'] = True

                if 'voice' in input:
                    voice = input['voice']
                    if voice and voice.voice:
                        attributes['voice'] = voice
                    elif 'voice' in attributes:
                        del attributes['voice']

                if 'link' in input:
                    link = input['link']
                    if link and link.url:
                        attributes['link'] = link
                    elif 'link' in attributes:
                        del attributes['link']

                asset.description = json.dumps(attributes)
                local_db_session.flush()

            if stage_ids != None:
                asset.stages.delete()
                for id in stage_ids:
                    asset.stages.append(ParentStage(stage_id=id))

            if user_ids != None:
                granted_permissions = asset.permissions.all()
                for permission in granted_permissions:
                    if isinstance(permission, AssetUsageModel):
                        if permission.user_id not in user_ids and permission.approved == True:
                            asset.permissions.remove(permission)
                            local_db_session.delete(permission)
                for user_id in user_ids:
                    permission = local_db_session.query(
                        AssetUsageModel).filter(
                            AssetUsageModel.asset_id == asset.id,
                            AssetUsageModel.user_id == user_id).first()
                    if not permission:
                        permission = AssetUsageModel(user_id=user_id)
                        asset.permissions.append(permission)
                    permission.approved = True
                local_db_session.flush()

            if tags:
                asset.tags.delete()
                for tag in tags:
                    tag_model = local_db_session.query(Tag).filter(
                        Tag.name == tag).first()
                    if not tag_model:
                        tag_model = Tag(name=tag)
                        local_db_session.add(tag_model)
                        local_db_session.flush()
                    asset.tags.append(MediaTag(tag_id=tag_model.id))

            local_db_session.flush()
            local_db_session.commit()
            asset = local_db_session.query(AssetModel).filter(
                AssetModel.id == asset.id).first()
            return SaveMedia(asset=asset)
Пример #9
0
def migrate_items():
    f = open("innovonet-migration-2016-05-11/item.json", "r")
    d = f.read()
    f.close()
    data_assets = json.loads(d)
    # data = data_assets[100]

    for data in data_assets['RECORDS']:
        data_obj = Asset()
        data_obj.title = data['title'] or None

        try:
            data_obj.organization = SubOrganization.objects.get(
                pk=int(data['ou_id']))
        except Exception as e:
            print e, data['item_id'], data['ou_id']
            data_obj.organization = None

        try:
            data_obj.building = Building.objects.get(
                pk=int(data['building_id']))
        except Exception as e:
            print e, data['item_id'], data['building_id']
            data_obj.building = None

        try:
            data_obj.date_updated = datetime.strptime(data['date_updated'],
                                                      '%Y-%m-%d %H:%M:%S')
        except:
            data_obj.date_updated = None

        try:
            data_obj.date_of_purchase = datetime.strptime(
                data['date_of_purchase'], '%Y-%m-%d %H:%M:%S')
        except:
            data_obj.date_of_purchase = None

        try:
            data_obj.date_added = datetime.strptime(data['date_added'],
                                                    '%Y-%m-%d %H:%M:%S')
        except:
            data_obj.date_added = None

        try:
            data_obj.image = data['image'] or None
        except Exception as e:
            print e.message, data['item_id'], 'image'

        try:
            data_obj.manufacturer_website = data['manufacturer_website'] or None
        except Exception as e:
            print e.message, data['item_id'], 'manufacturer_website'

        try:
            data_obj.cost = data['cost'] or None
        except Exception as e:
            print e.message, data['item_id'], 'cost'

        try:
            data_obj.keywords = data['keywords'] or None
        except Exception as e:
            print e.message, data['item_id'], 'keywords'

        try:
            data_obj.availability = data['availability'] or None
        except Exception as e:
            print e.message, data['item_id'], 'availability'

        try:
            data_obj.organisation = data['organisation'] or None

        except Exception as e:
            print e.message, data['item_id'], 'organisation'

        try:
            data_obj.comments = data['comments'] or None
        except Exception as e:
            print e.message, data['item_id'], 'comments'

        try:
            data_obj.contact_2_email = data['contact_2_email'] or None
        except Exception as e:
            print e.message, data['item_id'], 'contact_2_email'

        try:
            data_obj.contact_1_email = data['contact_1_email'] or None
        except Exception as e:
            print e.message, data['item_id'], 'contact_1_email'

        try:
            data_obj.short_description = data['short_description'] or None
        except Exception as e:
            print e.message, data['item_id'], 'short_description'

        try:
            data_obj.serial_no = data['serial_no'] or None
        except Exception as e:
            print e.message, data['item_id'], 'serial_no'

        try:
            data_obj.visibility = data['visibility'] or None
        except Exception as e:
            print e.message, data['item_id'], 'visibility'

        try:
            data_obj.manufacturer = data['manufacturer'] or None
        except Exception as e:
            print e.message, data['item_id'], 'manufacturer'

        try:
            data_obj.full_description = data['full_description'] or None
        except Exception as e:
            print e.message, data['item_id'], 'full_description'

        try:
            data_obj.contact_1_name = data['contact_1_name'] or None
        except Exception as e:
            print e.message, data['item_id'], 'contact_1_name'

        try:
            data_obj.asset_no = data['asset_no'] or None
        except Exception as e:
            print e.message, data['item_id'], 'asset_no'

        try:
            data_obj.contact_2_name = data['contact_2_name'] or None
        except Exception as e:
            print e.message, data['item_id'], 'contact_2_name'

        try:
            data_obj.specification = data['specification'] or None
        except Exception as e:
            print e.message, data['item_id'], 'specification'

        try:
            data_obj.quantity = data['quantity'] or None
        except Exception as e:
            print e.message, data['item_id'], 'quantity'

        try:
            data_obj.year_of_manufacture = data['year_of_manufacture'] or None
        except Exception as e:
            print e.message, data['item_id'], 'year_of_manufacture'

        try:
            data_obj.room = data['room'] or None
        except Exception as e:
            print e.message, data['item_id'], 'room'

        try:
            data_obj.model_name = data['model']
        except Exception as e:
            print type(e).__name__, e.message, data['item_id'], 'model_name'

        data_obj.save()
Пример #10
0
    def mutate(self, info, name, media_type, base64=None, file_location=None, description=None, id=None, copyright_level=None, player_access=None, uploaded_frames=None):
        current_user_id = get_jwt_identity()
        with ScopedSession() as local_db_session:
            asset_type = local_db_session.query(AssetTypeModel).filter(
                AssetTypeModel.name == media_type).first()
            if not asset_type:
                asset_type = AssetTypeModel(
                    name=media_type, file_location=media_type)
                local_db_session.add(asset_type)
                local_db_session.flush()

            if id:
                id = from_global_id(id)[1]
                asset = local_db_session.query(AssetModel).filter(
                    AssetModel.id == id).first()
            elif file_location:
                existedAsset = local_db_session.query(AssetModel).filter(
                    AssetModel.file_location == file_location).first()
                if existedAsset:
                    raise Exception(
                        "Media with the same key already existed, please pick another!")

                asset = AssetModel(owner_id=current_user_id)
                local_db_session.add(asset)

            if asset:
                asset.name = name
                asset.asset_type = asset_type
                asset.description = description
                if file_location:
                    if "?" in file_location:
                        file_location = file_location[:file_location.index(
                            "?")]
                    if asset.id and file_location != asset.file_location:
                        existedAsset = local_db_session.query(AssetModel).filter(
                            AssetModel.file_location == file_location).filter(AssetModel.id != asset.id).first()
                        if existedAsset:
                            raise Exception(
                                "Media with the same key already existed, please pick another!")
                    asset.file_location = file_location

                if base64:
                    # Replace image content
                    mediaDirectory = os.path.join(
                        absolutePath, storagePath, asset.file_location)
                    with open(mediaDirectory, "wb") as fh:
                        fh.write(b64decode(base64.split(',')[1]))
                    asset.updated_on = datetime.utcnow()

                if asset.asset_license:
                    asset.asset_license.level = copyright_level
                    asset.asset_license.permissions = player_access
                else:
                    if not asset.id:
                        local_db_session.flush()

                    asset_license = AssetLicense(
                        asset_id=asset.id,
                        level=copyright_level,
                        permissions=player_access
                    )
                    local_db_session.add(asset_license)
                local_db_session.flush()

            if uploaded_frames:
                filename, file_extension = os.path.splitext(
                    asset.file_location)
                attributes = json.loads(asset.description)
                if not attributes['frames']:
                    attributes['frames'] = []

                for frame in uploaded_frames:
                    unique_filename = uuid.uuid4().hex + file_extension
                    mediaDirectory = os.path.join(
                        absolutePath, storagePath, asset_type.file_location)
                    if not os.path.exists(mediaDirectory):
                        os.makedirs(mediaDirectory)
                    with open(os.path.join(mediaDirectory, unique_filename), "wb") as fh:
                        fh.write(b64decode(frame.split(',')[1]))

                    frame_location = os.path.join(
                        asset_type.file_location, unique_filename)
                    attributes['frames'].append(frame_location)

                asset.description = json.dumps(attributes)
                local_db_session.flush()

            local_db_session.flush()
            local_db_session.commit()
            asset = local_db_session.query(AssetModel).filter(
                AssetModel.id == asset.id).first()
            return UpdateMedia(asset=asset)
Пример #11
0
 def transfer_success(asset: Asset, issue: Issue):
     ''' 资产转移成功后 '''
     asset.owner = issue.assignee
     asset._change_reason = '转移'
     asset.save(tree_update=True)
Пример #12
0
 def return_success(asset: Asset, issue: Issue):
     ''' 资产退还成功后 '''
     asset.owner = issue.handler
     asset.status = 'IDLE'
     asset._change_reason = '退还'
     asset.save(tree_update=True)
Пример #13
0
 def fix(asset: Asset, issue: Issue):
     ''' 资产维保 成功或失败 后 '''
     asset.owner = issue.initiator
     asset.status = 'IN_USE'
     asset._change_reason = '维保结束'
     asset.save(tree_update=True)
Пример #14
0
        for row_num in range(1, rows):
            row = table.row_values(row_num)
            if row:
                group_instance = []
                ip, port, hostname, use_default_auth, username, password, group = row
                if get_object(Asset, hostname=hostname):
                    continue
                if isinstance(password, int) or isinstance(password, float):
                    password = unicode(int(password))
                use_default_auth = 1 if use_default_auth == u'默认' else 0
                password_encode = CRYPTOR.encrypt(password) if password else ''
                if hostname:
                    asset = Asset(ip=ip,
                                  port=port,
                                  hostname=hostname,
                                  use_default_auth=use_default_auth,
                                  username=username,
                                  password=password_encode
                                  )
                    asset.save()
                    group_list = group.split('/')
                    for group_name in group_list:
                        group = get_object(AssetGroup, name=group_name)
                        if group:
                            group_instance.append(group)
                    if group_instance:
                        asset.group = group_instance
                    asset.save()
        return True

Пример #15
0
        rows = table.nrows
        for row_num in range(1, rows):
            row = table.row_values(row_num)
            if row:
                group_instance = []
                ip, port, hostname, use_default_auth, username, password, group = row
                if get_object(Asset, hostname=hostname):
                    continue
                if isinstance(password, int) or isinstance(password, float):
                    password = unicode(int(password))
                use_default_auth = 1 if use_default_auth == u'默认' else 0
                password_encode = CRYPTOR.encrypt(password) if password else ''
                if hostname:
                    asset = Asset(ip=ip,
                                  port=port,
                                  hostname=hostname,
                                  use_default_auth=use_default_auth,
                                  username=username,
                                  password=password_encode)
                    asset.save()
                    group_list = group.split('/')
                    for group_name in group_list:
                        group = get_object(AssetGroup, name=group_name)
                        if group:
                            group_instance.append(group)
                    if group_instance:
                        asset.group = group_instance
                    asset.save()
        return True


def get_ansible_asset_info(asset_ip, setup_info):
Пример #16
0
def migrate_items():
    f = open("innovonet-migration-2016-05-11/item.json", "r")
    d = f.read()
    f.close()
    data_assets = json.loads(d)
    # data = data_assets[100]
    
    for data in data_assets['RECORDS']:
        data_obj = Asset()
        data_obj.title = data['title'] or None

        try:
            data_obj.organization = SubOrganization.objects.get(pk=int(data['ou_id']))
        except Exception as e:
            print e, data['item_id'], data['ou_id']
            data_obj.organization = None
        
        try:
            data_obj.building = Building.objects.get(pk=int(data['building_id']))
        except Exception as e:
            print e, data['item_id'], data['building_id']
            data_obj.building = None

        try:
            data_obj.date_updated = datetime.strptime(data['date_updated'], '%Y-%m-%d %H:%M:%S') 
        except:
            data_obj.date_updated = None
        
        try:
            data_obj.date_of_purchase = datetime.strptime(data['date_of_purchase'], '%Y-%m-%d %H:%M:%S') 
        except:
            data_obj.date_of_purchase = None;

        try:
            data_obj.date_added = datetime.strptime(data['date_added'], '%Y-%m-%d %H:%M:%S') 
        except:
            data_obj.date_added = None
        
        
        try:
            data_obj.image = data['image'] or None
        except Exception as e:
            print e.message, data['item_id'], 'image'
        
        try:
            data_obj.manufacturer_website = data['manufacturer_website'] or None
        except Exception as e:
            print e.message, data['item_id'], 'manufacturer_website'
        
        try:
            data_obj.cost = data['cost'] or None
        except Exception as e:
            print e.message, data['item_id'], 'cost'
    
        try:
            data_obj.keywords = data['keywords'] or None
        except Exception as e:
            print e.message, data['item_id'], 'keywords'

        try:
            data_obj.availability = data['availability'] or None
        except Exception as e:
            print e.message, data['item_id'], 'availability'
        
        try:
            data_obj.organisation = data['organisation'] or None
            
        except Exception as e:
            print e.message, data['item_id'], 'organisation'
        
        try:
            data_obj.comments = data['comments'] or None
        except Exception as e:
            print e.message, data['item_id'], 'comments'

        try:
            data_obj.contact_2_email = data['contact_2_email'] or None
        except Exception as e:
            print e.message, data['item_id'], 'contact_2_email'
        
        try:
            data_obj.contact_1_email = data['contact_1_email'] or None
        except Exception as e:
            print e.message, data['item_id'], 'contact_1_email'
        
        try:
            data_obj.short_description = data['short_description'] or None
        except Exception as e:
            print e.message, data['item_id'], 'short_description'
        
        try:
            data_obj.serial_no = data['serial_no'] or None
        except Exception as e:
            print e.message, data['item_id'], 'serial_no'

        try:
            data_obj.visibility = data['visibility'] or None
        except Exception as e:
            print e.message, data['item_id'], 'visibility'
        
        try:
            data_obj.manufacturer = data['manufacturer'] or None
        except Exception as e:
            print e.message, data['item_id'], 'manufacturer'
        
        try:
            data_obj.full_description = data['full_description'] or None
        except Exception as e:
            print e.message, data['item_id'], 'full_description'
        
        try:
            data_obj.contact_1_name = data['contact_1_name'] or None
        except Exception as e:
            print e.message, data['item_id'], 'contact_1_name'
        
        try:
            data_obj.asset_no = data['asset_no'] or None
        except Exception as e:
            print e.message, data['item_id'], 'asset_no'
        
        try:
            data_obj.contact_2_name = data['contact_2_name'] or None        
        except Exception as e:
            print e.message, data['item_id'], 'contact_2_name'
        
        try:
            data_obj.specification = data['specification'] or None        
        except Exception as e:
            print e.message, data['item_id'], 'specification'
        
        try:
            data_obj.quantity = data['quantity'] or None        
        except Exception as e:
            print e.message, data['item_id'], 'quantity'
        
        try:
            data_obj.year_of_manufacture = data['year_of_manufacture'] or None
        except Exception as e:
            print e.message, data['item_id'], 'year_of_manufacture'
        
        try:
            data_obj.room = data['room'] or None
        except Exception as e:
            print e.message, data['item_id'], 'room'
        
        try:
            data_obj.model_name = data['model']
        except Exception as e:
            print type(e).__name__, e.message, data['item_id'], 'model_name'

        data_obj.save()