Example #1
0
 def __init__(self, farm_url, email):
     self.url = farm_url
     self.email = self.mail_control(email)
     self.time = 10
     self.total_error_time = 10
     self.log = Log()
     self.total_time = 10
Example #2
0
 def __init__(self, params=None):
     Docker.__init__(self, params)
     self.log = Log()
     self.package = None
     self.commit_id = None
     self.queue_id = None
     self.repo = None
     self.branch = None
     self.kernel_requirement = None
     self.job = params.job
Example #3
0
 def __init__(self, parameters=None):
     self.log = Log()
     self.name = None
     self.memory_limit = self.set_memory_limit(parameters.memory_limit)
     self.binds = {}
     self.volumes = []
     self.package_name = None
     self.image = None
     self.cpu_set = self.set_cpu_set(parameters.cpu_set)
     self.command = None
     self.my_client = None
     self.host_config = None
     self.my_container = None
Example #4
0
 def __init__(self, farm_url, email):
     self.url = farm_url
     self.email = self.mail_control(email)
     self.time = 10
     self.total_error_time = 10
     self.log = Log()
     self.total_time = 10
Example #5
0
 def __init__(self, parameters=None):
     self.log = Log()
     self.name = None
     self.memory_limit = self.set_memory_limit(parameters.memory_limit)
     self.binds = {}
     self.volumes = []
     self.package_name = None
     self.image = None
     self.cpu_set = self.set_cpu_set(parameters.cpu_set)
     self.command = None
     self.my_client = None
     self.host_config = None
     self.my_container = None
     self.tmp_status = False
