Te tuhi GUI mo 1C RAC, mo Tcl/Tk ranei

I a matou e ruku ana ki te kaupapa mo te mahi o nga hua 1C i roto i te taiao Linux, i kitea tetahi raru - ko te kore o te taputapu maha-waahanga kauwhata mo te whakahaere i te roopu o nga tūmau 1C. Na ka whakatauhia kia whakatikahia tenei raru ma te tuhi i te GUI mo te taputapu papatohu rac. I tohua ko Tcl/tk hei reo whanaketanga, ki taku nei whakaaro, ko te reo e tika ana mo tenei mahi. Na, e hiahia ana ahau ki te whakaatu i etahi ahuatanga whakamere o te otinga i roto i tenei rauemi.

Hei mahi ka hiahia koe ki te tohatoha tcl/tk me te 1C. A, i te mea kua whakatau ahau ki te whai i nga kaha o te tuku tcl/tk taketake me te kore e whakamahi i nga kohinga tuatoru, ka hiahia ahau ki te putanga 8.6.7, kei roto ko te ttk - he kete me etahi atu waahanga whakairoiro, e hiahia ana matou ki te ttk. ::TreeView, ka taea e ia te whakaatu raraunga i roto i te ahua o te hanganga rakau me te ahua o te ripanga (rarangi). Ano, i roto i te putanga hou, kua mahi ano te mahi me nga tuunga (te whakahau whakamatau, e whakamahia ana i roto i te kaupapa i te wa e whakahaere ana nga whakahau o waho).

He maha nga konae kei roto i te kaupapa (ahakoa kahore he mea hei aukati i a koe ki te mahi i nga mea katoa ki te kotahi):

rac_gui.cfg - whirihora taunoa
rac_gui.tcl - tuhinga whakarewatanga matua
Kei roto i te whaiaronga lib nga konae ka utaina aunoa i te tiimatanga:
function.tcl - konae me nga tikanga
gui.tcl - atanga kauwhata matua
images.tcl - whare pukapuka whakaahua base64

Ko te konae rac_gui.tcl, ka tiimata te kaiwhakamaori, ka arawhiti i nga taurangi, ka utaina nga waahanga, nga whirihora, me era atu. Nga ihirangi o te konae me nga korero:

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"
    }    
}

I muri i te tango i nga mea katoa e hiahiatia ana me te tirotiro mo te waahi o te taputapu rac, ka whakarewahia he matapihi kauwhata. E toru nga waahanga o te atanga papatono:

Paeutauta, rakau me te rarangi

I hanga e ahau nga ihirangi o te "rakau" kia rite ki nga taputapu Windows paerewa mai i te 1C.

Te tuhi GUI mo 1C RAC, mo Tcl/Tk ranei

Ko te waehere matua hei hanga i tenei matapihi kei roto i te konae
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

Ko te algorithm mo te mahi me te kaupapa e whai ake nei:

1. Tuatahi, me whakauru koe i te tūmau tautau matua (arā, te tūmau whakahaere kāhui (i roto i te Linux, ka whakarewahia te whakahaere me te whakahau “/opt/1C/v8.3/x86_64/ras cluster —daemon”)).

Ki te mahi i tenei, paatohia te paatene "+" a i te matapihi e tuwhera ana, whakauruhia te wahitau tūmau me te tauranga:

Te tuhi GUI mo 1C RAC, mo Tcl/Tk ranei

Muri iho, ka puta mai to maatau tūmau i roto i te rakau ma te panui ki runga, ka tuwhera he rarangi o nga tautau, ka whakaatuhia he hapa hononga ranei.

2. Ma te panui i te ingoa tautau ka whakatuwhera i te rarangi o nga mahi e waatea ana.

rua.…

A pera tonu, i.e. ki te taapiri i tetahi kahui hou, tohua tetahi e waatea ana i te raarangi ka pehi i te paatene "+" i te paeutauta ka whakaatuhia te korero taapiri hou:

Te tuhi GUI mo 1C RAC, mo Tcl/Tk ranei

