Ho ngola GUI bakeng sa 1C RAC, kapa hape ka Tcl/Tk

Ha re ntse re hlahloba taba ea hore na lihlahisoa tsa 1C li sebetsa joang tikolohong ea Linux, ho ile ha sibolloa tšitiso e le 'ngoe - khaello ea sesebelisoa se bonolo sa li-platform tse ngata tsa ho laola sehlopha sa li-server tsa 1C. 'Me ho ile ha etsoa qeto ea ho lokisa bothata bona ka ho ngola GUI bakeng sa sesebelisoa sa rac console. Tcl / tk e khethiloe e le puo ea tsoelo-pele, ka maikutlo a ka, e loketseng ka ho fetisisa bakeng sa mosebetsi ona. 'Me kahoo, ke rata ho hlahisa likarolo tse ling tse thahasellisang tsa tharollo boitsebisong bona.

Ho sebetsa o tla hloka kabo ea tcl/tk le 1C. 'Me kaha ke nkile qeto ea ho sebelisa bokhoni ba mantlha ba ho fana ka tcl / tk ntle le ho sebelisa liphutheloana tsa batho ba bang, ke tla hloka mofuta oa 8.6.7, o kenyelletsang ttk - sephutheloana se nang le likarolo tse ling tsa litšoantšo, tseo re li hlokang haholo-holo ttk. ::TreeView, e lumella data ea pontšo ka bobeli ka mokhoa oa sebopeho sa sefate le ka mokhoa oa tafole (lenane). Hape, phetolelong e ncha, mosebetsi ntle le mekhelo o tsosolositsoe (taelo ea teko, e sebelisoang morerong ha ho etsoa litaelo tsa ka ntle).

Morero o na le lifaele tse 'maloa (le hoja ho se letho le u thibelang ho etsa ntho e' ngoe le e 'ngoe):

rac_gui.cfg - tlhophiso ea kamehla
rac_gui.tcl - sengoloa sa mantlha sa ho qala
Lib directory e na le lifaele tse kentsoeng ka bo eona qalong:
function.tcl - faele e nang le mekhoa
gui.tcl - sebopeho sa mantlha sa setšoantšo
litšoantšo.tcl - laebrari ea litšoantšo ea base64

Faele ea rac_gui.tcl, ha e le hantle, e qala mofetoleli, e qala mefuta e fapaneng, e jara li-modules, configs, joalo-joalo. Litaba tsa faele tse nang le maikutlo:

rac_gui.tcl

#!/bin/sh
exec wish "$0" -- "$@"

# Устанавливаем текущий каталог
set dir(root) [pwd]
# Устанавливаем рабочий каталог, если его нет то создаём
set dir(work) [file join $env(HOME) .rac_gui]
if {[file exists $dir(work)] == 0 } {
    file mkdir $dir(work)    
}
# каталог с модулями
set dir(lib) "[file join $dir(root) lib]"

# загружаем пользовательский конфиг, если он отсутствует, то копируем дефолтный
if {[file exists [file join $dir(work) rac_gui.cfg]] ==0} {
    file copy [file join [pwd] rac_gui.cfg] [file join $dir(work) rac_gui.cfg]
} 
source [file join $dir(work) rac_gui.cfg]
# Код проверки наличия rac и правильности указания пути в конфиге
# если программа не найдена то будет выведен диалог для указания корректного пути
# и этот путь будет записан в пользовательский конфиг
if {[file exists $rac_cmd] == 0} {
    set rac_cmd [tk_getOpenFile -initialdir $env(HOME) -parent . -title "Укажите путь до rac" -initialfile rac]
    file copy [file join $dir(work) rac_gui.cfg] [file join $dir(work) rac_gui.cfg.bak] 
    set orig_file [open [file join $dir(work) rac_gui.cfg.bak] "r"]
    set file [open [file join $dir(work) rac_gui.cfg] "w"]
    while {[gets $orig_file line] >=0 } {
        if {[string match "set rac_cmd*" $line]} {
            puts $file "set rac_cmd $rac_cmd"
        } else {
            puts $file $line
        }
    }
    close $file
    close $orig_file
    #return "$host:$port"
    file delete [file join $dir(work) 1c_srv.cfg.bak] 
} else {
    puts "Found $rac_cmd"
}

set cluster_user ""
set cluster_pwd ""
set agent_user ""
set agent_pwd ""
## LOAD FILE ##
# Загружаем модули кроме gui.tcl так как его надо загрузить последним
foreach modFile [lsort [glob -nocomplain [file join $dir(lib) *.tcl]]] {
    if {[file tail $modFile] ne "gui.tcl"} {
        source $modFile
        puts "Loaded module $modFile"
    }
}
source [file join $dir(lib) gui.tcl]
source [file join $dir(work) rac_gui.cfg]

# Читаем файл со списком серверов 1С
# и добавляем в дерево
if [file exists [file join $dir(work) 1c_srv.cfg]] {
    set f [open [file join $dir(work) 1c_srv.cfg] "RDONLY"]
    while {[gets $f line] >=0} {
        .frm_tree.tree insert {} end -id "server::$line" -text "$line" -values "$line"
    }    
}

Ka mor'a ho khoasolla ntho e 'ngoe le e' ngoe e hlokahalang le ho hlahloba boteng ba rac utility, fensetere ea graphical e tla hlahisoa. Sehokelo sa lenaneo se na le lintlha tse tharo:

Toolbar, sefate le lethathamo

Ke entse hore litaba tsa "sefate" li tšoane ka hohle kamoo ho ka khonehang le lisebelisoa tse tloaelehileng tsa Windows ho tloha 1C.

Ho ngola GUI bakeng sa 1C RAC, kapa hape ka Tcl/Tk

Khoutu e kholo e etsang fensetere ena e fumaneha faeleng
lib/gui.tcl

