def main():
    instructions = [
        "/login", "/shops", "/enter", "/goods", "/customers", "/buy", "/leave",
        "/addgoods", "/bye"
    ]
    th0 = threading.Thread(target=receive)
    th0.start()

    while True:
        msg = input('请输入您的指令:')
        text = msg.split()
        try:
            assert text[0] in instructions
            if text[0] == "/bye":
                upd_client.sendto(
                    Package("header#/bye").send(), server_ip_port)
                break
            msg = Package("header#" + text[0], cookie["user_id"],
                          ",".join(text[1:]))
            upd_client.sendto(msg.send(), server_ip_port)
            time.sleep(0.2)
        except AssertionError:
            print("没有该类型的指令!")
            print("正确的指令有:", instructions)

    running[0] = False
def import_packages_to_hashtable(hashtable, packages, filename):
    """Import package data into a list and a hash table."""

    with open(filename) as f:
        lines = f.readlines()

        # Read each line in the file, create a package item for it, and place
        # the package in the hashtable.
        for line in lines:
            line = line.strip()
            line = line.replace('"', '')
            line = line.split(",")

            # If the special notes column has commas in it, correct the multiple
            # comma separated columns to 1 column.
            special_notes = ""
            if len(line) > 8:
                special_notes = line[7]
                for i in range(8, len(line)):
                    special_notes += ", " + line[i]
                line = line[:7] + [special_notes]

            # Create a package.
            package = Package(int(line[0]), str(line[1]), str(line[2]),
                              str(line[3]), str(line[4]),
                              convert_standard_time_to_minutes(str(line[5])),
                              int(line[6]), str(line[7]))

            # Place the package into the hash table.
            hashtable.add(package)

            # Add the package to the provided queue.
            packages.append(package)
Beispiel #3
0
def update_list_of_packages():
    package_names = memcache.get(PACKAGES_CACHE_KEY)
    package_index = memcache.get(PACKAGES_CHECKED_INDEX)
    
    
    if package_index is None:
        package_index = 0
    
    if package_names is None:
        package_names = pypi_parser.get_list_of_packages()
        memcache.add(PACKAGES_CACHE_KEY, package_names, 60 * 60 * 24)

    for name in package_names[package_index:package_index + DB_STEPS]:
        if name in TO_IGNORE:
            pass
        else:
            query = db.GqlQuery("SELECT __key__ FROM Package WHERE name = :name", name=name)
            if len(list(query)) == 0:
                p = Package(name=name)
                p.put()
        
        package_index += 1
        if package_index % 5 == 0:
            memcache.set(PACKAGES_CHECKED_INDEX, package_index, 60 * 60 * 24)
            
    if package_index == len(package_names):
        return -1
    
    return package_index
Beispiel #4
0
    async def track(self, ctx, cod, *, tag = ""):
        """Register a track to a correios package

        Args:
            cod: Correios tracking code
            tag (optional): Tag to identify your package. Defaults to ""
        """
        member = ctx.message.author

        result = session.query(Package).filter_by(id=cod).first()

        if not result:
            res = await self.get_correios(cod)
            if len(res):
                session.add(Package(
                    id = cod,
                    user_id = member.id,
                    guild_id = ctx.guild.id,
                    tag = tag
                ))
                session.commit()
                logging.info(f"Successfully added tracking for package {cod}.")
                return await ctx.reply(f"Objeto cadastrado com sucesso.")
            logging.info(f"Package {cod} not found in database.")
            return await ctx.reply(f"Não encontramos esse objeto.")

        logging.info(f"Package {cod} was already in database.")
        return await ctx.reply(f"Objeto já cadastrado.")
Beispiel #5
0
    def parse_inactive(self, lines, package_state):
        packages_dict = {}

        if lines is None:
            return packages_dict

        found = False
        #lines = lines.splitlines()

        for line in lines:
            if found:
                location = None
                name = line.strip()

                #skip anything after the blank line
                if len(name) == 0:
                    break

                package = Package(location=location,
                                  name=name,
                                  state=package_state)
                packages_dict[name] = package

            elif 'package' in line:
                found = True

        return packages_dict