Example #6
0
class Docker:
    def __init__(self, parameters=None):
        self.log = Log()
        self.name = None
        self.memory_limit = self.set_memory_limit(parameters.memory_limit)
        self.binds = {}
        self.volumes = []
        self.package_name = None
        self.image = None
        self.cpu_set = self.set_cpu_set(parameters.cpu_set)
        self.command = None
        self.my_client = None
        self.host_config = None
        self.my_container = None
        self.tmp_status = False

    def start(self):
        # containerımızı parametreleri ile çalıştıracağımız fonksiyonumuz.
        if not self.my_client:
            # my_client'de çalışan docker process'ini yakalıyorum.
            self.my_client = Client(base_url='unix://var/run/docker.sock', version='1.23')

        # container'ımızın host configlerini yapalım.
        self.host_config = self.my_client.create_host_config(mem_limit='%sM' % self.memory_limit, binds=self.binds, security_opt=['seccomp:unconfined'])
        # hadi şimdi aynı isimle bir containerımız var mı görelim.
        self.control_docker()
        # kullanılacak imaj son sürüme yükseltelim
        self.tmp_status = False
        message = '%s imajı güncelleniyor' % self.image
        for line in self.my_client.pull(self.image, stream=True):
            line = json.loads(line.decode('UTF-8'))
            if line['status'] == 'Downloading':
                if self.tmp_status is False:
                    self.log.information(message=message)
                    self.tmp_status = True
                print('  %s' % line['progress'], end='\r')

        if self.tmp_status is True:
            print('')
            self.log.information(message='İmaj son sürüme güncellendi')

        # my_container ile konteynırımızı oluşturuyoruz ve onda saklıyoruz.
        self.my_container = self.my_client.create_container(image=self.image, command=self.command, name=self.name,
                                                            volumes=self.volumes,
                                                            host_config=self.host_config)
        # ve konteynırımızı çalıştırmaya başlıyoruz.
        self.my_client.start(self.name)

    def pause(self):
        # containerımızı durdurmak için çalıştıracağımız fonksiyonumuz.
        self.my_client.pause(self.name)

    def resume(self):
        # containerımızı devam ettirmek için çalıştıracağımız fonksiyonumuz.
        self.my_client.unpause(self.name)

    def stop(self):
        # konteynırımızda ki işlemi iptal etmek için çalıştıracağımız fonksiyonumuz.
        self.my_client.stop(self.name)

    def remove(self):
        # containerımızı silecek fonksiyonumuz
        state = self.my_client.inspect_container(self.name)
        state = state['State']['Running']
        if state is True:
            self.my_client.stop(self.name)
        self.my_client.remove_container(self.name)
        self.volumes = []
        self.binds = {}
        self.name = None
        if self.package_name is not None:
            shutil.rmtree('/tmp/gonullu/%s' % self.package_name, ignore_errors=True)
            shutil.rmtree('/tmp/varpisi/%s' % self.package_name, ignore_errors=True)
            self.package_name = None

    def get_logs(self):
        # burada oluşan log çıktılarımızı yakalayacağız.
        self.my_client.logs(self.name)

    def set_name(self, name):
        # container adımızı atadığımız fonksiyonumuz.
        dictionary = 'abcdefghijklmnopqrstuvxyzABCDEFGHIJKLMNOPQRSTUVXYZ-_1234567890'
        dictionary_len = len(dictionary)
        self.package_name = name
        self.name = ''
        for i in name:
            if i not in dictionary:
                i = dictionary[random.randint(1, dictionary_len)]
            self.name += str(i)
        if len(self.name) == 1:
            self.name += "_"

    @staticmethod
    def set_memory_limit(memory_limit):
        # ram limitimizi atadığımız fonksiyonumuz.
        return int((psutil.virtual_memory().total * (memory_limit / 100))) >> 20

    def set_image(self, image):
        # imajımızı atadığımız fonksiyonumuz.
        self.image = image

    @staticmethod
    def set_cpu_set(cpu_set):
        # atayacağımız cpularımızı atadığımız fonksiyonumuz.
        return int(cpu_set)

    def add_volume(self, local, indocker):
        # bölüm ekleyeceğimiz fonksiyonumuz.
        self.volumes.append(indocker)
        self.binds[local] = {'bind': indocker, 'mode': 'rw'}

    def set_command(self, application, queue_id, commit_id, package):
        # çalıştıracağımız komutu atadığımız fonksiyonumuz.
        self.command = '%s %s %s %s' % (application, queue_id, commit_id, package)

    def check(self):
        # derleme işlemi devam ediyor mu kontrol edelim
        for container in self.my_client.containers():
            if container['Names'][0].replace('/', '') == self.name:
                return 0
        else:
            return 1

    def control_docker(self):
        # oluşacak paketin adı ile önceden docker kaydı var mı kontrol edelim.
        for container in self.my_client.containers(all=True):
            if container['Names'][0].replace('/', '') == self.name:
                self.remove()

    def exit_signal(self, signal, frame):
        if self.name is not None:
            self.remove()

        self.log.blank_line()
        self.log.warning(message='CTRL+C\'ye tıkladınız!')
        self.log.get_exit()