# установка размера и положения основного окна
# можно установить в переменную topLevelGeometry в конфиг программы
if {[info exists topLevelGeometry]} {
    wm geometry . $topLevelGeometry
} else {
    wm geometry . 1024x768
}
# Заголовок окна
wm title . "1C Rac GUI"
wm iconname . "1C Rac Gui"
# иконка окна (берется из файла lib/imges.tcl)
wm iconphoto . tcl
wm protocol . WM_DELETE_WINDOW Quit
wm overrideredirect . 0
wm positionfrom . user

ttk::style theme use clam

# Панель инсрументов
set frm_tool [frame .frm_tool]
pack $frm_tool -side left -fill y 
ttk::panedwindow .panel -orient horizontal -style TPanedwindow
pack .panel -expand true -fill both
pack propagate .panel false

ttk::button $frm_tool.btn_add  -command Add  -image add_grey_32
ttk::button $frm_tool.btn_del  -command Del -image del_grey_32
ttk::button $frm_tool.btn_edit  -command Edit -image edit_grey_32
ttk::button $frm_tool.btn_quit -command Quit -image quit_grey_32

pack $frm_tool.btn_add $frm_tool.btn_del $frm_tool.btn_edit -side top -padx 5 -pady 5
pack $frm_tool.btn_quit  -side bottom -padx 5 -pady 5

# Дерево с полосами прокрутки
set frm_tree [frame .frm_tree]

ttk::scrollbar $frm_tree.hsb1 -orient horizontal -command [list $frm_tree.tree xview]
ttk::scrollbar $frm_tree.vsb1 -orient vertical -command [list $frm_tree.tree yview]
set tree [ttk::treeview $frm_tree.tree -show tree 
-xscrollcommand [list $frm_tree.hsb1 set] -yscrollcommand [list $frm_tree.vsb1 set]]

grid $tree -row 0 -column 0 -sticky nsew
grid $frm_tree.vsb1 -row 0 -column 1 -sticky nsew
grid $frm_tree.hsb1 -row 1 -column 0 -sticky nsew
grid columnconfigure $frm_tree 0 -weight 1
grid rowconfigure $frm_tree 0 -weight 1

# назначение обработчика нажатия кнопкой мыши
bind $frm_tree.tree <ButtonRelease> "TreePress $frm_tree.tree"

# Список для данных (таблица)
set frm_work [frame .frm_work]
ttk::scrollbar $frm_work.hsb -orient horizontal -command [list $frm_work.tree_work xview]
ttk::scrollbar $frm_work.vsb -orient vertical -command [list $frm_work.tree_work yview]
set tree_work [
    ttk::treeview $frm_work.tree_work 
    -show headings  -columns "par val" -displaycolumns "par val"
    -xscrollcommand [list $frm_work.hsb set] 
    -yscrollcommand [list $frm_work.vsb set]
]
# Установка цветов для чередования в таблице
$tree_work tag configure dark -background $color(dark_table_bg)
$tree_work tag configure light -background $color(light_table_bg)

# Размещение элементов на форме
grid $tree_work -row 0 -column 0 -sticky nsew
grid $frm_work.vsb -row 0 -column 1 -sticky nsew
grid $frm_work.hsb -row 1 -column 0 -sticky nsew
grid columnconfigure $frm_work 0 -weight 1
grid rowconfigure $frm_work 0 -weight 1
pack $frm_tree $frm_work -side left -expand true -fill both

#.panel add $frm_tool -weight 1
.panel add $frm_tree -weight 1 
.panel add $frm_work -weight 1

Algorithm ea ho sebetsa le lenaneo ke e latelang:

1. Ntlha ea pele, u lokela ho eketsa seva se seholo sa lihlopha (ke hore, seva sa tsamaiso ea lihlopha (ho Linux, tsamaiso e qalisoa ka taelo "/opt/1C/v8.3/x86_64/ras cluster -daemon").

Ho etsa sena, tobetsa konopo ea "+" 'me fensetereng e butsoeng, kenya aterese ea seva le boema-kepe:

Ho ngola GUI bakeng sa 1C RAC, kapa hape ka Tcl/Tk

Ka mor'a moo, seva sa rona se tla hlaha sefateng ka ho tobetsa ho sona, lethathamo la lihlopha le tla buleha kapa ho tla hlaha phoso ea khokahanyo.

2. Ho tobetsa lebitsong la cluster ho tla bula lenane la mesebetsi e fumanehang bakeng sa eona.

3.…

Le joalo-joalo, i.e. ho kenya sehlopha se secha, khetha leha e le efe e fumanehang lethathamong ebe o tobetsa konopo ea "+" ka har'a toolbar 'me puisano e ncha e tla hlahisoa:

Ho ngola GUI bakeng sa 1C RAC, kapa hape ka Tcl/Tk

Likonopo tse ka har'a toolbar li etsa mesebetsi ho latela moelelo, ke hore. Ho itšetlehile ka hore na ke karolo efe ea sefate kapa lethathamo le khethiloeng, mokhoa o le mong kapa o mong o tla etsoa.

Ha re shebeng mohlala oa konopo ea ho eketsa (“+”):

Khoutu ea ho etsa likonopo:

ttk::button $frm_tool.btn_add  -command Add  -image add_grey_32

Mona re bona hore ha konopo e tobetse, ho tla etsoa ts'ebetso ea "Add", khoutu ea eona:

proc Add {} {
    global active_cluster host
    # Определяем идентификатор выделенного элемента
    set id  [.frm_tree.tree selection] 
    # Определяем значение этого элемента
    set values [.frm_tree.tree item [.frm_tree.tree selection] -values]
    set key [lindex [split $id "::"] 0]
    # в зависимости от того что выделили будет запущена нужная процедура
    if {$key eq "" || $key eq "server"} {
        set host [ Add::server ]
        return
    }
    Add::$key .frm_tree.tree $host $values
}

Mona ke o mong oa melemo ea tickle: o ka fetisa boleng ba ho feto-fetoha joalo ka lebitso la ts'ebetso:

Add::$key .frm_tree.tree $host $values

Ke hore, mohlala, haeba re supa ho seva se seholo ebe o tobetsa "+", joale Add::mosebetsi oa seva o tla qalisoa, haeba ho sehlopha - Eketsa:: sehlopha joalo-joalo (ke tla ngola moo "linotlolo" tse hlokahalang li tsoa hanyane ka tlase), lits'ebetso tse thathamisitsoeng li hula likarolo tse hlakileng tse lumellanang le moelelo oa taba.

Joalokaha e ka 'na eaba u se u hlokometse, liforomo li tšoana ka mokhoa - sena ha se makatse, hobane li bontšoa ke mokhoa o le mong, ka ho toba sebopeho se seholo sa foromo (fensetere, li-buttons, setšoantšo, label), lebitso la ts'ebetso. AddTopLevel

proc AddToplevel {lbl img {win_name .add}} {
    set cmd "destroy $win_name"
    if [winfo exists $win_name] {destroy $win_name}
    toplevel $win_name
    wm title $win_name $lbl
    wm iconphoto $win_name tcl
    # метка с иконкой
    ttk::label $win_name.lbl -image $img
    # фрейм с полями ввода
    set frm [ttk::labelframe $win_name.frm -text $lbl -labelanchor nw]
    
    grid columnconfigure $frm 0 -weight 1
    grid rowconfigure $frm 0 -weight 1
    # фрейм и кнопки
    set frm_btn [frame $win_name.frm_btn -border 0]
    ttk::button $frm_btn.btn_ok -image ok_grey_24 -command { }
    ttk::button $frm_btn.btn_cancel -command $cmd -image quit_grey_24 
    grid $win_name.lbl -row 0 -column 0 -sticky nw -padx 5 -pady 10
    grid $frm -row 0 -column 1 -sticky nw -padx 5 -pady 5
    grid $frm_btn -row 1 -column 1 -sticky se -padx 5 -pady 5
    pack  $frm_btn.btn_cancel  -side right
    pack  $frm_btn.btn_ok  -side right -padx 10
    return $frm
}

Mekhahlelo ea ho letsetsa: sehlooho, lebitso la setšoantšo sa aekhone ho tsoa laebraring (lib/images.tcl) le paramethara ea lebitso la fensetere (ea kamehla .add). Kahoo, haeba re nka mehlala e kaholimo bakeng sa ho eketsa seva ea mantlha le sehlopha, mohala o tla ba joalo:

AddToplevel "Добавление основного сервера" server_grey_64

kapa

AddToplevel "Добавление кластера" cluster_grey_64

Hantle, ho tsoela pele ka mehlala ena, ke tla bontša mekhoa e bontšang ho eketsa lipuisano bakeng sa seva kapa sehlopha.

Eketsa::server

proc Add::server {} {
    global default
    # выводим основную форму
    set frm [AddToplevel "Добавление основного сервера" server_grey_64]
    # добавляем етки и поля ввода на эту форму
    label $frm.lbl_host -text "Адрес сервера"
    entry  $frm.ent_host
    label $frm.lbl_port -text "Порт"
    entry $frm.ent_port 
    $frm.ent_port  insert end $default(port)
    grid $frm.lbl_host -row 0 -column 0 -sticky nw -padx 5 -pady 5
    grid $frm.ent_host -row 0 -column 1 -sticky nsew -padx 5 -pady 5
    grid $frm.lbl_port -row 1 -column 0 -sticky nw -padx 5 -pady 5
    grid $frm.ent_port -row 1 -column 1 -sticky nsew -padx 5 -pady 5
    grid columnconfigure $frm 0 -weight 1
    grid rowconfigure $frm 0 -weight 1
    #set frm_btn [frame .add.frm_btn -border 0]
    # переопределяем обработчик нажатия кнопки
    .add.frm_btn.btn_ok configure -command {
        set host [SaveMainServer [.add.frm.ent_host get] [.add.frm.ent_port get]]
        .frm_tree.tree insert {} end -id "server::$host" -text "$host" -values "$host"
        destroy .add
        return $host
    }
    return $frm
}

Eketsa::sehlopha

proc Add::cluster {tree host values} {
    global default lifetime_limit expiration_timeout session_fault_tolerance_level
    global max_memory_size max_memory_time_limit errors_count_threshold security_level
    global load_balancing_mode kill_problem_processes 
    agent_user agent_pwd cluster_user cluster_pwd auth_agent
    if {$agent_user ne "" && $agent_pwd ne ""} {
        set auth_agent "--agent-user=$agent_user --agent-pwd=$agent_pwd"
    } else {
        set auth_agent ""
    }
    # устанавливаем глобальные переменные ()
    set lifetime_limit $default(lifetime_limit)
    set expiration_timeout $default(expiration_timeout)
    set session_fault_tolerance_level $default(session_fault_tolerance_level)
    set max_memory_size $default(max_memory_size)
    set max_memory_time_limit $default(max_memory_time_limit)
    set errors_count_threshold $default(errors_count_threshold)
    set security_level [lindex $default(security_level) 0]
    set load_balancing_mode [lindex $default(load_balancing_mode) 0]
    
    set frm [AddToplevel "Добавление кластера" cluster_grey_64]
    
    label $frm.lbl_host -text "Адрес основного сервера"
    entry  $frm.ent_host
    label $frm.lbl_port -text "Порт"
    entry $frm.ent_port 
    $frm.ent_port  insert end $default(port)
    label $frm.lbl_name -text "Название кластера"
    entry  $frm.ent_name
    label $frm.lbl_secure_connect -text "Защищённое соединение"
    ttk::combobox $frm.cb_security_level -textvariable security_level -values $default(security_level)
    label $frm.lbl_expiration_timeout -text "Останавливать выключенные процессы через:"
    entry  $frm.ent_expiration_timeout -textvariable expiration_timeout
    label $frm.lbl_session_fault_tolerance_level -text "Уровень отказоустойчивости"
    entry  $frm.ent_session_fault_tolerance_level -textvariable session_fault_tolerance_level
    label $frm.lbl_load_balancing_mode -text "Режим распределения нагрузки"
    ttk::combobox $frm.cb_load_balancing_mode -textvariable load_balancing_mode 
    -values $default(load_balancing_mode)
    label $frm.lbl_errors_count_threshold -text "Допустимое отклонение количества ошибок сервера, %"
    entry  $frm.ent_errors_count_threshold -textvariable errors_count_threshold
    label $frm.lbl_processes -text "Рабочие процессы:"
    label $frm.lbl_lifetime_limit -text "Период перезапуска, сек."
    entry  $frm.ent_lifetime_limit -textvariable lifetime_limit
    label $frm.lbl_max_memory_size -text "Допустимый объём памяти, КБ"
    entry  $frm.ent_max_memory_size -textvariable max_memory_size
    label $frm.lbl_max_memory_time_limit -text "Интервал превышения допустимого объёма памяти, сек."
    entry  $frm.ent_max_memory_time_limit -textvariable max_memory_time_limit
    label $frm.lbl_kill_problem_processes -justify left -anchor nw -text "Принудительно завершать проблемные процессы"
    checkbutton $frm.check_kill_problem_processes -variable kill_problem_processes -onvalue yes -offvalue no    
    
    grid $frm.lbl_host -row 0 -column 0 -sticky nw -padx 5 -pady 5
    grid $frm.ent_host -row 0 -column 1 -sticky nsew -padx 5 -pady 5
    grid $frm.lbl_port -row 1 -column 0 -sticky nw -padx 5 -pady 5
    grid $frm.ent_port -row 1 -column 1 -sticky nsew -padx 5 -pady 5
    grid $frm.lbl_name -row 2 -column 0 -sticky nw -padx 5 -pady 5
    grid $frm.ent_name -row 2 -column 1 -sticky nsew -padx 5 -pady 5
    grid $frm.lbl_secure_connect -row 3 -column 0 -sticky nw -padx 5 -pady 5
    grid $frm.cb_security_level -row 3 -column 1 -sticky nsew -padx 5 -pady 5
    grid $frm.lbl_expiration_timeout -row 4 -column 0 -sticky nw -padx 5 -pady 5
    grid $frm.ent_expiration_timeout -row 4 -column 1 -sticky nsew -padx 5 -pady 5
    grid $frm.lbl_session_fault_tolerance_level -row 5 -column 0 -sticky nw -padx 5 -pady 5
    grid $frm.ent_session_fault_tolerance_level -row 5 -column 1 -sticky nsew -padx 5 -pady 5
    grid $frm.lbl_load_balancing_mode -row 6 -column 0 -sticky nw -padx 5 -pady 5
    grid $frm.cb_load_balancing_mode -row 6 -column 1 -sticky nsew -padx 5 -pady 5
    grid $frm.lbl_errors_count_threshold -row 7 -column 0 -sticky nw -padx 5 -pady 5
    grid $frm.ent_errors_count_threshold -row 7 -column 1 -sticky nsew -padx 5 -pady 5
    grid $frm.lbl_processes -row 8 -column 0 -sticky nw -padx 5 -pady 5
    grid $frm.lbl_lifetime_limit -row 9 -column 0 -sticky nw -padx 5 -pady 5
    grid $frm.ent_lifetime_limit -row 9 -column 1 -sticky nsew -padx 5 -pady 5
    grid $frm.lbl_max_memory_size -row 10 -column 0 -sticky nw -padx 5 -pady 5
    grid $frm.ent_max_memory_size -row 10 -column 1 -sticky nsew -padx 5 -pady 5
    grid $frm.lbl_max_memory_time_limit -row 11 -column 0 -sticky nw -padx 5 -pady 5
    grid $frm.ent_max_memory_time_limit -row 11 -column 1 -sticky nsew -padx 5 -pady 5
    grid $frm.lbl_kill_problem_processes -row 12 -column 0 -sticky nw -padx 5 -pady 5
    grid $frm.check_kill_problem_processes -row 12 -column 1 -sticky nw -padx 5 -pady 5
    # переопределяем обработчик
    .add.frm_btn.btn_ok configure -command {
        RunCommand "" "cluster insert 
        --host=[.add.frm.ent_host get] 
        --port=[.add.frm.ent_port get] 
        --name=[.add.frm.ent_name get] 
        --expiration-timeout=$expiration_timeout 
        --lifetime-limit=$lifetime_limit 
        --max-memory-size=$max_memory_size 
        --max-memory-time-limit=$max_memory_time_limit 
        --security-level=$security_level 
        --session-fault-tolerance-level=$session_fault_tolerance_level 
        --load-balancing-mode=$load_balancing_mode 
        --errors-count-threshold=$errors_count_threshold 
        --kill-problem-processes=$kill_problem_processes 
        $auth_agent $host"
        Run::server $tree $host ""
        destroy .add
    }
    return $frm
}

Ha u bapisa khoutu ea lits'ebetso tsena, phapang e bonahala ka mahlo; Ke tla tsepamisa maikutlo ho "Ok" mokhanni oa konopo. Ho Tk, thepa ea likarolo tsa litšoantšo e ka hlakoloa nakong ea ts'ebetso ea lenaneo u sebelisa khetho lokisa. Ka mohlala, taelo ea pele ea ho hlahisa konopo:

ttk::button $frm_btn.btn_ok -image ok_grey_24 -command { }

Empa ka mefuta ea rona, taelo e ipapisitse le ts'ebetso e hlokahalang:

  .add.frm_btn.btn_ok configure -command {
        RunCommand "" "cluster insert 
        --host=[.add.frm.ent_host get] 
        --port=[.add.frm.ent_port get] 
        --name=[.add.frm.ent_name get] 
        --expiration-timeout=$expiration_timeout 
        --lifetime-limit=$lifetime_limit 
        --max-memory-size=$max_memory_size 
        --max-memory-time-limit=$max_memory_time_limit 
        --security-level=$security_level 
        --session-fault-tolerance-level=$session_fault_tolerance_level 
        --load-balancing-mode=$load_balancing_mode 
        --errors-count-threshold=$errors_count_threshold 
        --kill-problem-processes=$kill_problem_processes 
        $auth_agent $host"
        Run::server $tree $host ""
        destroy .add
    }

Mohlala o ka holimo, konopo ea "koaletsoeng" e qala mokhoa oa ho eketsa sehlopha.

Mona ho bohlokoa ho etsa tšitiso mabapi le ho sebetsa le likarolo tsa graphic ho Tk - bakeng sa lintlha tse fapaneng tsa ho kenya data (ho kena, combobox, konopo ea ho hlahloba, joalo-joalo) paramethara e hlahisitsoe e le phapang ea mongolo:

entry  $frm.ent_lifetime_limit -textvariable lifetime_limit

Phapang ena e hlalosoa sebakeng sa mabitso sa lefats'e mme e na le boleng bo kentsoeng hajoale. Tseo. e le hore u fumane mongolo o kentsoeng tšimong, u hloka feela ho bala boleng bo lumellanang le phapang (ehlile, hafeela e hlalosoa ha ho etsoa element).

Mokhoa oa bobeli oa ho khutlisa mongolo o kentsoeng (bakeng sa likarolo tsa mofuta oa ho kena) ke ho sebelisa get command:

.add.frm.ent_name get

Mekhoa ena ka bobeli e ka bonoa khoutu e kaholimo.

Ho tobetsa konopo ena, tabeng ena, ho qala ts'ebetso ea RunCommand ka mohala oa taelo o hlahisitsoeng bakeng sa ho eketsa sehlopha ho latela rac:

/opt/1C/v8.3/x86_64/rac cluster insert  --host=localhost  --port=1540  --name=dsdsds  --expiration-timeout=0  --lifetime-limit=0  --max-memory-size=0  --max-memory-time-limit=0  --security-level=0  --session-fault-tolerance-level=0  --load-balancing-mode=performance  --errors-count-threshold=0  --kill-problem-processes=no   localhost:1545

Hona joale re tla ho taelo e kholo, e laolang ho qalisoa ha rac ka li-parameter tseo re li hlokang, hape e fetisa tlhahiso ea litaelo ka manane le li-return, haeba ho hlokahala:

RunCommand

proc RunCommand {root par} {
    global dir rac_cmd cluster work_list_row_count agent_user agent_pwd cluster_user cluster_pwd
    puts "$rac_cmd $par"
    set work_list_row_count 0
    # открываем канал в неблокирующем режиме
    # $rac - команда с полным путём
    # $par - сформированные ключи запуска и опции    
    set pipe [open "|$rac_cmd $par" "r"]
    try {
        set lst ""
        set l ""
        # вывод команды добавляем в список списков
        while {[gets $pipe line]>=0} {
            #puts $line
            if {$line eq ""} {
                lappend l $lst
                set lst ""
            } else {
                lappend lst [string trim $line]
            }
        }
        close $pipe
        return $l
    } on error {result options} {
        # Запуск обработчика ошибок
        ErrorParcing $result $options
        return ""
    }
}

Ka mor'a ho kenya data ea mantlha ea seva, e tla ekeletsoa sefateng, bakeng sa sena, ho Eketsa ka holimo: ts'ebetso ea seva, khoutu e latelang e ikarabella:

.frm_tree.tree insert {} end -id "server::$host" -text "$host" -values "$host"

Hona joale, ka ho tobetsa lebitso la seva sefateng, re fumana lethathamo la lihlopha tse laoloang ke seva seo, 'me ka ho tobetsa sehlopha, re fumana lethathamo la lihlopha tsa lihlopha (li-server, infobases, joalo-joalo). Sena se kenngoa ts'ebetsong ea TreePress (file lib/function.tcl):

proc TreePress {tree} {
   global host server active_cluster infobase
   # определяем выделенный элемент
    set id  [$tree selection]
   # устанавливаем нужные глобальные переменные
    SetGlobalVarFromTreeItems $tree $id
   # Определяем ключ и значение, т.е. именно тип выбранного элемента
    set values [$tree item $id -values]
    set key [lindex [split $id "::"] 0]
   # и в зависимости от того что выбрали будет запущена соответствующая процедура 
   # в пространстве имён Run
    Run::$key $tree $host $values
}

Ka hona, Run :: seva e tla hlahisoa bakeng sa seva se seholo (bakeng sa sehlopha - Run :: cluster, bakeng sa seva se sebetsang - Run ::work_server, joalo-joalo). Tseo. boleng ba $ key variable ke karolo ea lebitso la sefate se boletsoeng ke khetho -ea.

A re ele hloko mokhoa ona

Matha::seva

proc Run::server {tree host values} {
    # получаем список кластеров требуемого сервера
    set lst [RunCommand server::$host "cluster list $host"]
    if {$lst eq ""} {return}
    set l [lindex $lst 0]
    #puts $lst
    # удаляем лишнее из списка
    .frm_work.tree_work delete  [ .frm_work.tree_work children {}]
    # читаем список
    foreach cluster_list $lst {
        # Заполняем список полученными значениями
        InsertItemsWorkList $cluster_list
        # обрабатываем вывод (список) для добавления данных в дерево
        foreach i $cluster_list {
            #puts $i
            set cluster_list [split $i ":"]
            if  {[string trim [lindex $cluster_list 0]] eq "cluster"} {
                set cluster_id [string trim [lindex $cluster_list 1]]
                lappend cluster($cluster_id) $cluster_id
            }
            if  {[string trim [lindex $cluster_list 0]] eq "name"} {
                lappend  cluster($cluster_id) [string trim [lindex $cluster_list 1]]
            }
        }
    }
    # добавляем кластеры в дерево
    foreach x [array names cluster] {
        set id [lindex $cluster($x) 0]
        if { [$tree exists "cluster::$id"] == 0 } {
            $tree insert "server::$host" end -id "cluster::$id" -text "[lindex $cluster($x) 1]" -values "$id"
            # добавляем элементы в кластер
            InsertClusterItems $tree $id
        }
    }
    if { [$tree exists "agent_admins::$id"] == 0 } {
        $tree insert "server::$host" end -id "agent_admins::$id" -text "Администраторы" -values "$id"
        #InsertClusterItems $tree $id
    }
}

Ts'ebetso ena e sebetsana le se amohetsoeng ho tsoa ho seva ka taelo ea RunCommand mme e eketsa mefuta eohle ea lintho sefateng - lihlopha, likarolo tse fapaneng tsa metso (metheo, li-server tse sebetsang, linako, joalo-joalo). Ha u sheba ka hloko, u tla hlokomela mohala o eang ts'ebetsong ea InsertItemsWorkList ka hare. E sebelisetsoa ho kenyelletsa likarolo lethathamong la litšoantšo ka ho sebetsana le tlhahiso ea rac console utility, eo pele e neng e khutlisetsoa e le lethathamo la $lst variable. Lena ke lethathamo la manane a nang le lipara tsa likarolo tse arohaneng ke kholo.

Ka mohlala, lethathamo la likhokahano tsa lihlopha:

svk@svk ~]$ /opt/1C/v8.3/x86_64/rac connection list --cluster=783d2170-56c3-11e8-c586-fc75165efbb2 localhost:1545
connection     : dcf5991c-7d24-11e8-1690-fc75165efbb2
conn-id        : 0
host           : svk.home
process        : 79de2e16-56c3-11e8-c586-fc75165efbb2
infobase       : 00000000-0000-0000-0000-000000000000
application    : "JobScheduler"
connected-at   : 2018-07-01T14:49:51
session-number : 0
blocked-by-ls  : 0