Beispiel #6
0
    def parse_active_and_committed(self, lines, package_state):
        packages_dict = {}

        if lines is None:
            return packages_dict

        #lines = lines.splitlines()

        trunks = self.get_trunks(lines)
        if len(trunks) > 0:
            # Collect all the packages
            package_list = []
            for module in trunks:
                for package in trunks[module]:
                    if not package in package_list and re.match(
                            "(ncs.*)", package):
                        package_list.append(package)

            for package_name in package_list:
                package = Package(name=package_name,
                                  location=None,
                                  state=package_state)

                # Check which module has this package
                for module in trunks:
                    for line in trunks[module]:
                        if line == package_name:
                            package.modules_package_state.append(
                                ModulePackageState(
                                    module_name=module,
                                    package_state=package_state))

                packages_dict[package_name] = package

        return packages_dict
Beispiel #7
0
    def parseContents(self, lines, package_state):
        packages_dict = {}

        if lines is None:
            return packages_dict

        found = False
        lines = lines.splitlines()

        for line in lines:
            if found:
                line = line.strip()

                if ':' in line:
                    location, name = line.split(':')
                else:
                    location = ''
                    name = line

                # skip anything after the blank line
                if len(line) == 0:
                    break

                package = Package(location=location,
                                  name=name,
                                  state=package_state)
                packages_dict[name] = package

            elif 'Packages' in line:
                found = True

        return packages_dict
Beispiel #8
0
def add_dependencies(package, session):
    deps = set()
    pkg = yumobj.pkgSack.searchNevra(name=package.name)
    if not pkg:
        print "Cannot find package: %s" % package.name
        return

    deps_d = yumobj.findDeps([pkg[0]])
    for dep in deps_d.itervalues():
        for req in dep.itervalues():
            deps.add(req[0].name)

    for dep in deps:
        base_query = session.query(Package).filter_by(name=dep)
        if base_query.count() == 0:
            _new_package = Package(name=dep)
            session.add(_new_package)
            session.flush()
            add_dependencies(_new_package, session)

        dep_as_package = base_query.one()

        if dep_as_package not in package.dependencies:
            package.dependencies.append(dep_as_package)

    print "package: %s has (%i/%i) deps" % (
        package.name, len(package.dependencies), len(deps))

    session.flush()
Beispiel #9
0
    def get_committed_packages(self, lines, package_state):
        """
        lines contains the CLI outputs for 'show version running'
        """
        package_dict = {}

        if lines:
            trunks = self.get_trunks(lines.splitlines())
            if len(trunks) > 0:
                # Collect all the packages
                package_list = []
                for module in trunks:
                    for package in trunks[module]:
                        package_list.append(package)

                for package_name in package_list:
                    package = Package(name=package_name,
                                      location=None,
                                      state=package_state)

                    # Check which module has this package
                    for module in trunks:
                        for line in trunks[module]:
                            if line == package_name:
                                package.modules_package_state.append(
                                    ModulePackageState(
                                        module_name=module,
                                        package_state=package_state))

                    package_dict[package_name] = package

        return package_dict
Beispiel #10
0
def package(name):
    """
    New or existing package
    """
    try:
        package = Package.objects.get(name__exact=name)
    except:
        package = Package(name=name)
        package.save()
    return package
Beispiel #11
0
def receive():
    while running[0]:
        data, server_ip = upd_client.recvfrom(1024)  # 接收信息
        text = Package(data.decode("utf-8"))
        cookie["user_id"] = text.user_id
        if text.header == "reply":
            for each in text.reply.split("\n"):
                print(each)
        if text.header == "msg":
            print("您有一条新消息:", text.context)
Beispiel #12
0
def Choose_Http():
    if request.method == 'POST':
        host = request.form['host']
        port = request.form['port']
        delay = request.form['delay']
        num = request.form['num']	
        nowTime=datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')#现在
        p = Package(dst = host, num = int(num), protocol = "HTTP", flow = int(int(num) * 58), time = nowTime)
        db_session.add(p) 
        db_session.commit()
        scapy_http(host = host, port = int(port), delay = int(delay), num = int(num))
    return render_template('http.html')