Ko nga paatene o te paeutauta e mahi ana i nga mahi i runga i te horopaki, i.e. I runga i te ahua o te huānga o te rakau, o te rarangi ranei ka tohua, ka mahia tetahi, tetahi atu tikanga ranei.

Me titiro ki te tauira o te paatene taapiri (“+”):

Waehere whakaputanga paatene:

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

I konei ka kite tatou ka pehia te paatene, ka mahia te tikanga "Tāpiri", ko tana waehere:

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
}

Anei tetahi o nga painga o te tickle: ka taea e koe te tuku i te uara o te taurangi hei ingoa tikanga:

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

Arā, hei tauira, ki te tohu tatou ki te tūmau matua me te pēhi i te "+", katahi ka whakarewahia te tikanga Tāpiri::server, mena kei te tautau - Add::cluster and so on (Ka tuhi ahau mo te waahi o te Ko nga "ki" e tika ana ka ahu mai i te iti o raro), ko nga tikanga kua whakarārangihia e tuhi ana i nga huānga whakairoiro e tika ana ki te horopaki.

Kua kite pea koe, he rite te ahua o nga puka - ehara tenei i te mea miharo, na te mea ka whakaatuhia e te tikanga kotahi, ko te anga matua o te puka (matapihi, paatene, ahua, tapanga), te ingoa o te tikanga. 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
}

Waea tawhā: taitara, ingoa whakaahua mo te ata mai i te whare pukapuka (lib/images.tcl) me tetahi tawhā ingoa matapihi (taunoa .add). Na, ki te tango tatou i nga tauira i runga ake nei mo te taapiri i te tūmau matua me te kāhui, ka rite te piiraa:

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

ranei

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

Ana, ma te haere tonu i enei tauira, ka whakaatu ahau i nga tikanga e whakaatu ana i nga korero taapiri mo te tūmau, te tautau ranei.

Tāpiri::tūmau

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
}

Tāpiri::cluster

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
}

I te whakataurite i te waehere o enei tikanga, ka kitea te rereketanga ki te kanohi tahanga; Ka arotahi ahau ki te kaikawe paatene "Ok". I roto i te Tk, ka taea te whakakore i nga ahuatanga o nga huānga whakairoiro i te wa e mahia ana te papatono ma te whakamahi i te whiringa whirihora. Hei tauira, ko te whakahau tuatahi hei whakaatu i te paatene:

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

Engari i roto i o maatau ahua, ka whakawhirinaki te whakahau ki nga mahi e hiahiatia ana:

  .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
    }

I roto i te tauira i runga ake nei, ka tiimata te paatene "kotia" te tikanga mo te taapiri i te tautau.

I konei he mea tika kia huri ke ki te mahi me nga huānga whakairoiro i Tk - mo nga momo huānga urunga raraunga (whakaurunga, pouaka paheko, patene taki, me etahi atu) kua whakauruhia he tawhā hei taurangi kuputuhi:

entry  $frm.ent_lifetime_limit -textvariable lifetime_limit

Kua tautuhia tenei taurangi ki te mokowāingoa o te ao me te uara kua whakauruhia inaianei. Ko era. ki te tiki i te tuhinga i whakauruhia mai i te mara, me panui noa koe i te uara e pa ana ki te taurangi (ko te tikanga, mena kua tautuhia i te wa e hanga ana te huānga).

Ko te tikanga tuarua mo te tiki mai i te tuhinga kua whakauruhia (mo nga huānga o te momo urunga) ko te whakamahi i te tono tiki:

.add.frm.ent_name get

Ko enei tikanga e rua ka kitea i roto i te waehere o runga.

Ma te paatene i tenei paatene, i tenei keehi, ka whakarewahia te tikanga RunCommand me te raina whakahau i hangaia mo te taapiri i tetahi tautau mo te 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

Inaianei kua tae mai matou ki te whakahau matua, e whakahaere ana i te whakarewatanga o te rac me nga tawhā e hiahiatia ana e matou, ka panuitia hoki te whakaputanga o nga whakahau ki roto i nga rarangi ka hoki mai, ki te hiahiatia:

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 ""
    }
}