connection     : b993293a-7d24-11e8-1690-fc75165efbb2
conn-id        : 0
host           : svk.home
process        : 79de2e16-56c3-11e8-c586-fc75165efbb2
infobase       : 00000000-0000-0000-0000-000000000000
application    : "JobScheduler"
connected-at   : 2018-07-01T14:48:52
session-number : 0
blocked-by-ls  : 0

Ka sebopeho sa graphical e tla shebahala tjena:

Ho ngola GUI bakeng sa 1C RAC, kapa hape ka Tcl/Tk

Mokhoa o ka holimo o khetha mabitso a likarolo bakeng sa hlooho le data ho tlatsa tafole:

InsertItemsWorkList

proc InsertItemsWorkList {lst} {
    global work_list_row_count
    # установка чередования цвета для строки
    if [expr $work_list_row_count % 2] {
        set tag dark
    } else {
        set tag light
    }
    # разбор строк на пары ключ - значение
    foreach i $lst {
        if [regexp -nocase -all -- {(D+)(s*?|)(:)(s*?|)(.*)} $i match param v2 v3 v4 value] {
            lappend column_list [string trim $param]
            lappend value_list [string trim $value]
        }
    }
     # заполнение таблицы
    .frm_work.tree_work configure -columns $column_list -displaycolumns $column_list
    .frm_work.tree_work insert {} end  -values $value_list -tags $tag
    .frm_work.tree_work column #0 -stretch
    # установка заголовков
    foreach j $column_list {
        .frm_work.tree_work heading $j -text $j
    }
    incr work_list_row_count
}