Beispiel #13
0
def Choose_Dns():
    if request.method == 'POST':
        srchost = request.form['srchost']
        dsthost = request.form['dsthost']
        qdcount = request.form['qdcount']
        qname = request.form['qname']   
        nowTime=datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')#现在
        p = Package(dst = dsthost, num = int(qdcount), protocol = "DNS", flow = int(int(qdcount) * 56), time = nowTime)
        db_session.add(p) 
        db_session.commit()
        dns_packets(srchost = srchost, dsthost = dsthost, qdcount = int(qdcount), qname = qname)

    return render_template('dns.html')
Beispiel #14
0
def main():
    upd_client = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    server_ip_port = ('127.0.0.1', 25365)
    
    instructions = ["/msg", "/opennewshop", "/enter", "/goods", "/customers", "/shops", "/users", "/closeshop", "/bye"]
    
    while True:  # 通信循环
        msg = input('请输入您的指令:')
        text = msg.split()
        try:
            assert text[0] in instructions
            if text[0] == "/bye":
                break
            msg = Package("header#" + text[0], 999, ",".join(text[1:]))
            upd_client.sendto(msg.send(), server_ip_port)  # 发送信息,信息量,服务端地址
            data, server_ip = upd_client.recvfrom(1024)  # 管理员不需要异步加载消息,防止管理员徇私舞弊
            text = Package(data.decode("utf-8"))
            for each in text.reply.split("\n"):
                print(each)
        except AssertionError:
            print("没有该类型的指令!")
            print("正确的指令有:", instructions)
Beispiel #15
0
    def get_committed_packages(self, lines, package_state):
        """
        lines contains the CLI outputs for 'show version'
        """
        logging.warning("IOS.py get_committed_packages: lines = %s", lines)
        packages = []
        lines = lines.splitlines()
        for line in lines:
            match = re.search(r'(asr.*bin)', line)
            if match:
                package_name = match.group()
                packages.append(Package(location=None, name=package_name, state=package_state))

        return packages
Beispiel #16
0
def populate(comps='comps-f16', do_dependencies=True):
    from yum.comps import Comps

    session = DBSession()

    c = Comps()
    c.add('comps/%s.xml' % comps)

    for group in c.groups:
        g = Group(id=group.groupid,
                  name=group.name,
                  description=group.description)
        session.add(g)

        for package in group.packages:
            p = session.query(Package).filter_by(
                name=to_unicode(package)).first()
            if not p:
                p = Package(name=package)
                session.add(p)
            p.group = g

        session.flush()

    root = Root(name=u'Fedora')
    session.add(root)
    session.flush()

    for category in c.categories:
        c = Category(id=category.categoryid,
                     name=category.name,
                     description=category.description)
        session.add(c)
        root.categories.append(c)
        for group in category.groups:
            g = session.query(Group).filter_by(
                group_id=to_unicode(group)).first()
            if not g:
                print "Cannot find group: %s" % group
            else:
                g.category = c

        session.flush()

    if do_dependencies:
        for package in session.query(Package).all():
            add_dependencies(package, session)

    session.commit()
Beispiel #17
0
    def get_inactive_packages(self, lines, package_state):
        """
        lines contains the CLI outputs for 'cd flash:', then 'dir'
        """
        packages = []

        lines = lines.splitlines()
        for line in lines:
            if '.bin' in line:
                match = re.search(r'asr\S*', line)
                if match:
                    package_name = match.group()
                    packages.append(Package(location=None, name=package_name, state=package_state))

        return packages
Beispiel #18
0
def package_update(request):
    if request.method == 'POST':
        package = Package(request.POST)
        print(package)
        print("---------------------------------")
        package.bundle_identifier = request.POST.get("bundle_identifer", None)
        print(package)
        print("package")
        print("package.bundle_identifier")
        print(package.bundle_identifier)
        print(package.id)
        form = UpdatePackageForm(request.POST)
#        pack = Package(form)
#        print(pack)
        return render(request, "Application/upload_success.html", context_instance=RequestContext(request))
    else:
        return HttpResponse("FAIL")