Example #7
0
class Farm:
    def __init__(self, farm_url, email):
        self.url = farm_url
        self.email = self.mail_control(email)
        self.time = 10
        self.total_error_time = 10
        self.log = Log()
        self.total_time = 10

    def get(self, request, json=True):
        # Get isteğini işleyip json data dönen fonksiyonumuz.
        try:
            response = requests.get('%s/%s' % (self.url, request))
            if json:
                self.total_error_time = 10
                return response.json()
            else:
                self.total_error_time = 10
                return response
        except requests.ConnectionError:
            self.log.error(
                'Sunucuya %s saniyedir erişilemedi tekrar bağlanmaya çalışıyor!'
                % self.total_error_time,
                continued=True)
            self.total_error_time += 10
            self.total_time = 10
            return -2

    def send_file(self, package, binary_path):
        # Oluşan çıktı dosyalarını çiftliğe gönderen fonksiyonumuz.
        output_files = glob.glob('/tmp/gonullu/%s/*.[lpe]*' % package)
        for file in output_files:
            if self.send(file, binary_path):
                pass
            else:
                while not (self.send(file, binary_path)):
                    self.log.warning(
                        message='%s dosyası tekrar gönderilmeye çalışılacak.' %
                        file)
                    self.wait()
        return True

    def send(self, file, binary_path):
        self.log.information(message='%s dosyası gönderiliyor.' %
                             file.split('/')[-1])
        if file.split('.')[-1] in ('err', 'log'):
            content = open(file, 'r').read()
            html = open('%s.html' % file, 'w')
            html.write('<html><body><pre>')
            html.write(content)
            html.write('</pre></body></html>')
            html.close()
            file = '%s.html' % file

        f = {'file': open(file, 'rb')}
        try:
            r = requests.post('%s/%s' % (self.url, 'upload'),
                              files=f,
                              data={'binrepopath': binary_path})
            hashx = self.sha1file(file)

            file = file.split('/')[-1]
            if hashx == r.text.strip():
                self.log.success(message='%s dosyası başarı ile gönderildi.' %
                                 file)
                return True
            else:
                self.log.error(message='%s dosyası gönderilemedi!' % file)
                return False
        except requests.ConnectionError:
            self.log.error(message='%s dosyası gönderilemedi!' % file)
            return False

    def get_package(self):
        request = '%s/%s' % ('requestPkg', self.email)
        response = self.get(request)

        if response == -1:
            return -1

        if response == -2:
            time.sleep(self.time)
            self.total_time += self.time
            return -2

        elif response['state'] == 200:
            self.log.information(
                message='Yeni paket bulundu, paketin adı: %s' %
                response['package'])
            self.total_time = 0
            return response

        elif response['state'] == 401:
            self.log.error(message='Mail adresiniz yetkili değil!')
            self.log.get_exit()

        elif response['state'] == 402:
            return -1

        elif response['state'] == 403:
            self.log.error(message='Docker imajı bulunamadı!')
            self.log.get_exit()

        else:
            self.log.error(message='Tanımlı olmayan bir hata oluştu!')
            self.log.get_exit()

    def wait(self, message='', reset=False):
        if reset is True:
            self.total_time = 0

        if not message == '':
            information_message = '%d saniye%s' % (self.total_time, message)
            self.log.information(message=information_message, continued=True)
        time.sleep(self.time)
        self.total_time += self.time

    def get_total_time(self):
        return self.total_time

    def running_process(self):
        # uygulama çalışmaya devam ettiği sürece siteye bildirim göndereceğiz.
        # TODO: İlker abiden devam ediyor olan uygulamalar kısmına bunun ile ilgili bir servis isteyeceğiz.
        pass

    def complete_process(self):
        # uygulama çalışması bitince çalışacak olan prosedür fonksiyonumuz.
        pass

    @staticmethod
    def mail_control(email):
        # Mail adresimiz onaylı mı diye kontrol eden fonksiyonumuz.
        # TODO: İlker abiden mail adresi onaylı mı diye istek yapabileceğimiz bir url isteyeceğiz.
        return email

    @staticmethod
    def sha1file(filepath):
        import hashlib
        sha = hashlib.sha1()
        with open(filepath, 'rb') as f:
            while True:
                block = f.read(2**20)  # Magic number: one-megabyte  blocks.
                if not block:
                    break
                sha.update(block)
            return sha.hexdigest()