Mona, ho e-na le taelo e bonolo [split $str ":"], e arolang khoele hore e be likarolo tse arohaneng ka ":" le ho khutlisetsa lethathamo, ho sebelisoa polelo e tloaelehileng, kaha likarolo tse ling le tsona li na le kholo.

Ts'ebetso ea InsertClusterItems (e 'ngoe ea tse' maloa tse tšoanang) e kenyelletsa feela lethathamo la likarolo tsa bana tse nang le li-identifiers tse tsamaellanang sefateng sa karolo e hlokahalang ea sehlopha.
InsertClusterItems

proc InsertClusterItems {tree id} {
    set parent "cluster::$id"
    $tree insert $parent end -id "infobases::$id" -text "Информационные базы" -values "$id"
    $tree insert $parent end -id "servers::$id" -text "Рабочие серверы" -values "$id"
    $tree insert $parent end -id "admins::$id" -text "Администраторы" -values "$id"
    $tree insert $parent end -id "managers::$id" -text "Менеджеры кластера" -values $id
    $tree insert $parent end -id "processes::$id" -text "Рабочие процессы" -values "workprocess-all"
    $tree insert $parent end -id "sessions::$id" -text "Сеансы" -values "sessions-all"
    $tree insert $parent end -id "locks::$id" -text "Блокировки" -values "blocks-all"
    $tree insert $parent end -id "connections::$id" -text "Соединения" -values "connections-all"
    $tree insert $parent end -id "profiles::$id" -text "Профили безопасности" -values $id
}