Beispiel #19
0
    def insert_packages(payload):
        body = request.json
        name = body.get('name', None)
        duration = body.get('duration', None)
        price = body.get('price', None)

        if any(arg is None for arg in [name, duration, price]) or '' in [
                name, duration, price
        ]:
            abort(400, 'name , duration and price are required fields.')

        new_package = Package(name=name, duration=duration, price=price)
        new_package.insert()

        return jsonify({
            'success': True,
            'packages': [Package.query.get(new_package.id).format()]
        })
Beispiel #20
0
    def get_inactive_packages(self, lines, package_state):
        """
        lines contains the CLI outputs for 'sh install inactive'
        """
        packages = []

        lines = lines.splitlines()
        for line in lines:
            if 'lib32_n9000' in line:
                match = re.search(r'\S*lib32_n9000', line)
                if match:
                    package_name = match.group()
                    packages.append(
                        Package(location=None,
                                name=package_name,
                                state=package_state))

        return packages
Beispiel #21
0
    def parse_inactive(self, lines, package_state):
        """
        NON-ADMIN:
        RP/0/RP0/CPU0:Deploy#show install inactive
        5 inactive package(s) found:
            ncs6k-k9sec-5.2.5.47I
            ncs6k-mpls-5.2.5.47I
            ncs6k-5.2.5.47I.CSCuy47880-0.0.4.i
            ncs6k-mgbl-5.2.5.47I
            ncs6k-5.2.5.CSCuz65240-1.0.0

        ADMIN: Inactive
        sysadmin-vm:0_RP0:NCS-Deploy2# show install inactive
        Wed Jun  8  23:03:38.637 UTC
         Node 0/RP0 [RP]
            Inactive Packages:
               ncs6k-sysadmin-5.0.1.CSCun50237-1.0.0
               ncs6k-sysadmin-5.2.3.CSCut94440-1.0.0
               ncs6k-sysadmin-5.0.1.CSCum80946-1.0.0
               ncs6k-sysadmin-5.0.1.CSCus71815-1.0.0
               ncs6k-sysadmin-5.2.3.CSCut24295-1.0.0
               ncs6k-sysadmin-5.0.1.CSCuq00795-1.0.0
         Node 0/RP1 [RP]
            Inactive Packages:
               ncs6k-sysadmin-5.0.1.CSCun50237-1.0.0
               ncs6k-sysadmin-5.2.3.CSCut94440-1.0.0
               ncs6k-sysadmin-5.0.1.CSCum80946-1.0.0
               ncs6k-sysadmin-5.0.1.CSCus71815-1.0.0
               ncs6k-sysadmin-5.2.3.CSCut24295-1.0.0
               ncs6k-sysadmin-5.0.1.CSCuq00795-1.0.0
        """
        package_dict = {}
        if lines:
            lines = lines.splitlines()
            for line in lines:
                line = line.strip()
                if len(line) == 0: continue

                if re.match("(ncs.*|asr9k.*|xrv9k.*)", line):
                    package_dict[line] = Package(location=None,
                                                 name=line,
                                                 state=package_state)

        return package_dict
Beispiel #22
0
    def get_committed_packages(self, lines, package_state):
        """
        lines contains the CLI outputs for 'sh install packages | grep lib32_n9000'

        bfd.lib32_n9000                         2.0.0-7.0.3.I4.1              installed
        core.lib32_n9000                        2.0.0-7.0.3.I4.1              installed
        eigrp.lib32_n9000                       2.0.0-7.0.3.I4.1              installed
        eth.lib32_n9000                         2.0.0-7.0.3.I4.1              installed
        """
        packages = []
        lines = lines.splitlines()
        for line in lines:
            if 'lib32_n9000' in line:
                match = re.search(r'\S*lib32_n9000', line)
                if match:
                    package_name = match.group()
                    packages.append(
                        Package(location=None,
                                name=package_name,
                                state=package_state))

        return packages