Example #8
0
class Volunteer(Docker):
    def __init__(self, params=None):
        Docker.__init__(self, params)
        self.log = Log()
        self.package = None
        self.commit_id = None
        self.queue_id = None
        self.repo = None
        self.branch = None
        self.kernel_requirement = None
        self.job = params.job

    def get_package_farm(self, response):
        self.package = response['package']
        self.set_name(self.package)
        self.add_volume('/var/cache/pisi/packages', '/var/cache/pisi/packages')
        self.add_volume('/var/cache/pisi/archives', '/var/cache/pisi/archives')
        self.add_volume('/tmp/gonullu/build', '/build')
        self.add_volume('/tmp/varpisi/%s' % self.package, '/var/pisi')
        self.add_volume('/tmp/gonullu/%s' % self.package,
                        '/root/%s' % self.package)
        self.repo = response['repo']
        self.branch = response['branch']
        self.set_image(response['dockerimage'])
        self.commit_id = response['commit_id']
        self.kernel_requirement = response['kernel_required']
        self.sandbox_requirement = self.sandbox_is_require()
        self.queue_id = response['queue_id']
        self.preparation(self.kernel_requirement, self.sandbox_requirement,
                         self.package, self.job)
        self.set_command('/build/build-%s.sh' % self.package, self.queue_id,
                         self.commit_id, self.package)
        self.start()

    def sandbox_is_require(self):
        config_file = os.path.join(os.path.dirname(__file__),
                                   'config/sandbox-requirement.yml')

        with open(config_file, 'r') as sandbox_file:
            try:
                #FIXME! yaml.load(input) is depricated
                if self.package in yaml.load(sandbox_file,
                                             Loader=yaml.FullLoader):
                    return False
            except:
                self.log.error(message='%s dosyası işlenemedi' % config_file)
                self.log.get_exit()

        return True

    @staticmethod
    def preparation(kernel_require, sandbox_requirement, package, j=5):
        krn = ' '
        sandbox = ' '
        if kernel_require is True:
            krn = ' kernel '

        if sandbox_requirement is False:
            sandbox = ' --ignore-sandbox '

        build_sh = """#!/bin/bash
service dbus start && pisi cp && update-ca-certificates && pisi ar pisiBeta https://ciftlik.pisilinux.org/2.0-Beta.1/pisi-index.xml.xz && pisi it --ignore-safety --ignore-dependency autoconf autogen automake binutils bison flex gawk gc gcc gnuconfig guile libmpc libsigsegv libtool-ltdl libtool lzo m4 make mpfr nasm pkgconfig yacc glibc-devel isl %s
pisi ar core --ignore-check https://github.com/pisilinux/core/raw/master/pisi-index.xml.xz && pisi ar main --ignore-check https://github.com/pisilinux/main/raw/master/pisi-index.xml.xz --at 2
pisi ur
sed -i 's/-j5/-j%d/g' /etc/pisi/pisi.conf
sed -i 's/build_host = localhost/build_host=farmV5/g'   /etc/pisi/pisi.conf
cd /root
pisi bi --ignore-safety%s-y $3 1>/root/%s/$1-$2-$3.log 2>/root/%s/$1-$2-$3.err
STAT=$?
for s in `ls *.pisi`
do
    mv $s /root/%s/$1-$2-$s
done
echo $STAT >  /root/%s/$3.bitti
""" % (krn, j, sandbox, package, package, package, package)

        build_directory = os.path.join('/', 'tmp', 'gonullu', 'build')
        if not os.path.exists(build_directory):
            os.makedirs(build_directory)

        f = open(os.path.join(build_directory, 'build-%s.sh' % package), 'w')
        f.write(build_sh)
        f.close()
        os.chmod(os.path.join(build_directory, 'build-%s.sh' % package), 0o755)