I muri i te whakauru i nga raraunga tūmau matua, ka taapirihia ki te rakau, mo tenei, i runga ake nei i te Tāpiri: te mahinga tūmau, ko te waehere e whai ake nei te kawenga:

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

Inaianei, ma te panui i te ingoa tūmau i roto i te rakau, ka whiwhi tatou i te rarangi o nga tautau e whakahaeretia ana e taua tūmau, a, ma te panui i te kohinga, ka whiwhi tatou i te rarangi o nga huinga huinga (tūmau, infobases, etc.). Ka whakatinanahia tenei i roto i te tikanga 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
}

Na, ka whakarewahia te Run::server mo te tūmau matua (mo te tautau - Run::cluster, mo te tūmau mahi - Run::work_server, etc.). Ko era. ko te uara o te taurangi $key he wahanga o te ingoa o te huānga rakau i tohua e te whiringa -id.

Kia whai whakaaro tatou ki te tukanga

Whakahaere::tūmau

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
    }
}

Ka tukatukahia e tenei tikanga nga mea i riro mai i te tūmau na roto i te whakahau RunCommand me te taapiri i nga momo mea katoa ki te rakau - nga tautau, nga momo huanga pakiaka (nga turanga, nga kaitoro mahi, nga huihuinga, me era atu). Mena ka ata titiro koe, ka kite koe i te waea ki te tikanga InsertItemsWorkList i roto. Ka whakamahia hei taapiri i nga huānga ki te rarangi kauwhata ma te tukatuka i te putanga o te taputapu papatohu rac, i whakahokia i mua hei rarangi ki te taurangi $lst. He rarangi rarangi kei roto nga huānga takirua kua wehea e te kopirua.

Hei tauira, he rarangi o nga hononga huinga:

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

I roto i te ahua kauwhata ka penei te ahua:

Te tuhi GUI mo 1C RAC, mo Tcl/Tk ranei

Ko te tikanga i runga ake nei ka kowhiri i nga ingoa o nga huānga mo te pane me nga raraunga hei whakaki i te ripanga:

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
}

I konei, hei utu mo te whakahau ngawari [wehea $str ":"], ka wehewehe i te aho ki nga huānga kua wehea e ":" ka whakahoki mai i te rarangi, ka whakamahia he korero auau, na te mea kei etahi huānga ano he kopirua.

Ko te tikanga InsertClusterItems (tetahi o etahi o nga mea rite) ka taapiri noa i te rarangi o nga huānga tamariki me nga tohu tohu ki te rakau o te huānga tautau e hiahiatia ana
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
}

Ka taea e koe te whakaaro kia rua atu nga whiringa mo te whakatinana i tetahi tikanga rite, ka tino kitea me pehea e taea ai e koe te arotau me te whakakore i nga whakahau tukurua:

I roto i tenei tikanga, ka whakatauhia te taapiri me te arowhai:

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"
    }
}

Anei tetahi huarahi tika ake:

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 
    }
}

Ko te rereketanga i waenga i a raatau ko te whakamahi i te kapiti, ka mahia nga whakahau tukurua. Ko tehea huarahi hei whakamahi ma te kaiwhakawhanake.

Kua hipokina e matou te taapiri i nga huānga me te tiki raraunga, inaianei kua tae ki te aro ki te whakatika. I te mea ko te tikanga, he rite tonu nga tawhā mo te whakatika me te taapiri (haunga te turanga korero), ka whakamahia nga momo korero. Ko te algorithm mo te karanga i nga tikanga mo te taapiri he penei te ahua:

Tāpiri::$key->AddToplevel

A mo te whakatika penei:

Whakatika::$key->Taapiri::$key->AddTopLevel

Hei tauira, me tango tatou ki te whakatika i tetahi tautau, i.e. Ka paatohia te ingoa o te tautau i roto i te rakau, pehia te paatene whakatika i te paeutauta (pene) ka whakaatuhia te puka e rite ana ki te mata:

Te tuhi GUI mo 1C RAC, mo Tcl/Tk ranei
Whakatika::cluster

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
    }
}

I runga i nga korero i roto i te waehere, i runga i te kaupapa, he maamaa nga mea katoa, engari ko te waehere kaihautu paatene kua whakakorehia, kei reira he tikanga FormFieldsDataInsert e whakaki ana i nga mara ki nga raraunga me te timata i nga taurangi:

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
                }
            }
        }
    }
}

I tenei tikanga, ka puta mai tetahi atu painga o te tcl - ko nga uara o etahi atu taurangi ka whakakapihia hei ingoa rereke. Ko era. ki te whakakī aunoa i nga puka me te arawhitinga o nga taurangi, ko nga ingoa o nga mara me nga taurangi e rite ana ki nga huringa raina whakahau o te whaipainga rac me nga ingoa o nga tawhā whakaputa whakahau me etahi atu - ka whakakapihia te taarua e te tohu raro. Hei tauira kua whakaritea-mahi-whakakahore e rite ana ki te mara ent_scheduled_jobs_deny me te taurangi kua whakaritea_mahi_whakakahore.

Ko nga puka hei taapiri me te whakatika ka rereke pea i te hanganga o nga mara, hei tauira, te mahi me te turanga korero:

Te taapiri i te haumarutanga korero

Te tuhi GUI mo 1C RAC, mo Tcl/Tk ranei

Te whakatika i te haumarutanga korero

Te tuhi GUI mo 1C RAC, mo Tcl/Tk ranei

I roto i te tikanga whakatika Whakatika::infobase, ka taapirihia nga mara e hiahiatia ana ki te puka; he nui te waehere, na reira kaore au e whakaatu ki konei.

Ma te whakataurite, ka whakatinanahia nga tikanga mo te taapiri, te whakatika, te whakakore mo etahi atu waahanga.

Mai i te mea ko te mahi o te whaipainga e kii ana i te maha o nga kaitoro, tautau, turanga korero, me era atu, hei whakatau ko tehea te tautau no te punaha haumarutanga korero ranei, he maha nga taurangi o te ao kua whakauruhia, ko nga uara kua whakaritea mo ia. te wa ka panui koe i nga huānga o te rakau. Ko era. ka haere hoki te tukanga i roto i nga huānga matua katoa me te tautuhi i nga taurangi:

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
    }
}

Ko te roopu 1C ka taea e koe te mahi me te kore whakaaetanga ranei. E rua nga momo kaiwhakahaere—te kaiwhakahaere a te roopu roopu me te kaiwhakahaere roopu. Na reira, mo te mahi tika, e 4 atu nga taurangi o te ao i whakaurua kei roto te takiuru a te kaiwhakahaere me te kupuhipa. Ko era. mena he kaute kaiwhakahaere kei roto i te roopu, ka whakaatuhia he korero hei whakauru i to takiuru me to kupuhipa, ka tiakina nga raraunga ki roto i te mahara ka whakauruhia ki ia whakahau mo te roopu e rite ana.

Koinei te kawenga o te tikanga whakahaere hapa.

HapaParcing

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"
        }
    }
}

Ko era. i runga ano i ta te whakahau e whakahoki mai, ka pera ano te tauhohenga.

I tenei wa, tata ki te 95 ōrau o te mahi kua whakatinanahia, ko nga mea katoa e toe ana ko te whakatinana i nga mahi me nga tuhinga haumaru me te whakamatautau =). Heoi ano. Ka mihi ahau mo te korero mokemoke.

Kei te waatea te waehere konei.

Whakahoutanga: I mutu taku mahi me nga korero haumaru. Inaianei kua 100% te whakatinanatanga o te mahi.

Whakahoutanga 2: kua taapirihia te waahi ki te reo Ingarihi me te Ruhia, kua whakamatauria te mahi i roto i te win7
Te tuhi GUI mo 1C RAC, mo Tcl/Tk ranei

Source: will.com

Tāpiri i te kōrero