U ka nahana ka likhetho tse ling tse peli tsa ho kenya ts'ebetsong ts'ebetso e ts'oanang, moo ho tla bonahala ka ho hlaka hore na u ka ntlafatsa joang le ho tlosa litaelo tse pheta-phetoang:

Ts'ebetsong ena, ho eketsa le ho hlahloba ho rarolloa hang-hang:

InsertBaseItems

proc InsertBaseItems {tree id} {
    set parent "infobase::$id"
    if { [$tree exists "sessions::$id"] == 0 } {
        $tree insert $parent end -id "sessions::$id" -text "Сеансы" -values "$id"
    }
    if { [$tree exists "locks::$id"] == 0 } {
        $tree insert $parent end -id "locks::$id" -text "Блокировки" -values "$id"
    }
    if { [$tree exists "connections::$id"] == 0 } {
        $tree insert $parent end -id "connections::$id" -text "Соединения" -values "$id"
    }
}

Mona ke mokhoa o nepahetseng haholoanyane:

InsertProfileItems

proc InsertProfileItems {tree id} {
    set parent "profile::$id"
    set lst {
        {dir "Виртуальные каталоги"}
        {com "Разрешённые COM-классы"}
        {addin "Внешние компоненты"}
        {module "Внешние отчёты и обработки"}
        {app "Разрешённые приложения"}
        {inet "Ресурсы интернет"}
    }
    foreach i $lst {
        append item [lindex $i 0] "::$id"
        if { [$tree exists $item] == 0 } {
            $tree insert $parent end -id $item -text [lindex $i 1] -values "$id"
        }
        unset item 
    }
}