Example #9
0
class Docker:
    def __init__(self, parameters=None):
        self.log = Log()
        self.name = None
        self.memory_limit = self.set_memory_limit(parameters.memory_limit)
        self.binds = {}
        self.volumes = []
        self.package_name = None
        self.image = None
        self.cpu_set = self.set_cpu_set(parameters.cpu_set)
        self.command = None
        self.my_client = None
        self.host_config = None
        self.my_container = None
        self.tmp_status = False

    def start(self):
        # containerımızı parametreleri ile çalıştıracağımız fonksiyonumuz.
        if not self.my_client:
            # my_client'de çalışan docker process'ini yakalıyorum.
            self.my_client = Client(base_url='unix://var/run/docker.sock')

        # container'ımızın host configlerini yapalım.
        self.host_config = self.my_client.create_host_config(mem_limit='%sM' % self.memory_limit, binds=self.binds)
        # hadi şimdi aynı isimle bir containerımız var mı görelim.
        self.control_docker()
        # kullanılacak imaj son sürüme yükseltelim
        self.tmp_status = False
        message = '%s imajı güncelleniyor' % self.image
        for line in self.my_client.pull(self.image, stream=True):
            line = json.loads(line.decode('UTF-8'))
            if line['status'] == 'Downloading':
                if self.tmp_status is False:
                    self.log.information(message=message)
                    self.tmp_status = True
                print('  %s' % line['progress'], end='\r')

        if self.tmp_status is True:
            print('')
            self.log.information(message='İmaj son sürüme güncellendi')

        # my_container ile konteynırımızı oluşturuyoruz ve onda saklıyoruz.
        self.my_container = self.my_client.create_container(image=self.image, command=self.command, name=self.name,
                                                            volumes=self.volumes,
                                                            host_config=self.host_config)
        # ve konteynırımızı çalıştırmaya başlıyoruz.
        self.my_client.start(self.name)

    def pause(self):
        # containerımızı durdurmak için çalıştıracağımız fonksiyonumuz.
        self.my_client.pause(self.name)

    def resume(self):
        # containerımızı devam ettirmek için çalıştıracağımız fonksiyonumuz.
        self.my_client.unpause(self.name)

    def stop(self):
        # konteynırımızda ki işlemi iptal etmek için çalıştıracağımız fonksiyonumuz.
        self.my_client.stop(self.name)

    def remove(self):
        # containerımızı silecek fonksiyonumuz
        state = self.my_client.inspect_container(self.name)
        state = state['State']['Running']
        if state is True:
            self.my_client.stop(self.name)
        self.my_client.remove_container(self.name)
        self.volumes = []
        self.binds = {}
        self.name = None
        if self.package_name is not None:
            shutil.rmtree('/tmp/gonullu/%s' % self.package_name, ignore_errors=True)
            shutil.rmtree('/tmp/varpisi/%s' % self.package_name, ignore_errors=True)
            self.package_name = None

    def get_logs(self):
        # burada oluşan log çıktılarımızı yakalayacağız.
        self.my_client.logs(self.name)

    def set_name(self, name):
        # container adımızı atadığımız fonksiyonumuz.
        dictionary = 'abcdefghijklmnopqrstuvxyzABCDEFGHIJKLMNOPQRSTUVXYZ-_1234567890'
        dictionary_len = len(dictionary)
        self.package_name = name
        self.name = ''
        for i in name:
            if i not in dictionary:
                i = dictionary[random.randint(1, dictionary_len)]
            self.name += str(i)
        if len(self.name) == 1:
            self.name += "_"

    @staticmethod
    def set_memory_limit(memory_limit):
        # ram limitimizi atadığımız fonksiyonumuz.
        return int((psutil.virtual_memory().total * (memory_limit / 100))) >> 20

    def set_image(self, image):
        # imajımızı atadığımız fonksiyonumuz.
        self.image = image

    @staticmethod
    def set_cpu_set(cpu_set):
        # atayacağımız cpularımızı atadığımız fonksiyonumuz.
        return int(cpu_set)

    def add_volume(self, local, indocker):
        # bölüm ekleyeceğimiz fonksiyonumuz.
        self.volumes.append(indocker)
        self.binds[local] = {'bind': indocker, 'mode': 'rw'}

    def set_command(self, application, queue_id, commit_id, package):
        # çalıştıracağımız komutu atadığımız fonksiyonumuz.
        self.command = '%s %s %s %s' % (application, queue_id, commit_id, package)

    def check(self):
        # derleme işlemi devam ediyor mu kontrol edelim
        for container in self.my_client.containers():
            if container['Names'][0].replace('/', '') == self.name:
                return 0
        else:
            return 1

    def control_docker(self):
        # oluşacak paketin adı ile önceden docker kaydı var mı kontrol edelim.
        for container in self.my_client.containers(all=True):
            if container['Names'][0].replace('/', '') == self.name:
                self.remove()

    def exit_signal(self, signal, frame):
        if self.name is not None:
            self.remove()

        self.log.blank_line()
        self.log.warning(message='CTRL+C\'ye tıkladınız!')
        self.log.get_exit()