Beispiel #23
0
 def handle(self):
     print(db)
     data = self.request[0]
     ans = Package("header#reply")
     reply = ""
     try:
         msg = Package(data.decode('utf-8'))
         header = msg.header
         parm = msg.parm.strip().split(",")
         user = db.get_user(user_id=int(msg.user_id))
         print(msg)
         print(header)
         if header == "/bye":
             reply += "Bye~"
         elif header == "/login":
             assert parm[0]
             user = db.get_user(user_name=parm[0])
             if user is None:
                 user = db.add_user(user_name=parm[0])
             reply += "您的ID为" + str(user.user_id)
             msg.user_id = user.user_id
             user.client_address = self.client_address
         elif header == "/shops":
             reply += "有以下店铺:\n"
             for each in db.shops:
                 reply += "店主:{0} 店名:{1} \n".format(each.owner_id,
                                                    each.shop_name)
         elif header == "/enter":
             assert parm[0]
             shop = db.get_shop(shop_name=parm[0])
             if shop is None:
                 reply += "进店失败!"
             else:
                 shop.customers.append(user.user_id)
                 user.at = shop.owner_id
                 reply += "进店成功!"
                 # 服务器为其发送该商店的商品信息
                 reply += "该商店的商品有\n"
                 for each in shop.goods:
                     goods = db.get_goods(goods_id=int(each))
                     reply += "{0} ({1}) 单件{2}\n".format(
                         goods.goods_name, goods.goods_id, goods.price)
                 try:
                     # 并将该信息发送给商家
                     msg1 = Package("header#msg")
                     msg1.context = "用户{0}访问了你的店铺".format(user.user_name)
                     user = db.get_user(user_id=shop.owner_id)
                     self.request[1].sendto(msg1.send(),
                                            user.client_address)
                 except:
                     pass
         elif header == "/goods":
             shop = db.get_shop(owner_id=user.at)
             if shop is None:
                 reply += "您不在任何商店中"
             else:
                 # 列出所进去的虚拟商店中的商品的情况,包括商品ID,商品名称,单价。
                 reply += "该商店的商品有\n"
                 for each in shop.goods:
                     goods = db.get_goods(goods_id=int(each))
                     reply += "{0} ({1}) 单件{2}\n".format(
                         goods.goods_name, goods.goods_id, goods.price)
         elif header == "/customers":
             shop = db.get_shop(owner_id=user.at)
             if shop is None:
                 reply += "您不在任何商店中"
             else:
                 reply += "该商店中的顾客有\n"
                 for each in shop.customers:
                     reply += db.get_user(
                         user_id=int(each)).user_name + "\n"
         elif header == "/buy":
             assert parm[0]
             goods = db.get_goods(goods_id=int(parm[0]))
             try:
                 msg1 = Package("header#msg")
                 msg1.context = "用户{0}想购买你的商品{1}".format(
                     user.user_name, goods.goods_name)
                 user = db.get_user(user_id=goods.owner_id)
                 # 并将该信息发送给商家
                 self.request[1].sendto(msg1.send(), user.client_address)
             except:
                 pass
             reply += "已发送购买请求"
         elif header == "/leave":
             shop = db.get_shop(owner_id=user.at)
             if shop is None or user.at == user.user_id:
                 reply += "您不在任何商店中"
             else:
                 reply += "已成功离店"
                 user.at = user.user_id
         elif header == "/addgoods":
             assert parm[0] and parm[1]
             shop = db.get_shop(owner_id=user.user_id)
             if shop is None:
                 reply += "您还没有拥有一家店"
             else:
                 db.add_goods(goods_name=parm[0],
                              price=int(parm[1]),
                              owner_id=user.user_id)
                 reply += "商品添加成功"
                 msg1 = Package("header#msg$context#您正在逛的商店有商品添加")
                 try:
                     # 并将该信息发送给正在他店里“逛”的顾客
                     for each in shop.customers:
                         user = db.get_user(user_id=each)
                         self.request[1].sendto(msg1.send(),
                                                user.client_address)
                 except:
                     pass
         elif header == "/msg":
             assert parm[0]
             if user is None or user.user_id != 999:
                 reply += "您没有该权限"
             else:
                 assert parm
                 reply += "消息发送成功!"
                 msg1 = Package("header#msg$context#" + parm[0])
                 try:
                     # 群发和向指定的用户发送消息,用以发送某些提示
                     for each in parm[1:]:
                         user = db.get_user(user_id=int(each))
                         assert user.client_address
                         self.request[1].sendto(msg1.send(),
                                                user.client_address)
                 except:
                     pass
         elif header == "/opennewshop":
             if user is None or user.user_id != 999:
                 reply += "您没有该权限"
             else:
                 shop = db.get_shop(owner_id=user.user_id)
                 if shop is not None:
                     reply += "该用户已有商店"
                 assert parm[0] and parm[1]
                 db.add_shop(shop_name=parm[0], owner_id=int(parm[1]))
                 user = db.get_user(user_id=int(parm[1]))
                 reply += "已开启店铺"
                 try:
                     # 为某个用户开通一个新的虚拟商店并通知用户
                     msg1 = Package("header#msg")
                     msg1.context = "您的店已开启"
                     self.request[1].sendto(msg1.send(),
                                            user.client_address)
                 except:
                     pass
         elif header == "/closeshop":
             if user is None or user.user_id != 999:
                 reply += "您没有该权限"
             else:
                 assert parm[0]
                 shop = db.get_shop(shop_name=parm[0])
                 if shop is None:
                     reply += "不存在叫这个名字的店"
                 else:
                     user = db.get_user(user_id=shop.owner_id)
                     try:
                         # 关闭某一虚拟商城,并通知虚拟商店的拥有者和正在逛的人
                         msg1 = Package("header#msg")
                         msg1.context = "您的店已被关闭"
                         self.request[1].sendto(msg1.send(),
                                                user.client_address)
                         for each in shop.customers:
                             user = db.get_user(user_id=int(each))
                             msg2 = Package("header#msg")
                             msg2.context = "当前店铺已被关闭"
                             self.request[1].sendto(msg2.send(),
                                                    user.client_address)
                     except:
                         pass
                     db.close_shop(shop.owner_id)
                     reply += "已关闭此店"
         elif header == "/users":
             if user is None or user.user_id != 999:
                 reply += "您没有该权限"
             else:
                 reply += "有以下用户\n"
                 print(db.users)
                 for each in db.users:
                     a = "用户ID: {0} 用户名: {1} \n".format(
                         each.user_id, each.user_name)
                     reply += a
                     print(reply)
     except AssertionError:
         reply += "指令参数错误!"
     ans.reply = reply
     self.request[1].sendto(ans.send(), self.client_address)