Phapang lipakeng tsa tsona ke ts'ebeliso ea loop, eo ho eona (li)taelo tse pheta-phetoang li etsoang. Ke mokhoa ofe o ka sebelisoang ho ea ka boikhethelo ba moqapi.

Re kentse lintlha ka ho eketsa lintlha le ho fumana lintlha, joale ke nako ea ho tsepamisa maikutlo ho e lokisa. Kaha, ha e le hantle, li-parameter tse tšoanang li sebelisoa bakeng sa ho hlophisa le ho eketsa (ntle le motheo oa boitsebiso), ho sebelisoa mefuta e tšoanang ea puisano. Algorithm ea ho letsetsa mekhoa ea ho eketsa e shebahala tjena:

Eketsa::$key->AddToplevel

Le ho hlophisa tjena:

Fetola::$key->Kenya::$key->AddTopLevel

Ka mohlala, ha re nke ho hlophisa sehlopha, i.e. Ha u se u tobetse lebitsong la sehlopha se sefateng, tobetsa konopo ea edita ho toolbar (pentšele) 'me foromo e lumellanang e tla hlahisoa skrineng:

Ho ngola GUI bakeng sa 1C RAC, kapa hape ka Tcl/Tk
Fetola::sehlopha

proc Edit::cluster {tree host values} {
    global default lifetime_limit expiration_timeout session_fault_tolerance_level
    global max_memory_size max_memory_time_limit errors_count_threshold security_level
    global load_balancing_mode kill_problem_processes active_cluster 
    agent_user agent_pwd cluster_user cluster_pwd auth
    if {$cluster_user ne "" && $cluster_pwd ne ""} {
        set auth "--cluster-user=$cluster_user --cluster-pwd=$cluster_pwd"
    } else {
        set auth ""
    }
    # рисуем форму для кластера
    set frm [Add::cluster $tree $host $values]
    # меняем текст на метке
    $frm configure -text "Редактирование кластера"
    
    set active_cluster $values
    # получаем данные по выделенному кластеру
    set lst [RunCommand cluster::$values "cluster info --cluster=$active_cluster $host"]
    # заполняем поля
    FormFieldsDataInsert $frm $lst
    # выключаем поля, редактирование которых запрещено
    $frm.ent_host configure -state disable
    $frm.ent_port configure -state disable
    # переназначаем обработчик
    .add.frm_btn.btn_ok configure -command {
        RunCommand "" "cluster update 
        --cluster=$active_cluster $auth 
        --name=[.add.frm.ent_name get] 
        --expiration-timeout=$expiration_timeout 
        --lifetime-limit=$lifetime_limit 
        --max-memory-size=$max_memory_size 
        --max-memory-time-limit=$max_memory_time_limit 
        --security-level=$security_level 
        --session-fault-tolerance-level=$session_fault_tolerance_level 
        --load-balancing-mode=$load_balancing_mode 
        --errors-count-threshold=$errors_count_threshold 
        --kill-problem-processes=$kill_problem_processes 
        $auth $host"
        $tree delete "cluster::$active_cluster"
        Run::server $tree $host ""
        destroy .add
    }
}

Ho latela maikutlo a khoutu, ha e le hantle, ntho e 'ngoe le e' ngoe e hlakile, ntle le hore khoutu ea ho sebetsana le konopo e fetisitsoe 'me ho na le mokhoa oa FormFieldsDataInsert o tlatsang masimo ka data le ho qala mefuta e fapaneng:

FormFieldsDataInsert

proc FormFieldsDataInsert {frm lst} {
    foreach i [lindex $lst 0] {
        # получаем список параметров и значений
        if [regexp -nocase -all -- {(D+)(s*?|)(:)(s*?|)(.*)} $i match param v2 v3 v4 value] {
            # меняем символы
            regsub -all -- "-" [string trim $param] "_" entry_name
            # заполняем данными
            if [winfo exists $frm.ent_$entry_name] {
                $frm.ent_$entry_name delete 0 end
                $frm.ent_$entry_name insert end [string trim $value """]
            }
            if [winfo exists $frm.cb_$entry_name] {
                global $entry_name
                set $entry_name [string trim $value """]
            }
            # для чекбоксов меняем значения
            if [winfo exists $frm.check_$entry_name] {
                global $entry_name
                if {$value eq "0"} {
                    set $entry_name no
                } elseif {$value eq "1"} {
                    set $entry_name yes
                } else {
                    set $entry_name $value
                }
            }
        }
    }
}