Example #10
0
class Farm:
    def __init__(self, farm_url, email):
        self.url = farm_url
        self.email = self.mail_control(email)
        self.time = 10
        self.total_error_time = 10
        self.log = Log()
        self.total_time = 10

    def get(self, request, json=True):
        # Get isteğini işleyip json data dönen fonksiyonumuz.
        try:
            response = requests.get('%s/%s' % (self.url, request))
            if json:
                self.total_error_time = 10
                return response.json()
            else:
                self.total_error_time = 10
                return response
        except requests.ConnectionError:
            self.log.error('Sunucuya %s saniyedir erişilemedi tekrar bağlanmaya çalışıyor!' % self.total_error_time,
                           continued=True)
            self.total_error_time += 10
            self.total_time = 10
            return -2

    def send_file(self, package, binary_path):
        # Oluşan çıktı dosyalarını çiftliğe gönderen fonksiyonumuz.
        output_files = glob.glob('/tmp/gonullu/%s/*.[lpe]*' % package)
        for file in output_files:
            if self.send(file, binary_path):
                pass
            else:
                while not (self.send(file, binary_path)):
                    self.log.warning(message='%s dosyası tekrar gönderilmeye çalışılacak.' % file)
                    self.wait()
        return True

    def send(self, file, binary_path):
        self.log.information(message='%s dosyası gönderiliyor.' % file.split('/')[-1])
        if file.split('.')[-1] in ('err', 'log'):
            content = open(file, 'r').read()
            html = open('%s.html' % file, 'w')
            html.write('<html><body><pre>')
            html.write(content)
            html.write('</pre></body></html>')
            html.close()
            file = '%s.html' % file

        f = {'file': open(file, 'rb')}
        try:
            r = requests.post('%s/%s' % (self.url, 'upload'), files=f, data={'binrepopath': binary_path})
            hashx = self.sha1file(file)

            file = file.split('/')[-1]
            if hashx == r.text.strip():
                self.log.success(message='%s dosyası başarı ile gönderildi.' % file)
                return True
            else:
                self.log.error(message='%s dosyası gönderilemedi!' % file)
                return False
        except requests.ConnectionError:
            self.log.error(message='%s dosyası gönderilemedi!' % file)
            return False

    def get_package(self):
        request = '%s/%s' % ('requestPkg', self.email)
        response = self.get(request)

        if response == -1:
            return -1

        if response == -2:
            time.sleep(self.time)
            self.total_time += self.time
            return -2

        elif response['state'] == 200:
            self.log.information(message='Yeni paket bulundu, paketin adı: %s' % response['package'])
            self.total_time = 0
            return response

        elif response['state'] == 401:
            self.log.error(message='Mail adresiniz yetkili değil!')
            self.log.get_exit()

        elif response['state'] == 402:
            return -1

        elif response['state'] == 403:
            self.log.error(message='Docker imajı bulunamadı!')
            self.log.get_exit()

        else:
            self.log.error(message='Tanımlı olmayan bir hata oluştu!')
            self.log.get_exit()

    def wait(self, message='', reset=False):
        if reset is True:
            self.total_time = 0

        if not message == '':
            information_message = '%d saniye%s' % (self.total_time, message)
            self.log.information(message=information_message, continued=True)
        time.sleep(self.time)
        self.total_time += self.time

    def get_total_time(self):
        return self.total_time

    def running_process(self):
        # uygulama çalışmaya devam ettiği sürece siteye bildirim göndereceğiz.
        # TODO: İlker abiden devam ediyor olan uygulamalar kısmına bunun ile ilgili bir servis isteyeceğiz.
        pass

    def complete_process(self):
        # uygulama çalışması bitince çalışacak olan prosedür fonksiyonumuz.
        pass

    @staticmethod
    def mail_control(email):
        # Mail adresimiz onaylı mı diye kontrol eden fonksiyonumuz.
        # TODO: İlker abiden mail adresi onaylı mı diye istek yapabileceğimiz bir url isteyeceğiz.
        return email

    @staticmethod
    def sha1file(filepath):
        import hashlib
        sha = hashlib.sha1()
        with open(filepath, 'rb') as f:
            while True:
                block = f.read(2 ** 20)  # Magic number: one-megabyte  blocks.
                if not block:
                    break
                sha.update(block)
            return sha.hexdigest()