Beispiel #24
0
        def get_result():
            content = json.loads(request.content.read(),
                                 object_pairs_hook=deunicodify_hook)
            # first will checkif the repo exists
            reponame = content['reponame'].split('/')[0]
            repopath = os.path.join(config['cache'].get('repos'), reponame)
            repo_config = os.path.join(repopath, '%s.json' % reponame)
            if not os.path.exists(repo_config):
                raise OSError(
                    "Repository has not exists, Please create it first!")

            repo_config = json.load(open(repo_config, "r"))
            action_config = repo_config.get(content['action'])

            if not action_config:
                raise OSError("Repository is not support this action.")
            if action_config.get('division'):
                if '/' not in content['reponame']:
                    raise OSError("Reponame should like dde/1207")
                #checkif the division created
                division_path = os.path.join(repopath, content['action'],
                                             content['reponame'].split('/')[1],
                                             'db/packages.db')
                if not os.path.exists(division_path):
                    raise OSError("Division repo is not created.")

            dist = action_config['dist']
            # filter the source from arches
            arches = filter(lambda arch: arch != 'source',
                            repo_config.get(content['action'])['arches'])

            command = "../tools/git.py --pkgname %(pkgname)s --action %(action)s --cachedir %(cache)s \
                --source %(source)s --reponame %(reponame)s" % {
                "pkgname": content['pkgname'],
                "action": content['action'],
                "source": content['source'],
                "cache": config['cache'].get('sources'),
                "reponame": content['reponame']
            }

            if content.get('debian'):
                command += " --debian %(debian)s" % {
                    "debian": content['debian']
                }
            if content.get('version'):
                command += " --version %(version)s" % {
                    "version": content['version']
                }

            try:
                """result will like blow
                {'files': 
                    ['dde-session-ui_4.3.1+2+gc1ab148.dsc', 
                    'dde-session-ui_4.3.1+2+gc1ab148.tar.xz'], 
                'path': '/tmp/git-archive-temp/tmp3HoN4D',
                'version': '4.3.1+2+gc1ab148', 
                'hashsum': 'c1ab1484818011ab76bbe383101b25d33e923ef4'
                }
                """
                result = subprocess.check_output(command,
                                                 shell=True,
                                                 stderr=subprocess.STDOUT)
            except subprocess.CalledProcessError as exc:
                raise exc

            result = json.loads(result)

            for file in result['files']:
                if file.endswith('.dsc'):
                    dsc_file = os.path.join(result['path'], file)
                    _arches = parser_dscfile(dsc_file)
                    break

            if content.get('arches'):
                added_arches = set(content['arches'])
            else:
                added_arches = set()
                for arch in _arches:
                    if arch == 'any':
                        for repo_arch in arches:
                            added_arches.add(repo_arch)
                    elif arch == 'all':
                        added_arches.add(arches[0])
                    elif arch in arches:
                        added_arches.add(arch)

            if len(added_arches) == 0:
                os.system("rm -rf %s" % result['path'])
                raise OSError("None of architecture support with this action.")
            kwargs = {
                'pkgname': content['pkgname'],
                'pkgver': result['version'],
                'reponame': content['reponame'],
                'action': content['action'],
                'hashsum': result['revision'],
                'reponame': content['reponame']
            }

            build_args = []
            if content.get('build_args'):
                build_args.extend(content['build_args'])

            if result.get('build_args'):
                build_args.extend(result['build_args'])

            build_args = set(build_args)
            build_args = '|'.join(build_args)
            if build_args.startswith('|'):
                build_args = build_args[1:]

            if Package.selectBy(**kwargs).count() != 0:
                package = Package.selectBy(**kwargs).orderBy('-id')[0]
                package.triggered = package.triggered + 1
                #update build_args
                if build_args:
                    package.build_args = build_args

                package.upload_status = UploadStatus.UNKNOWN
                for job in Job.selectBy(packageID=package.id):
                    if job.status != JobStatus.BUILDING:
                        job.status = JobStatus.WAIT
            else:
                package = Package(**kwargs)
                if build_args:
                    package.build_args = build_args
                for arch in added_arches:
                    Job(package=package,
                        arch=arch,
                        dist=dist,
                        status=JobStatus.WAIT)

                #save the source to cache
                tasks_cache = config['cache'].get('tasks')
                if not os.path.exists(tasks_cache):
                    os.makedirs(tasks_cache)
                source_cache = os.path.join(tasks_cache, str(package.id),
                                            'source')
                for file in result['files']:
                    os.system(
                        "install -Dm644 %(source)s %(dest)s" % {
                            'source': os.path.join(result['path'], file),
                            'dest': os.path.join(source_cache, file)
                        })
            Log(section='task',
                message='apply %(pkgname)s %(pkgver)s to %(reponame)s' %
                package.dict())
            os.system("rm -rf %s" % result['path'])
            return package.dict()