Ts'ebetsong ena, monyetla o mong oa tcl o ile oa hlaha - boleng ba mefuta e meng e nkeloa sebaka ke mabitso a fapaneng. Tseo. ho iketsetsa ho tlatsoa ha liforomo le ho qalisoa ha mefuta-futa, mabitso a masimo le mefuta-futa a lumellana le li-switch line tsa taelo ea rac utility le mabitso a li-parameter tsa tlhahiso ea taelo ntle le mokhelo - dash e nkeloa sebaka ke underscore. Mohlala kemiso-mesebetsi- hana e tsamaisanang le lebala ent_scheduled_jobs_deny le ho fetoha hlophisitsoe_mesebetsi_ hana.

Liforomo tsa ho kenyelletsa le ho hlophisa li ka fapana ka sebopeho sa masimo, mohlala, ho sebetsa ka motheo oa tlhahisoleseling:

Ho eketsa tshireletso ya tlhahisoleseding

Ho ngola GUI bakeng sa 1C RAC, kapa hape ka Tcl/Tk

Ho hlophisa ts'ireletso ea tlhahisoleseling

Ho ngola GUI bakeng sa 1C RAC, kapa hape ka Tcl/Tk

Ts'ebetsong ea ho hlophisa Edita::infobase, likarolo tse hlokahalang li kenyellelitsoe foromong; khoutu e ngata, ka hona ha ke e hlahise mona.

Ka papiso, mekhoa ea ho eketsa, ho hlophisa, ho tlosa e sebelisoa bakeng sa likarolo tse ling.

Kaha ts'ebetso ea ts'ebeliso e bolela palo e sa lekanyetsoang ea li-server, lihlopha, metheo ea tlhahisoleseling, joalo-joalo, ho tseba hore na ke sehlopha sefe sa sistimi ea ts'ireletso ea tlhahisoleseling, ho hlahisitsoe mefuta e mengata ea lefats'e, eo boleng ba eona bo behiloeng ka bomong. nako eo o tobetsang ka eona likarolo tsa sefate. Tseo. ts'ebetso e sebetsa ka makhetlo ho likarolo tsohle tsa motsoali mme e beha mefuta e fapaneng:

SetGlobalVarFromTreeItems

proc SetGlobalVarFromTreeItems {tree id} {
    global host server active_cluster infobase
    set parent [$tree parent $id]
    set values [$tree item $id -values]
    set key [lindex [split $id "::"] 0]
    switch -- $key {
        server {set host $values}
        work_server {set server $values}
        cluster {set active_cluster $values}
        infobase {set infobase $values}
    }
    if {$parent eq ""} {
        return
    } else {
        SetGlobalVarFromTreeItems $tree $parent
    }
}

Sehlopha sa 1C se u lumella ho sebetsa ka tumello kapa ntle le tumello. Ho na le mefuta e 'meli ea balaoli-mookameli oa li-cluster agent le mookameli oa lihlopha. Ka hona, bakeng sa ts'ebetso e nepahetseng, ho ile ha hlahisoa mefuta e meng e 4 ea lefats'e e nang le ho kena le password ea motsamaisi. Tseo. haeba ho na le ak'haonte ea motsamaisi sehlopheng, puisano e tla hlahisoa ho kenya lebitso la hau la ho kena le password, data e tla bolokoa mohopolong ebe e kenngoa taelong e 'ngoe le e' ngoe bakeng sa sehlopha se lumellanang.

Ona ke boikarabello ba mokhoa oa ho sebetsana le liphoso.

ErrorParcing

proc ErrorParcing {err opt} {
    global cluster_user cluster_pwd agent_user agent_pwd
        switch -regexp -- $err {
        "Cluster administrator is not authenticated" {
            AuthorisationDialog "Администратор кластера"
            .auth_win.frm_btn.btn_ok configure -command {
                set cluster_user [.auth_win.frm.ent_name get]
                set cluster_pwd [.auth_win.frm.ent_pwd get]
                destroy .auth_win
            }
            #RunCommand $root $par
        }
        "Central server administrator is not authenticated" {
            AuthorisationDialog "Администратор агента кластера"
            .auth_win.frm_btn.btn_ok configure -command {
                set agent_user [.auth_win.frm.ent_name get]
                set agent_pwd [.auth_win.frm.ent_pwd get]
                destroy .auth_win
            }
        }
        "Администратор кластера не аутентифицирован" {
            AuthorisationDialog "Администратор кластера"
            .auth_win.frm_btn.btn_ok configure -command {
                set cluster_user [.auth_win.frm.ent_name get]
                set cluster_pwd [.auth_win.frm.ent_pwd get]
                destroy .auth_win
            }
            #RunCommand $root $par
        }
        "Администратор центрального сервера не аутентифицирован" {
            AuthorisationDialog "Администратор агента кластера"
            .auth_win.frm_btn.btn_ok configure -command {
                set agent_user [.auth_win.frm.ent_name get]
                set agent_pwd [.auth_win.frm.ent_pwd get]
                destroy .auth_win
            }
        }
        (.+) {
            tk_messageBox -type ok -icon error -message "$err"
        }
    }
}

Tseo. ho latela hore na taelo e khutlisa eng, karabelo e tla ba joalo.

Hona joale, hoo e ka bang karolo ea 95 lekholong ea ts'ebetso e se e kentsoe ts'ebetsong, se setseng ke ho kenya ts'ebetsong mosebetsi ka litlaleho tsa ts'ireletso le ho le leka =). Ke phetho. Ke kopa tšoarelo bakeng sa pale e soabaneng.

Khoutu e fumaneha ka moetlo mona.

Ntlafatso: Ke qetile ho sebetsa ka liprofaele tsa ts'ireletso. Hona joale ts'ebetso e sebetsa ka 100%.

Nchafatso ea 2: ho eketsoa ka Senyesemane le Serussia, mosebetsi ho win7 o lekoa
Ho ngola GUI bakeng sa 1C RAC, kapa hape ka Tcl/Tk

Source: www.habr.com

Eketsa ka tlhaloso