async def createLabel(y, folder):
    print(f"started at {time.strftime('%X')}")
    # range should be # of threads / # of labels
    for x in range(0, int(os.getenv("HOW_MANY_LABELS_I_NEED"))):
        # Modify Globals to change shipment information
        packageDimensions = PackageDimensions()

        pacakgeWeight = PackageWeight(value=float(totalWeight),
                                      unit=weightUnit)

        packages_to_ship = Package(weight=pacakgeWeight,
                                   dimensions=packageDimensions)

        shipTo = ShipToAddress(
            name=shipToName,
            phone=shipToPhone,
            company_name=shipToCompany,
            address_line1=shipToAddress1,
            address_line2=shipToAddress2,
            city_locality=shipToCity,
            state_province=shipToState,
            postal_code=shipToZip,
            country_code="US",
        )

        shipFrom = ShipFromAddress(
            name=shipFromName,
            phone=shipFromPhone,
            company_name=shipFromCompany,
            address_line1=shipFromAddress1,
            address_line2=shipFromAddress2,
            city_locality=shipFromCity,
            state_province=shipFromState,
            postal_code=shipFromZip,
            country_code="US",
        )

        shipment = Shipment(
            carrier_id=carrierId,
            service_code=serviceCode,
            ship_date=CURRENT_DATE,
            ship_to=shipTo,
            ship_from=shipFrom,
            packages=[packages_to_ship],
        )
        new_data = j.dumps(
            {
                "is_return_label": "true",
                "charge_event": "on_carrier_acceptance",
                "shipment": dataclasses.asdict(shipment),
                "rma_number": os.getenv("RMA_NUMBER"),
            },
            indent=2,
        )
        labelUrl = host + "/v1/labels/"
        r = await post(labelUrl, headers=headers, data=new_data)
        response = r.json()
        jResponse = j.dumps(response, indent=2)
        # Uncomment the following line to print request data for quick debugging
        # print(jResponse)
        data = j.loads(jResponse, parse_int=str)
        status = r.status_code
        if status == 200:
            downloadUrl = data["label_download"]["pdf"]
            print(f"{x + 1}.) label created " + data["label_id"])
            try:
                await downloadPdf(str(x + 1), downloadUrl, folder, data)
            except:
                print("PDF could not be printed - " + data["label_id"])
        elif status == 429:
            sleep_seconds = 90
            print(
                f"LABEL_PROCESS_THROTTLED: Process #{x} -- waiting {sleep_seconds} seconds to retry..."
            )
            time.sleep(sleep_seconds)
        else:
            print(f"Label Number: {x + 1} failed:\n {jResponse}")
Beispiel #26
0
    def parse_packages_by_node(self, lines, package_state):
        """
        Used to parse 'show install active/committed' CLI output.
        Package
            ModulePackageState
            ModulePackageState

        NON-ADMIN: Active
        RP/0/RP0/CPU0:Deploy#show install active
        Node 0/RP0/CPU0 [RP]
            Boot Partition: xr_lv0
            Active Packages: 8
                ncs6k-xr-5.2.5 version=5.2.5 [Boot image]
                ncs6k-mgbl-5.2.5
                ncs6k-mcast-5.2.5
                ncs6k-li-5.2.5
                ncs6k-k9sec-5.2.5
                ncs6k-doc-5.2.5
                ncs6k-mpls-5.2.5
                ncs6k-5.2.5.CSCux82987-1.0.0

        Node 0/RP1/CPU0 [RP]
            Boot Partition: xr_lv0
            Active Packages: 8
                ncs6k-xr-5.2.5 version=5.2.5 [Boot image]
                ncs6k-mgbl-5.2.5
                ncs6k-mcast-5.2.5
                ncs6k-li-5.2.5
                ncs6k-k9sec-5.2.5
                ncs6k-doc-5.2.5
                ncs6k-mpls-5.2.5
                ncs6k-5.2.5.CSCux82987-1.0.0

        ADMIN: Active
        sysadmin-vm:0_RP0:NCS-Deploy2# show install active
        Wed Jun  8  22:47:32.908 UTC
         Node 0/RP0 [RP]
            Active Packages: 2
               ncs6k-sysadmin-5.2.5 version=5.2.5 [Boot image]
               ncs6k-sysadmin-5.2.5.CSCuy44658-1.0.0

         Node 0/RP1 [RP]
            Active Packages: 2
               ncs6k-sysadmin-5.2.5 version=5.2.5 [Boot image]
               ncs6k-sysadmin-5.2.5.CSCuy44658-1.0.0

         Node 0/2 [LC]
            Active Packages: 2
               ncs6k-sysadmin-5.2.5 version=5.2.5 [Boot image]
               ncs6k-sysadmin-5.2.5.CSCuy44658-1.0.0

        """
        package_dict = {}

        if lines:
            trunks = self.get_trunks(lines.splitlines())
            if len(trunks) > 0:
                # Collect all the packages
                package_list = []
                for module in trunks:
                    for package in trunks[module]:
                        if not package in package_list and re.match(
                                "(ncs.*|asr9k.*|iosxr.*|xrv9k.*)", package):
                            package_list.append(package)

                for package_name in package_list:
                    package = Package(name=package_name,
                                      location=None,
                                      state=package_state)

                    # Check which module has this package
                    for module in trunks:
                        for line in trunks[module]:
                            if line == package_name:
                                package.modules_package_state.append(
                                    ModulePackageState(
                                        module_name=module,
                                        package_state=package_state))

                    package_dict[package_name] = package

        return package_dict